diff --git a/Cargo.lock b/Cargo.lock index 2151630..e2ed194 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -139,6 +139,16 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "cc" +version = "1.2.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -191,6 +201,22 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -280,12 +306,33 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "generic-array" version = "0.14.7" @@ -401,6 +448,23 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "native-tls" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8614eb2c83d59d1c8cc974dd3f920198647674a0a035e1af1fa58707e317466" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -411,12 +475,68 @@ dependencies = [ "libm", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "once_cell_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl" +version = "0.10.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f9e8deee91df40a943c71b917e5874b951d32a802526c85721ce3b776c929d6" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + [[package]] name = "portable-atomic" version = "1.13.1" @@ -578,6 +698,38 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "serde" version = "1.0.228" @@ -632,6 +784,12 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "strsim" version = "0.10.0" @@ -693,6 +851,7 @@ dependencies = [ "http", "httparse", "log", + "native-tls", "rand", "sha1", "thiserror", @@ -729,6 +888,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index 0eabfc8..0bcd4e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,12 +22,16 @@ clap = { version = "=4.4.18", features = ["derive"] } anyhow = "1.0" log = "0.4" env_logger = "0.11" -tungstenite = "0.24" +tungstenite = { version = "0.24", features = ["native-tls"] } [[bin]] name = "browser-connection" path = "src/bin/browser-connection.rs" +[[bin]] +name = "browser-connection-relay" +path = "src/bin/browser-connection-relay.rs" + [dev-dependencies] tempfile = "=3.10.1" proptest = "=1.4.0" diff --git a/README.md b/README.md index 88de6db..d7e7528 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Installs two binaries: ```text docker-git-browser-connection # start/status browser container browser-connection # MCP stdio server for Codex/Hermes +browser-connection-relay # WebSocket relay for browser share links ``` ## Start browser manually @@ -46,6 +47,129 @@ args = ["--project", "dg-my-project"] ``` Use `browser-connection`, not `npx @playwright/mcp`. The MCP server starts/reuses the same Rust-managed browser container automatically. +It also starts a local browser/noVNC control panel by default; `browser_list` reports its +`controlPanelUrl`. + +Optional panel controls: + +```toml +[mcp_servers.playwright] +command = "browser-connection" +args = ["--project", "dg-my-project", "--control-port", "6888"] +``` + +Use `--no-control-panel` for headless tests or when another process owns the chosen port. + +## Share a remote Edge by link + +For a remote Microsoft Edge where you do not want SSH, VPN, or an exposed CDP port, use the Edge +share extension plus the relay: + +```bash +browser-connection-relay --bind 127.0.0.1:8765 +``` + +In Edge, load `extension/edge-share` as an unpacked extension, open the extension popup, keep the +relay URL as `http://127.0.0.1:8765` for local testing or set your hosted relay URL, then click +`Share` and copy the link. + +Open the `browser-connection` control panel (`controlPanelUrl` from `browser_list`), paste the link +into `Shared Link`, and add it as `edge`. The target appears as `kind=shared-extension`; selecting +it makes MCP tools route through the extension session instead of a CDP port: + +```toml +[mcp_servers.playwright] +command = "browser-connection" +args = [ + "--project", "dg-my-project", + "--browser-share", "edge=https://relay.example/share/session#agent=token", + "--active-browser", "managed", +] +``` + +The share link is a bearer credential. Anyone with the link can control that shared session until +the user clicks `Stop` in the extension or the relay session is removed. Extension sharing supports +common browser tools such as navigate, snapshot, evaluate, click, type, key press, and screenshot, +but it is not full CDP/VNC parity and protected Edge pages may reject actions. + +### Connect Edge from the noVNC control panel + +The control panel can also act as the connection page. Install the Edge share extension, then open +the `controlPanelUrl` in that Edge. The page detects `window.browserConnection`, opens the +extension approval window, and registers the returned `shareUrl` into the current +`browser-connection` runtime through `/api/share`. + +This mode uses the control panel origin as the relay URL, so a separate +`browser-connection-relay` process is not required for the current workspace. If Edge runs on +another machine, expose the control panel only through an authenticated platform proxy or private +tunnel that forwards HTTP and WebSocket upgrade to the same origin; the panel token is CSRF +protection for the UI, not public authentication. + +## Personal browser + +You can attach an already running desktop Chrome/Chromium browser if it exposes a CDP port. +When `browser-connection` runs inside Docker, use a host-reachable address such as +`host.docker.internal`, not `127.0.0.1`. + +```bash +google-chrome \ + --remote-debugging-address=0.0.0.0 \ + --remote-debugging-port=9222 \ + --user-data-dir="$HOME/.browser-connection-personal" \ + --no-first-run +``` + +To also view that desktop browser through noVNC, expose the host desktop/browser through VNC: + +```bash +x11vnc -display :0 -rfbport 5900 -listen 0.0.0.0 -nopw -forever -shared +``` + +Then register both the CDP endpoint and the VNC display endpoint: + +```toml +[mcp_servers.playwright] +command = "browser-connection" +args = [ + "--project", "dg-my-project", + "--personal-browser", "http://host.docker.internal:9222", + "--personal-vnc", "host.docker.internal:5900", +] +``` + +Multiple browser targets can be configured and switched at runtime. This example starts on the +Docker-managed noVNC browser and keeps the personal browser ready in the noVNC control panel: + +```toml +[mcp_servers.playwright] +command = "browser-connection" +args = [ + "--project", "dg-my-project", + "--browser", "personal=http://host.docker.internal:9222", + "--browser-vnc", "personal=host.docker.internal:5900", + "--browser", "work=http://127.0.0.1:9333", + "--active-browser", "managed", +] +``` + +Environment alternatives: + +```bash +export BROWSER_CONNECTION_PERSONAL_CDP_ENDPOINT=http://host.docker.internal:9222 +export BROWSER_CONNECTION_PERSONAL_VNC_ENDPOINT=host.docker.internal:5900 +export BROWSER_CONNECTION_BROWSERS=work=http://127.0.0.1:9333 +export BROWSER_CONNECTION_BROWSER_VNCS=work=host.docker.internal:5901 +export BROWSER_CONNECTION_BROWSER_SHARES=edge=https://relay.example/share/session#agent=token +export BROWSER_CONNECTION_ACTIVE_BROWSER=managed +``` + +`browser_list` reports each target's `cdpEndpoint`, `vncEndpoint`, `novncUrl`, and `shareUrl`. If a +target has a VNC endpoint but no explicit noVNC URL, `browser_select` starts a lightweight noVNC +proxy for that target unless `--no-start-browser` is set. + +Open the reported `controlPanelUrl` to choose `managed`, `personal`, or any configured browser from +the noVNC UI. The same `browser-connection` process keeps running, and MCP browser tools use the new +active target on the next tool call. ## Hermes MCP config @@ -60,6 +184,58 @@ mcp_servers: connect_timeout: 60 ``` +## CLI browser automation + +Use `rbc` when an agent should drive the browser with normal commands instead of MCP tool +calls. It can target a browser by name from the configured browser pool, a shared Edge extension +link, a direct CDP endpoint, or the active browser from the `browser-connection` control panel. A +platform can set `BROWSER_CONNECTION_CONTROL_URL` so agents can use browser names without knowing +the underlying share link. + +```bash +rbc edge snapshot +rbc edge navigate https://example.com +rbc edge click 'button[type="submit"]' +rbc edge type 'input[name="q"]' 'search text' +rbc edge key Enter +rbc edge eval 'document.title' +rbc edge eval --file /tmp/browser-task.js +rbc edge pw --code 'return await page.title()' +rbc edge pw /tmp/playwright-task.js +rbc edge screenshot --full-page --output /tmp/page.png +rbc edge tabs +rbc edge activate-tab 123 +rbc chromium snapshot +rbc active pw --code 'return await page.title()' +``` + +Direct targets bypass the control panel: + +```bash +rbc edge --share-url "$EDGE_SHARE_URL" snapshot +rbc chromium --cdp-url http://127.0.0.1:9223 snapshot +rbc edge --control-url https://executive-fri-sea-lets.trycloudflare.com snapshot +``` + +Add `--json` for machine-readable output and `--trace-dir .browser-trace` to append +`rbc.jsonl` audit events. `rbc tools snapshot` is also accepted when a caller wants an +explicit `tools` namespace. If no matching browser is found in the configured pool, the first +argument is treated as the legacy docker-git project id and `rbc` falls back to that project's local +CDP/control-panel ports. + +`rbc pw` uses real Playwright through `chromium.connectOverCDP` for CDP-backed Chromium/Edge +targets. For Edge extension share links it sends the script to the extension and runs it with the +bundled Playwright CRX runtime against the selected tab. Shared-extension scripts should use the +Playwright Test action shape generated by the recorder; a bare `--code` body is wrapped into +`test('rbc', async ({ page }) => { ... })` before it is sent to the extension. Unsupported CRX +actions fail with the extension runtime error. + +```js +// /tmp/playwright-task.js +await page.goto("https://example.com"); +return { title: await page.title(), url: page.url() }; +``` + ## MCP tools ```text @@ -70,8 +246,16 @@ browser_click(selector) browser_type(selector, text) browser_press_key(key) browser_take_screenshot(full_page?) +browser_list() +browser_select(name, cdp_endpoint?, vnc_endpoint?, novnc_url?, share_url?) ``` +The noVNC control panel is the interactive switcher. Use `browser_select` with `name=managed` to +return to the Rust-managed noVNC/CDP browser, or with +`name=personal`, `cdp_endpoint=http://host.docker.internal:9222`, and +`vnc_endpoint=host.docker.internal:5900` to connect a personal browser without restarting the MCP +server. + ## Smoke test ```bash diff --git a/artifacts/README.md b/artifacts/README.md new file mode 100644 index 0000000..72a3b84 --- /dev/null +++ b/artifacts/README.md @@ -0,0 +1,17 @@ +# Downloadable Artifacts + +## Edge share extension + +Download `edge-share-extension.zip` or `edge-share-extension.tar.gz`, extract it, +then open Edge: + +```text +edge://extensions +``` + +Enable `Developer mode`, choose `Load unpacked`, and select the extracted +`edge-share` folder. + +Open the `browser-connection` control panel in Edge to approve an automatic +connection into the current browser pool. The popup/manual mode is still +available for hosted `browser-connection-relay` share links. diff --git a/artifacts/edge-share-extension.tar.gz b/artifacts/edge-share-extension.tar.gz new file mode 100644 index 0000000..31e7a39 Binary files /dev/null and b/artifacts/edge-share-extension.tar.gz differ diff --git a/artifacts/edge-share-extension.zip b/artifacts/edge-share-extension.zip new file mode 100644 index 0000000..bd28526 Binary files /dev/null and b/artifacts/edge-share-extension.zip differ diff --git a/artifacts/edge-share.zip b/artifacts/edge-share.zip new file mode 100644 index 0000000..2963faa Binary files /dev/null and b/artifacts/edge-share.zip differ diff --git a/changelog.d/20260624_071400_personal_browser_targets.md b/changelog.d/20260624_071400_personal_browser_targets.md new file mode 100644 index 0000000..a3fc29b --- /dev/null +++ b/changelog.d/20260624_071400_personal_browser_targets.md @@ -0,0 +1,9 @@ +--- +bump: minor +--- + +### Added +- Add named MCP browser targets so agents can connect to a personal CDP browser and switch between personal, external, and Rust-managed browser sessions at runtime. +- Add optional VNC/noVNC display metadata for browser targets, including a Docker-managed noVNC proxy for host personal browsers. +- Add a local noVNC control panel for choosing the active browser target while one `browser-connection` MCP process keeps running. +- Add link-based shared browser targets through an Edge extension, `browser-connection-relay`, and `--browser-share NAME=URL`. diff --git a/changelog.d/20260625_000000_rbc_cli.md b/changelog.d/20260625_000000_rbc_cli.md new file mode 100644 index 0000000..3a3efc0 --- /dev/null +++ b/changelog.d/20260625_000000_rbc_cli.md @@ -0,0 +1,7 @@ +--- +bump: minor +--- + +### Added +- Added `rbc` for browser automation through CLI commands without MCP, including browser-pool names, legacy project-first calls, direct CDP/shared-extension targets, JSON output, screenshots, tab control, and JSONL traces. +- Added `rbc pw` for running Playwright scripts against CDP-backed Chromium/Edge targets and a Playwright-compatible subset against shared Edge extension targets. diff --git a/changelog.d/20260625_124424_control_panel_redesign.md b/changelog.d/20260625_124424_control_panel_redesign.md new file mode 100644 index 0000000..e0b3be5 --- /dev/null +++ b/changelog.d/20260625_124424_control_panel_redesign.md @@ -0,0 +1,11 @@ +--- +bump: patch +--- + +### Changed + +- Redesigned the browser control panel with clearer target status, shared Edge activity, screenshot history, action logs, and filterable window/tab inventory. +- Added a searchable agent action timeline with status counts, stable action IDs, expandable details, and screenshot jump links. +- Added an Edge extension action recorder with popup Record/Stop controls, shared relay sync, and Playwright-like script export in the control panel. +- Added Playwright CRX-inspired recorder modes with Inspect selector preview, floating step list, and replay of recorded actions through the shared Edge relay. +- Added a full Playwright CRX fork artifact integrated with Browser Connection relay sharing and platform-triggered browser pool connection. diff --git a/extension/edge-share-crx/PLAYWRIGHT_CRX_LICENSE b/extension/edge-share-crx/PLAYWRIGHT_CRX_LICENSE new file mode 100644 index 0000000..717e848 --- /dev/null +++ b/extension/edge-share-crx/PLAYWRIGHT_CRX_LICENSE @@ -0,0 +1,203 @@ + 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. + + Portions Copyright (c) Rui Figueira. + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 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. diff --git a/extension/edge-share-crx/PLAYWRIGHT_CRX_NOTICE b/extension/edge-share-crx/PLAYWRIGHT_CRX_NOTICE new file mode 100644 index 0000000..a132ddb --- /dev/null +++ b/extension/edge-share-crx/PLAYWRIGHT_CRX_NOTICE @@ -0,0 +1,5 @@ +Playwright CRX +Copyright (c) Rui Figueira + +This software contains code derived from the Playwright project (https://github.com/microsoft/playwright), +available under the Apache 2.0 license (https://github.com/microsoft/playwright/blob/master/LICENSE). diff --git a/extension/edge-share-crx/README.md b/extension/edge-share-crx/README.md new file mode 100644 index 0000000..ef1b50f --- /dev/null +++ b/extension/edge-share-crx/README.md @@ -0,0 +1,29 @@ +# Browser Connection Playwright CRX + +This directory contains the installable Edge/Chrome extension built from +`ruifigueira/playwright-crx` recorder sources and integrated with the +`browser-connection` relay. + +Upstream project: https://github.com/ruifigueira/playwright-crx + +## What is included + +- Playwright CRX recorder/player UI, side panel, shortcuts, context menu, and + options page. +- Browser Connection provider bridge exposed to web pages as + `window.browserConnection`. +- Browser relay WebSocket client used by the control panel and `rbc` tools. + +## Install + +1. Open `edge://extensions`. +2. Enable Developer mode. +3. Click `Load unpacked`. +4. Select this directory after unpacking the release archive. + +## Notes + +- The extension action button is reserved for Playwright CRX recorder attach, + so Browser Connection sharing is triggered from the platform page. +- Apache-2.0 upstream attribution is preserved in + `PLAYWRIGHT_CRX_LICENSE` and `PLAYWRIGHT_CRX_NOTICE`. diff --git a/extension/edge-share-crx/background.js b/extension/edge-share-crx/background.js new file mode 100644 index 0000000..4f35055 --- /dev/null +++ b/extension/edge-share-crx/background.js @@ -0,0 +1,143484 @@ +import { l as loadSettings, a as addSettingsChangedListener, d as defaultSettings } from "./settings.js"; +var define_process_env_default = {}; +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value; +var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value); +var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" })); +} +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} +function getAugmentedNamespace(n) { + if (Object.prototype.hasOwnProperty.call(n, "__esModule")) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a2() { + if (this instanceof a2) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, "__esModule", { value: true }); + Object.keys(n).forEach(function(k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function() { + return n[k]; + } + }); + }); + return a; +} +var browser$j = { exports: {} }; +var hasRequiredBrowser$j; +function requireBrowser$j() { + if (hasRequiredBrowser$j) return browser$j.exports; + hasRequiredBrowser$j = 1; + var process2 = browser$j.exports = {}; + var cachedSetTimeout; + var cachedClearTimeout; + function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); + } + function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + if (typeof setTimeout === "function") { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === "function") { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + })(); + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); + } + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e2) { + return cachedSetTimeout.call(this, fun, 0); + } + } + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); + } + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + return cachedClearTimeout(marker); + } catch (e) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e2) { + return cachedClearTimeout.call(this, marker); + } + } + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + process2.nextTick = function(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function() { + this.fun.apply(null, this.array); + }; + process2.title = "browser"; + process2.browser = true; + process2.env = {}; + process2.argv = []; + process2.version = ""; + process2.versions = {}; + function noop2() { + } + process2.on = noop2; + process2.addListener = noop2; + process2.once = noop2; + process2.off = noop2; + process2.removeListener = noop2; + process2.removeAllListeners = noop2; + process2.emit = noop2; + process2.prependListener = noop2; + process2.prependOnceListener = noop2; + process2.listeners = function(name) { + return []; + }; + process2.binding = function(name) { + throw new Error("process.binding is not supported"); + }; + process2.cwd = function() { + return "/"; + }; + process2.chdir = function(dir) { + throw new Error("process.chdir is not supported"); + }; + process2.umask = function() { + return 0; + }; + return browser$j.exports; +} +var browserExports$4 = requireBrowser$j(); +const process$2 = /* @__PURE__ */ getDefaultExportFromCjs(browserExports$4); +process$2.hrtime = (previousTimestamp) => { + const baseNow = Math.floor((Date.now() - performance.now()) * 1e-3); + const clocktime = performance.now() * 1e-3; + let seconds = Math.floor(clocktime) + baseNow; + let nanoseconds = Math.floor(clocktime % 1 * 1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds, nanoseconds]; +}; +process$2.platform = "linux"; +process$2.versions.node = "18.16"; +process$2.stdout = { isTTY: "false" }; +process$2.geteuid = () => ""; +process$2.env["PLAYWRIGHT_BROWSERS_PATH"] = "."; +self.process = process$2; +var setImmediate$2 = {}; +var hasRequiredSetImmediate$1; +function requireSetImmediate$1() { + if (hasRequiredSetImmediate$1) return setImmediate$2; + hasRequiredSetImmediate$1 = 1; + (function(global2, undefined$1) { + if (global2.setImmediate) { + return; + } + var nextHandle = 1; + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global2.document; + var registerImmediate; + function setImmediate2(callback) { + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + var task = { callback, args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined$1, args); + break; + } + } + function runIfPresent(handle) { + if (currentlyRunningATask) { + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function() { + runIfPresent(handle); + }); + }; + } + function canUsePostMessage() { + if (global2.postMessage && !global2.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global2.onmessage; + global2.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global2.postMessage("", "*"); + global2.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + function installPostMessageImplementation() { + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global2 && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + if (global2.addEventListener) { + global2.addEventListener("message", onGlobalMessage, false); + } else { + global2.attachEvent("onmessage", onGlobalMessage); + } + registerImmediate = function(handle) { + global2.postMessage(messagePrefix + handle, "*"); + }; + } + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + var script = doc.createElement("script"); + script.onreadystatechange = function() { + runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + }; + } + function installSetTimeoutImplementation() { + registerImmediate = function(handle) { + setTimeout(runIfPresent, 0, handle); + }; + } + var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global2); + attachTo = attachTo && attachTo.setTimeout ? attachTo : global2; + if ({}.toString.call(global2.process) === "[object process]") { + installNextTickImplementation(); + } else if (canUsePostMessage()) { + installPostMessageImplementation(); + } else if (global2.MessageChannel) { + installMessageChannelImplementation(); + } else if (doc && "onreadystatechange" in doc.createElement("script")) { + installReadyStateChangeImplementation(); + } else { + installSetTimeoutImplementation(); + } + attachTo.setImmediate = setImmediate2; + attachTo.clearImmediate = clearImmediate; + })(typeof self === "undefined" ? typeof commonjsGlobal === "undefined" ? setImmediate$2 : commonjsGlobal : self); + return setImmediate$2; +} +requireSetImmediate$1(); +self.setImmediate = setImmediate; +var buffer$3 = {}; +var base64Js = {}; +var hasRequiredBase64Js; +function requireBase64Js() { + if (hasRequiredBase64Js) return base64Js; + hasRequiredBase64Js = 1; + base64Js.byteLength = byteLength; + base64Js.toByteArray = toByteArray; + base64Js.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i2; + for (i2 = 0; i2 < len2; i2 += 4) { + tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i2 = start; i2 < end; i2 += 3) { + tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { + parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); + } + return base64Js; +} +var ieee754 = {}; +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +var hasRequiredIeee754; +function requireIeee754() { + if (hasRequiredIeee754) return ieee754; + hasRequiredIeee754 = 1; + ieee754.read = function(buffer2, offset2, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer2[offset2 + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer2[offset2 + i], i += d, nBits -= 8) { + } + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer2[offset2 + i], i += d, nBits -= 8) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + ieee754.write = function(buffer2, value, offset2, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer2[offset2 + i] = m & 255, i += d, m /= 256, mLen -= 8) { + } + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer2[offset2 + i] = e & 255, i += d, e /= 256, eLen -= 8) { + } + buffer2[offset2 + i - d] |= s * 128; + }; + return ieee754; +} +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +var hasRequiredBuffer$2; +function requireBuffer$2() { + if (hasRequiredBuffer$2) return buffer$3; + hasRequiredBuffer$2 = 1; + (function(exports) { + const base64 = requireBase64Js(); + const ieee7542 = requireIeee754(); + const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports.Buffer = Buffer2; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + const K_MAX_LENGTH = 2147483647; + exports.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) return void 0; + return this.byteOffset; + } + }); + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } + const buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe(arg); + } + return from2(arg, encodingOrOffset, length); + } + Buffer2.poolSize = 8192; + function from2(value, encodingOrOffset, length) { + if (typeof value === "string") { + return fromString(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer2.from(valueOf, encodingOrOffset, length); + } + const b = fromObject(value); + if (b) return b; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + Buffer2.from = function(value, encodingOrOffset, length) { + return from2(value, encodingOrOffset, length); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding2) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding2 === "string" ? createBuffer(size).fill(fill, encoding2) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding2) { + return alloc(size, fill, encoding2); + }; + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe(size); + }; + function fromString(string2, encoding2) { + if (typeof encoding2 !== "string" || encoding2 === "") { + encoding2 = "utf8"; + } + if (!Buffer2.isEncoding(encoding2)) { + throw new TypeError("Unknown encoding: " + encoding2); + } + const length = byteLength(string2, encoding2) | 0; + let buf = createBuffer(length); + const actual = buf.write(string2, encoding2); + if (actual !== length) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length); + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length === void 0) { + buf = new Uint8Array(array); + } else if (length === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length) { + if (length >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length | 0; + } + function SlowBuffer(length) { + if (+length != length) { + length = 0; + } + return Buffer2.alloc(+length); + } + Buffer2.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer2.prototype; + }; + Buffer2.compare = function compare2(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength); + if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a === b) return 0; + let x = a.length; + let y = b.length; + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding2) { + switch (String(encoding2).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + Buffer2.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + let i; + if (length === void 0) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + const buffer2 = Buffer2.allocUnsafe(length); + let pos = 0; + for (i = 0; i < list.length; ++i) { + let buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer2.length) { + if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf); + buf.copy(buffer2, pos); + } else { + Uint8Array.prototype.set.call( + buffer2, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer2, pos); + } + pos += buf.length; + } + return buffer2; + }; + function byteLength(string2, encoding2) { + if (Buffer2.isBuffer(string2)) { + return string2.length; + } + if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { + return string2.byteLength; + } + if (typeof string2 !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 + ); + } + const len = string2.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding2) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string2).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string2).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string2).length; + } + encoding2 = ("" + encoding2).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength; + function slowToString(encoding2, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding2) encoding2 = "utf8"; + while (true) { + switch (encoding2) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding2); + encoding2 = (encoding2 + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; + } + Buffer2.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString2() { + const length = this.length; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals2(b) { + if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer2.compare(this, b) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + let str = ""; + const max2 = exports.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max2) str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare2(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + let x = thisEnd - thisStart; + let y = end - start; + const len = Math.min(x, y); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + function bidirectionalIndexOf(buffer2, val, byteOffset, encoding2, dir) { + if (buffer2.length === 0) return -1; + if (typeof byteOffset === "string") { + encoding2 = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer2.length - 1; + } + if (byteOffset < 0) byteOffset = buffer2.length + byteOffset; + if (byteOffset >= buffer2.length) { + if (dir) return -1; + else byteOffset = buffer2.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding2); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer2, val, byteOffset, encoding2, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset); + } + } + return arrayIndexOf(buffer2, [val], byteOffset, encoding2, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding2, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding2 !== void 0) { + encoding2 = String(encoding2).toLowerCase(); + if (encoding2 === "ucs2" || encoding2 === "ucs-2" || encoding2 === "utf16le" || encoding2 === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read2(buf, i2) { + if (indexSize === 1) { + return buf[i2]; + } else { + return buf.readUInt16BE(i2 * indexSize); + } + } + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read2(arr, i) === read2(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j = 0; j < valLength; j++) { + if (read2(arr, i + j) !== read2(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding2) { + return this.indexOf(val, byteOffset, encoding2) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding2) { + return bidirectionalIndexOf(this, val, byteOffset, encoding2, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding2) { + return bidirectionalIndexOf(this, val, byteOffset, encoding2, false); + }; + function hexWrite(buf, string2, offset2, length) { + offset2 = Number(offset2) || 0; + const remaining = buf.length - offset2; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + const strLen = string2.length; + if (length > strLen / 2) { + length = strLen / 2; + } + let i; + for (i = 0; i < length; ++i) { + const parsed = parseInt(string2.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset2 + i] = parsed; + } + return i; + } + function utf8Write(buf, string2, offset2, length) { + return blitBuffer(utf8ToBytes(string2, buf.length - offset2), buf, offset2, length); + } + function asciiWrite(buf, string2, offset2, length) { + return blitBuffer(asciiToBytes(string2), buf, offset2, length); + } + function base64Write(buf, string2, offset2, length) { + return blitBuffer(base64ToBytes(string2), buf, offset2, length); + } + function ucs2Write(buf, string2, offset2, length) { + return blitBuffer(utf16leToBytes(string2, buf.length - offset2), buf, offset2, length); + } + Buffer2.prototype.write = function write2(string2, offset2, length, encoding2) { + if (offset2 === void 0) { + encoding2 = "utf8"; + length = this.length; + offset2 = 0; + } else if (length === void 0 && typeof offset2 === "string") { + encoding2 = offset2; + length = this.length; + offset2 = 0; + } else if (isFinite(offset2)) { + offset2 = offset2 >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding2 === void 0) encoding2 = "utf8"; + } else { + encoding2 = length; + length = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset2; + if (length === void 0 || length > remaining) length = remaining; + if (string2.length > 0 && (length < 0 || offset2 < 0) || offset2 > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding2) encoding2 = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding2) { + case "hex": + return hexWrite(this, string2, offset2, length); + case "utf8": + case "utf-8": + return utf8Write(this, string2, offset2, length); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string2, offset2, length); + case "base64": + return base64Write(this, string2, offset2, length); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string2, offset2, length); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding2); + encoding2 = ("" + encoding2).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + const MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + let out = ""; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + if (end < start) end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset2, ext, length) { + if (offset2 % 1 !== 0 || offset2 < 0) throw new RangeError("offset is not uint"); + if (offset2 + ext > length) throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset2, byteLength2, noAssert) { + offset2 = offset2 >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) checkOffset(offset2, byteLength2, this.length); + let val = this[offset2]; + let mul = 1; + let i = 0; + while (++i < byteLength2 && (mul *= 256)) { + val += this[offset2 + i] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset2, byteLength2, noAssert) { + offset2 = offset2 >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset2, byteLength2, this.length); + } + let val = this[offset2 + --byteLength2]; + let mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset2 + --byteLength2] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 1, this.length); + return this[offset2]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + return this[offset2] | this[offset2 + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + return this[offset2] << 8 | this[offset2 + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return (this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16) + this[offset2 + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return this[offset2] * 16777216 + (this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]); + }; + Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const lo = first + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 24; + const hi = this[++offset2] + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); + }); + Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const hi = first * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + this[++offset2]; + const lo = this[++offset2] * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + last; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }); + Buffer2.prototype.readIntLE = function readIntLE(offset2, byteLength2, noAssert) { + offset2 = offset2 >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) checkOffset(offset2, byteLength2, this.length); + let val = this[offset2]; + let mul = 1; + let i = 0; + while (++i < byteLength2 && (mul *= 256)) { + val += this[offset2 + i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset2, byteLength2, noAssert) { + offset2 = offset2 >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) checkOffset(offset2, byteLength2, this.length); + let i = byteLength2; + let mul = 1; + let val = this[offset2 + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset2 + --i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 1, this.length); + if (!(this[offset2] & 128)) return this[offset2]; + return (255 - this[offset2] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + const val = this[offset2] | this[offset2 + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 2, this.length); + const val = this[offset2 + 1] | this[offset2] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return this[offset2] | this[offset2 + 1] << 8 | this[offset2 + 2] << 16 | this[offset2 + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return this[offset2] << 24 | this[offset2 + 1] << 16 | this[offset2 + 2] << 8 | this[offset2 + 3]; + }; + Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const val = this[offset2 + 4] + this[offset2 + 5] * 2 ** 8 + this[offset2 + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset2] * 2 ** 8 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 24); + }); + Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset2) { + offset2 = offset2 >>> 0; + validateNumber(offset2, "offset"); + const first = this[offset2]; + const last = this[offset2 + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset2, this.length - 8); + } + const val = (first << 24) + // Overflow + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + this[++offset2]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset2] * 2 ** 24 + this[++offset2] * 2 ** 16 + this[++offset2] * 2 ** 8 + last); + }); + Buffer2.prototype.readFloatLE = function readFloatLE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return ieee7542.read(this, offset2, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 4, this.length); + return ieee7542.read(this, offset2, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 8, this.length); + return ieee7542.read(this, offset2, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset2, noAssert) { + offset2 = offset2 >>> 0; + if (!noAssert) checkOffset(offset2, 8, this.length); + return ieee7542.read(this, offset2, false, 52, 8); + }; + function checkInt(buf, value, offset2, ext, max2, min2) { + if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max2 || value < min2) throw new RangeError('"value" argument is out of bounds'); + if (offset2 + ext > buf.length) throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset2, byteLength2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset2, byteLength2, maxBytes, 0); + } + let mul = 1; + let i = 0; + this[offset2] = value & 255; + while (++i < byteLength2 && (mul *= 256)) { + this[offset2 + i] = value / mul & 255; + } + return offset2 + byteLength2; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset2, byteLength2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset2, byteLength2, maxBytes, 0); + } + let i = byteLength2 - 1; + let mul = 1; + this[offset2 + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset2 + i] = value / mul & 255; + } + return offset2 + byteLength2; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 1, 255, 0); + this[offset2] = value & 255; + return offset2 + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0); + this[offset2] = value & 255; + this[offset2 + 1] = value >>> 8; + return offset2 + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 65535, 0); + this[offset2] = value >>> 8; + this[offset2 + 1] = value & 255; + return offset2 + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0); + this[offset2 + 3] = value >>> 24; + this[offset2 + 2] = value >>> 16; + this[offset2 + 1] = value >>> 8; + this[offset2] = value & 255; + return offset2 + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 4294967295, 0); + this[offset2] = value >>> 24; + this[offset2 + 1] = value >>> 16; + this[offset2 + 2] = value >>> 8; + this[offset2 + 3] = value & 255; + return offset2 + 4; + }; + function wrtBigUInt64LE(buf, value, offset2, min2, max2) { + checkIntBI(value, min2, max2, buf, offset2, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset2++] = lo; + lo = lo >> 8; + buf[offset2++] = lo; + lo = lo >> 8; + buf[offset2++] = lo; + lo = lo >> 8; + buf[offset2++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset2++] = hi; + hi = hi >> 8; + buf[offset2++] = hi; + hi = hi >> 8; + buf[offset2++] = hi; + hi = hi >> 8; + buf[offset2++] = hi; + return offset2; + } + function wrtBigUInt64BE(buf, value, offset2, min2, max2) { + checkIntBI(value, min2, max2, buf, offset2, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset2 + 7] = lo; + lo = lo >> 8; + buf[offset2 + 6] = lo; + lo = lo >> 8; + buf[offset2 + 5] = lo; + lo = lo >> 8; + buf[offset2 + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset2 + 3] = hi; + hi = hi >> 8; + buf[offset2 + 2] = hi; + hi = hi >> 8; + buf[offset2 + 1] = hi; + hi = hi >> 8; + buf[offset2] = hi; + return offset2 + 8; + } + Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset2 = 0) { + return wrtBigUInt64LE(this, value, offset2, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset2 = 0) { + return wrtBigUInt64BE(this, value, offset2, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeIntLE = function writeIntLE(value, offset2, byteLength2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset2, byteLength2, limit - 1, -limit); + } + let i = 0; + let mul = 1; + let sub = 0; + this[offset2] = value & 255; + while (++i < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset2 + i - 1] !== 0) { + sub = 1; + } + this[offset2 + i] = (value / mul >> 0) - sub & 255; + } + return offset2 + byteLength2; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value, offset2, byteLength2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset2, byteLength2, limit - 1, -limit); + } + let i = byteLength2 - 1; + let mul = 1; + let sub = 0; + this[offset2 + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset2 + i + 1] !== 0) { + sub = 1; + } + this[offset2 + i] = (value / mul >> 0) - sub & 255; + } + return offset2 + byteLength2; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 1, 127, -128); + if (value < 0) value = 255 + value + 1; + this[offset2] = value & 255; + return offset2 + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768); + this[offset2] = value & 255; + this[offset2 + 1] = value >>> 8; + return offset2 + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 2, 32767, -32768); + this[offset2] = value >>> 8; + this[offset2 + 1] = value & 255; + return offset2 + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648); + this[offset2] = value & 255; + this[offset2 + 1] = value >>> 8; + this[offset2 + 2] = value >>> 16; + this[offset2 + 3] = value >>> 24; + return offset2 + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset2, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) checkInt(this, value, offset2, 4, 2147483647, -2147483648); + if (value < 0) value = 4294967295 + value + 1; + this[offset2] = value >>> 24; + this[offset2 + 1] = value >>> 16; + this[offset2 + 2] = value >>> 8; + this[offset2 + 3] = value & 255; + return offset2 + 4; + }; + Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset2 = 0) { + return wrtBigUInt64LE(this, value, offset2, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset2 = 0) { + return wrtBigUInt64BE(this, value, offset2, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function checkIEEE754(buf, value, offset2, ext, max2, min2) { + if (offset2 + ext > buf.length) throw new RangeError("Index out of range"); + if (offset2 < 0) throw new RangeError("Index out of range"); + } + function writeFloat(buf, value, offset2, littleEndian, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset2, 4); + } + ieee7542.write(buf, value, offset2, littleEndian, 23, 4); + return offset2 + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset2, noAssert) { + return writeFloat(this, value, offset2, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset2, noAssert) { + return writeFloat(this, value, offset2, false, noAssert); + }; + function writeDouble(buf, value, offset2, littleEndian, noAssert) { + value = +value; + offset2 = offset2 >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset2, 8); + } + ieee7542.write(buf, value, offset2, littleEndian, 52, 8); + return offset2 + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset2, noAssert) { + return writeDouble(this, value, offset2, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset2, noAssert) { + return writeDouble(this, value, offset2, false, noAssert); + }; + Buffer2.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer"); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding2) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding2 = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding2 = end; + end = this.length; + } + if (encoding2 !== void 0 && typeof encoding2 !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding2 === "string" && !Buffer2.isEncoding(encoding2)) { + throw new TypeError("Unknown encoding: " + encoding2); + } + if (val.length === 1) { + const code = val.charCodeAt(0); + if (encoding2 === "utf8" && code < 128 || encoding2 === "latin1") { + val = code; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) val = 0; + let i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding2); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + return this; + }; + const errors2 = {}; + function E(sym, getMessage, Base) { + errors2[sym] = class NodeError extends Base { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; + } + E( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name) { + if (name) { + return `${name} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E( + "ERR_INVALID_ARG_TYPE", + function(name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E( + "ERR_OUT_OF_RANGE", + function(str, range2, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg += ` It must be ${range2}. Received ${received}`; + return msg; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}`; + } + function checkBounds(buf, offset2, byteLength2) { + validateNumber(offset2, "offset"); + if (buf[offset2] === void 0 || buf[offset2 + byteLength2] === void 0) { + boundsError(offset2, buf.length - (byteLength2 + 1)); + } + } + function checkIntBI(value, min2, max2, buf, offset2, byteLength2) { + if (value > max2 || value < min2) { + const n = typeof min2 === "bigint" ? "n" : ""; + let range2; + { + if (min2 === 0 || min2 === BigInt(0)) { + range2 = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`; + } else { + range2 = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`; + } + } + throw new errors2.ERR_OUT_OF_RANGE("value", range2, value); + } + checkBounds(buf, offset2, byteLength2); + } + function validateNumber(value, name) { + if (typeof value !== "number") { + throw new errors2.ERR_INVALID_ARG_TYPE(name, "number", value); + } + } + function boundsError(value, length, type2) { + if (Math.floor(value) !== value) { + validateNumber(value, type2); + throw new errors2.ERR_OUT_OF_RANGE("offset", "an integer", value); + } + if (length < 0) { + throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors2.ERR_OUT_OF_RANGE( + "offset", + `>= ${0} and <= ${length}`, + value + ); + } + const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + function utf8ToBytes(string2, units) { + units = units || Infinity; + let codePoint; + const length = string2.length; + let leadSurrogate = null; + const bytes = []; + for (let i = 0; i < length; ++i) { + codePoint = string2.charCodeAt(i); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + continue; + } else if (i + 1 === length) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str) { + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + byteArray.push(str.charCodeAt(i) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + let c, hi, lo; + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); + } + function blitBuffer(src2, dst, offset2, length) { + let i; + for (i = 0; i < length; ++i) { + if (i + offset2 >= dst.length || i >= src2.length) break; + dst[i + offset2] = src2[i]; + } + return i; + } + function isInstance(obj, type2) { + return obj instanceof type2 || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type2.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + const hexSliceLookupTable = function() { + const alphabet = "0123456789abcdef"; + const table = new Array(256); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; + } + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); + } + })(buffer$3); + return buffer$3; +} +var bufferExports = requireBuffer$2(); +const buffer$2 = /* @__PURE__ */ getDefaultExportFromCjs(bufferExports); +self.Buffer = buffer$2.Buffer; +var lib$2 = { exports: {} }; +var Stats$1 = {}; +var constants$8 = {}; +var hasRequiredConstants$7; +function requireConstants$7() { + if (hasRequiredConstants$7) return constants$8; + hasRequiredConstants$7 = 1; + Object.defineProperty(constants$8, "__esModule", { value: true }); + constants$8.constants = void 0; + constants$8.constants = { + O_RDONLY: 0, + O_WRONLY: 1, + O_RDWR: 2, + S_IFMT: 61440, + S_IFREG: 32768, + S_IFDIR: 16384, + S_IFCHR: 8192, + S_IFBLK: 24576, + S_IFIFO: 4096, + S_IFLNK: 40960, + S_IFSOCK: 49152, + O_CREAT: 64, + O_EXCL: 128, + O_NOCTTY: 256, + O_TRUNC: 512, + O_APPEND: 1024, + O_DIRECTORY: 65536, + O_NOATIME: 262144, + O_NOFOLLOW: 131072, + O_SYNC: 1052672, + O_SYMLINK: 2097152, + O_DIRECT: 16384, + O_NONBLOCK: 2048, + S_IRWXU: 448, + S_IRUSR: 256, + S_IWUSR: 128, + S_IXUSR: 64, + S_IRWXG: 56, + S_IRGRP: 32, + S_IWGRP: 16, + S_IXGRP: 8, + S_IRWXO: 7, + S_IROTH: 4, + S_IWOTH: 2, + S_IXOTH: 1, + F_OK: 0, + R_OK: 4, + W_OK: 2, + X_OK: 1, + UV_FS_SYMLINK_DIR: 1, + UV_FS_SYMLINK_JUNCTION: 2, + UV_FS_COPYFILE_EXCL: 1, + UV_FS_COPYFILE_FICLONE: 2, + UV_FS_COPYFILE_FICLONE_FORCE: 4, + COPYFILE_EXCL: 1, + COPYFILE_FICLONE: 2, + COPYFILE_FICLONE_FORCE: 4 + }; + return constants$8; +} +var hasRequiredStats; +function requireStats() { + if (hasRequiredStats) return Stats$1; + hasRequiredStats = 1; + Object.defineProperty(Stats$1, "__esModule", { value: true }); + Stats$1.Stats = void 0; + const constants_1 = requireConstants$7(); + const { S_IFMT, S_IFDIR, S_IFREG, S_IFBLK, S_IFCHR, S_IFLNK, S_IFIFO, S_IFSOCK } = constants_1.constants; + class Stats2 { + static build(node2, bigint = false) { + const stats = new Stats2(); + const { uid, gid, atime, mtime, ctime } = node2; + const getStatNumber = !bigint ? (number) => number : (number) => BigInt(number); + stats.uid = getStatNumber(uid); + stats.gid = getStatNumber(gid); + stats.rdev = getStatNumber(0); + stats.blksize = getStatNumber(4096); + stats.ino = getStatNumber(node2.ino); + stats.size = getStatNumber(node2.getSize()); + stats.blocks = getStatNumber(1); + stats.atime = atime; + stats.mtime = mtime; + stats.ctime = ctime; + stats.birthtime = ctime; + stats.atimeMs = getStatNumber(atime.getTime()); + stats.mtimeMs = getStatNumber(mtime.getTime()); + const ctimeMs = getStatNumber(ctime.getTime()); + stats.ctimeMs = ctimeMs; + stats.birthtimeMs = ctimeMs; + if (bigint) { + stats.atimeNs = BigInt(atime.getTime()) * BigInt(1e6); + stats.mtimeNs = BigInt(mtime.getTime()) * BigInt(1e6); + const ctimeNs = BigInt(ctime.getTime()) * BigInt(1e6); + stats.ctimeNs = ctimeNs; + stats.birthtimeNs = ctimeNs; + } + stats.dev = getStatNumber(0); + stats.mode = getStatNumber(node2.mode); + stats.nlink = getStatNumber(node2.nlink); + return stats; + } + _checkModeProperty(property) { + return (Number(this.mode) & S_IFMT) === property; + } + isDirectory() { + return this._checkModeProperty(S_IFDIR); + } + isFile() { + return this._checkModeProperty(S_IFREG); + } + isBlockDevice() { + return this._checkModeProperty(S_IFBLK); + } + isCharacterDevice() { + return this._checkModeProperty(S_IFCHR); + } + isSymbolicLink() { + return this._checkModeProperty(S_IFLNK); + } + isFIFO() { + return this._checkModeProperty(S_IFIFO); + } + isSocket() { + return this._checkModeProperty(S_IFSOCK); + } + } + Stats$1.Stats = Stats2; + Stats$1.default = Stats2; + return Stats$1; +} +var Dirent$1 = {}; +var encoding = {}; +var buffer$1 = {}; +var hasRequiredBuffer$1; +function requireBuffer$1() { + if (hasRequiredBuffer$1) return buffer$1; + hasRequiredBuffer$1 = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.bufferFrom = exports.bufferAllocUnsafe = exports.Buffer = void 0; + const buffer_1 = requireBuffer$2(); + Object.defineProperty(exports, "Buffer", { enumerable: true, get: function() { + return buffer_1.Buffer; + } }); + function bufferV0P12Ponyfill(arg0, ...args) { + return new buffer_1.Buffer(arg0, ...args); + } + const bufferAllocUnsafe = buffer_1.Buffer.allocUnsafe || bufferV0P12Ponyfill; + exports.bufferAllocUnsafe = bufferAllocUnsafe; + const bufferFrom = buffer_1.Buffer.from || bufferV0P12Ponyfill; + exports.bufferFrom = bufferFrom; + })(buffer$1); + return buffer$1; +} +var errors$3 = {}; +var assert$1 = { exports: {} }; +var errors$2 = {}; +var util$6 = {}; +var types$3 = {}; +var shams$1; +var hasRequiredShams$1; +function requireShams$1() { + if (hasRequiredShams$1) return shams$1; + hasRequiredShams$1 = 1; + shams$1 = function hasSymbols2() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = ( + /** @type {PropertyDescriptor} */ + Object.getOwnPropertyDescriptor(obj, sym) + ); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + return shams$1; +} +var shams; +var hasRequiredShams; +function requireShams() { + if (hasRequiredShams) return shams; + hasRequiredShams = 1; + var hasSymbols2 = requireShams$1(); + shams = function hasToStringTagShams() { + return hasSymbols2() && !!Symbol.toStringTag; + }; + return shams; +} +var esObjectAtoms; +var hasRequiredEsObjectAtoms; +function requireEsObjectAtoms() { + if (hasRequiredEsObjectAtoms) return esObjectAtoms; + hasRequiredEsObjectAtoms = 1; + esObjectAtoms = Object; + return esObjectAtoms; +} +var esErrors; +var hasRequiredEsErrors; +function requireEsErrors() { + if (hasRequiredEsErrors) return esErrors; + hasRequiredEsErrors = 1; + esErrors = Error; + return esErrors; +} +var _eval; +var hasRequired_eval; +function require_eval() { + if (hasRequired_eval) return _eval; + hasRequired_eval = 1; + _eval = EvalError; + return _eval; +} +var range; +var hasRequiredRange; +function requireRange() { + if (hasRequiredRange) return range; + hasRequiredRange = 1; + range = RangeError; + return range; +} +var ref$1; +var hasRequiredRef; +function requireRef() { + if (hasRequiredRef) return ref$1; + hasRequiredRef = 1; + ref$1 = ReferenceError; + return ref$1; +} +var syntax; +var hasRequiredSyntax; +function requireSyntax() { + if (hasRequiredSyntax) return syntax; + hasRequiredSyntax = 1; + syntax = SyntaxError; + return syntax; +} +var type; +var hasRequiredType; +function requireType() { + if (hasRequiredType) return type; + hasRequiredType = 1; + type = TypeError; + return type; +} +var uri; +var hasRequiredUri; +function requireUri() { + if (hasRequiredUri) return uri; + hasRequiredUri = 1; + uri = URIError; + return uri; +} +var abs; +var hasRequiredAbs; +function requireAbs() { + if (hasRequiredAbs) return abs; + hasRequiredAbs = 1; + abs = Math.abs; + return abs; +} +var floor; +var hasRequiredFloor; +function requireFloor() { + if (hasRequiredFloor) return floor; + hasRequiredFloor = 1; + floor = Math.floor; + return floor; +} +var max; +var hasRequiredMax; +function requireMax() { + if (hasRequiredMax) return max; + hasRequiredMax = 1; + max = Math.max; + return max; +} +var min; +var hasRequiredMin; +function requireMin() { + if (hasRequiredMin) return min; + hasRequiredMin = 1; + min = Math.min; + return min; +} +var pow; +var hasRequiredPow; +function requirePow() { + if (hasRequiredPow) return pow; + hasRequiredPow = 1; + pow = Math.pow; + return pow; +} +var round; +var hasRequiredRound; +function requireRound() { + if (hasRequiredRound) return round; + hasRequiredRound = 1; + round = Math.round; + return round; +} +var _isNaN; +var hasRequired_isNaN; +function require_isNaN() { + if (hasRequired_isNaN) return _isNaN; + hasRequired_isNaN = 1; + _isNaN = Number.isNaN || function isNaN2(a) { + return a !== a; + }; + return _isNaN; +} +var sign$1; +var hasRequiredSign$1; +function requireSign$1() { + if (hasRequiredSign$1) return sign$1; + hasRequiredSign$1 = 1; + var $isNaN = /* @__PURE__ */ require_isNaN(); + sign$1 = function sign2(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : 1; + }; + return sign$1; +} +var gOPD; +var hasRequiredGOPD; +function requireGOPD() { + if (hasRequiredGOPD) return gOPD; + hasRequiredGOPD = 1; + gOPD = Object.getOwnPropertyDescriptor; + return gOPD; +} +var gopd; +var hasRequiredGopd; +function requireGopd() { + if (hasRequiredGopd) return gopd; + hasRequiredGopd = 1; + var $gOPD = /* @__PURE__ */ requireGOPD(); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e) { + $gOPD = null; + } + } + gopd = $gOPD; + return gopd; +} +var esDefineProperty; +var hasRequiredEsDefineProperty; +function requireEsDefineProperty() { + if (hasRequiredEsDefineProperty) return esDefineProperty; + hasRequiredEsDefineProperty = 1; + var $defineProperty = Object.defineProperty || false; + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e) { + $defineProperty = false; + } + } + esDefineProperty = $defineProperty; + return esDefineProperty; +} +var hasSymbols; +var hasRequiredHasSymbols; +function requireHasSymbols() { + if (hasRequiredHasSymbols) return hasSymbols; + hasRequiredHasSymbols = 1; + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = requireShams$1(); + hasSymbols = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + return hasSymbols; +} +var Reflect_getPrototypeOf; +var hasRequiredReflect_getPrototypeOf; +function requireReflect_getPrototypeOf() { + if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf; + hasRequiredReflect_getPrototypeOf = 1; + Reflect_getPrototypeOf = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; + return Reflect_getPrototypeOf; +} +var Object_getPrototypeOf; +var hasRequiredObject_getPrototypeOf; +function requireObject_getPrototypeOf() { + if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf; + hasRequiredObject_getPrototypeOf = 1; + var $Object = /* @__PURE__ */ requireEsObjectAtoms(); + Object_getPrototypeOf = $Object.getPrototypeOf || null; + return Object_getPrototypeOf; +} +var implementation$4; +var hasRequiredImplementation$4; +function requireImplementation$4() { + if (hasRequiredImplementation$4) return implementation$4; + hasRequiredImplementation$4 = 1; + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max2 = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a, b) { + var arr = []; + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset2) { + var arr = []; + for (var i = offset2, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + implementation$4 = function bind(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max2(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = "$" + i; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + return implementation$4; +} +var functionBind; +var hasRequiredFunctionBind; +function requireFunctionBind() { + if (hasRequiredFunctionBind) return functionBind; + hasRequiredFunctionBind = 1; + var implementation2 = requireImplementation$4(); + functionBind = Function.prototype.bind || implementation2; + return functionBind; +} +var functionCall; +var hasRequiredFunctionCall; +function requireFunctionCall() { + if (hasRequiredFunctionCall) return functionCall; + hasRequiredFunctionCall = 1; + functionCall = Function.prototype.call; + return functionCall; +} +var functionApply; +var hasRequiredFunctionApply; +function requireFunctionApply() { + if (hasRequiredFunctionApply) return functionApply; + hasRequiredFunctionApply = 1; + functionApply = Function.prototype.apply; + return functionApply; +} +var reflectApply; +var hasRequiredReflectApply; +function requireReflectApply() { + if (hasRequiredReflectApply) return reflectApply; + hasRequiredReflectApply = 1; + reflectApply = typeof Reflect !== "undefined" && Reflect && Reflect.apply; + return reflectApply; +} +var actualApply; +var hasRequiredActualApply; +function requireActualApply() { + if (hasRequiredActualApply) return actualApply; + hasRequiredActualApply = 1; + var bind = requireFunctionBind(); + var $apply = requireFunctionApply(); + var $call = requireFunctionCall(); + var $reflectApply = requireReflectApply(); + actualApply = $reflectApply || bind.call($call, $apply); + return actualApply; +} +var callBindApplyHelpers; +var hasRequiredCallBindApplyHelpers; +function requireCallBindApplyHelpers() { + if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers; + hasRequiredCallBindApplyHelpers = 1; + var bind = requireFunctionBind(); + var $TypeError = /* @__PURE__ */ requireType(); + var $call = requireFunctionCall(); + var $actualApply = requireActualApply(); + callBindApplyHelpers = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== "function") { + throw new $TypeError("a function is required"); + } + return $actualApply(bind, $call, args); + }; + return callBindApplyHelpers; +} +var get; +var hasRequiredGet; +function requireGet() { + if (hasRequiredGet) return get; + hasRequiredGet = 1; + var callBind2 = requireCallBindApplyHelpers(); + var gOPD2 = /* @__PURE__ */ requireGopd(); + var hasProtoAccessor; + try { + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ + [].__proto__ === Array.prototype; + } catch (e) { + if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") { + throw e; + } + } + var desc = !!hasProtoAccessor && gOPD2 && gOPD2( + Object.prototype, + /** @type {keyof typeof Object.prototype} */ + "__proto__" + ); + var $Object = Object; + var $getPrototypeOf = $Object.getPrototypeOf; + get = desc && typeof desc.get === "function" ? callBind2([desc.get]) : typeof $getPrototypeOf === "function" ? ( + /** @type {import('./get')} */ + function getDunder(value) { + return $getPrototypeOf(value == null ? value : $Object(value)); + } + ) : false; + return get; +} +var getProto; +var hasRequiredGetProto; +function requireGetProto() { + if (hasRequiredGetProto) return getProto; + hasRequiredGetProto = 1; + var reflectGetProto = requireReflect_getPrototypeOf(); + var originalGetProto = requireObject_getPrototypeOf(); + var getDunderProto = /* @__PURE__ */ requireGet(); + getProto = reflectGetProto ? function getProto2(O) { + return reflectGetProto(O); + } : originalGetProto ? function getProto2(O) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new TypeError("getProto: not an object"); + } + return originalGetProto(O); + } : getDunderProto ? function getProto2(O) { + return getDunderProto(O); + } : null; + return getProto; +} +var hasown; +var hasRequiredHasown; +function requireHasown() { + if (hasRequiredHasown) return hasown; + hasRequiredHasown = 1; + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind = requireFunctionBind(); + hasown = bind.call(call, $hasOwn); + return hasown; +} +var getIntrinsic; +var hasRequiredGetIntrinsic; +function requireGetIntrinsic() { + if (hasRequiredGetIntrinsic) return getIntrinsic; + hasRequiredGetIntrinsic = 1; + var undefined$1; + var $Object = /* @__PURE__ */ requireEsObjectAtoms(); + var $Error = /* @__PURE__ */ requireEsErrors(); + var $EvalError = /* @__PURE__ */ require_eval(); + var $RangeError = /* @__PURE__ */ requireRange(); + var $ReferenceError = /* @__PURE__ */ requireRef(); + var $SyntaxError = /* @__PURE__ */ requireSyntax(); + var $TypeError = /* @__PURE__ */ requireType(); + var $URIError = /* @__PURE__ */ requireUri(); + var abs2 = /* @__PURE__ */ requireAbs(); + var floor2 = /* @__PURE__ */ requireFloor(); + var max2 = /* @__PURE__ */ requireMax(); + var min2 = /* @__PURE__ */ requireMin(); + var pow2 = /* @__PURE__ */ requirePow(); + var round2 = /* @__PURE__ */ requireRound(); + var sign2 = /* @__PURE__ */ requireSign$1(); + var $Function = Function; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e) { + } + }; + var $gOPD = /* @__PURE__ */ requireGopd(); + var $defineProperty = /* @__PURE__ */ requireEsDefineProperty(); + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }() : throwTypeError; + var hasSymbols2 = requireHasSymbols()(); + var getProto2 = requireGetProto(); + var $ObjectGPO = requireObject_getPrototypeOf(); + var $ReflectGPO = requireReflect_getPrototypeOf(); + var $apply = requireFunctionApply(); + var $call = requireFunctionCall(); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto2 ? undefined$1 : getProto2(Uint8Array); + var INTRINSICS = { + __proto__: null, + "%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2([][Symbol.iterator]()) : undefined$1, + "%AsyncFromSyncIteratorPrototype%": undefined$1, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": $Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": $EvalError, + "%Float16Array%": typeof Float16Array === "undefined" ? undefined$1 : Float16Array, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(getProto2([][Symbol.iterator]())) : undefined$1, + "%JSON%": typeof JSON === "object" ? JSON : undefined$1, + "%Map%": typeof Map === "undefined" ? undefined$1 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": $Object, + "%Object.getOwnPropertyDescriptor%": $gOPD, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy, + "%RangeError%": $RangeError, + "%ReferenceError%": $ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined$1 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(""[Symbol.iterator]()) : undefined$1, + "%Symbol%": hasSymbols2 ? Symbol : undefined$1, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array, + "%URIError%": $URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet, + "%Function.prototype.call%": $call, + "%Function.prototype.apply%": $apply, + "%Object.defineProperty%": $defineProperty, + "%Object.getPrototypeOf%": $ObjectGPO, + "%Math.abs%": abs2, + "%Math.floor%": floor2, + "%Math.max%": max2, + "%Math.min%": min2, + "%Math.pow%": pow2, + "%Math.round%": round2, + "%Math.sign%": sign2, + "%Reflect.getPrototypeOf%": $ReflectGPO + }; + if (getProto2) { + try { + null.error; + } catch (e) { + var errorProto = getProto2(getProto2(e)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var doEval = function doEval2(name) { + var value; + if (name === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name === "%AsyncGenerator%") { + var fn = doEval2("%AsyncGeneratorFunction%"); + if (fn) { + value = fn.prototype; + } + } else if (name === "%AsyncIteratorPrototype%") { + var gen = doEval2("%AsyncGenerator%"); + if (gen && getProto2) { + value = getProto2(gen.prototype); + } + } + INTRINSICS[name] = value; + return value; + }; + var LEGACY_ALIASES = { + __proto__: null, + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind = requireFunctionBind(); + var hasOwn2 = /* @__PURE__ */ requireHasown(); + var $concat = bind.call($call, Array.prototype.concat); + var $spliceApply = bind.call($apply, Array.prototype.splice); + var $replace = bind.call($call, String.prototype.replace); + var $strSlice = bind.call($call, String.prototype.slice); + var $exec = bind.call($call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string2) { + var first = $strSlice(string2, 0, 1); + var last = $strSlice(string2, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string2, rePropName, function(match, number, quote2, subString) { + result[result.length] = quote2 ? $replace(subString, reEscapeChar, "$1") : number || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn2(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn2(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name + " does not exist!"); + }; + getIntrinsic = function GetIntrinsic(name, allowMissing) { + if (typeof name !== "string" || name.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn2(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); + } + return void 0; + } + if ($gOPD && i + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn2(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + return getIntrinsic; +} +var callBind = { exports: {} }; +var defineDataProperty; +var hasRequiredDefineDataProperty; +function requireDefineDataProperty() { + if (hasRequiredDefineDataProperty) return defineDataProperty; + hasRequiredDefineDataProperty = 1; + var $defineProperty = /* @__PURE__ */ requireEsDefineProperty(); + var $SyntaxError = /* @__PURE__ */ requireSyntax(); + var $TypeError = /* @__PURE__ */ requireType(); + var gopd2 = /* @__PURE__ */ requireGopd(); + defineDataProperty = function defineDataProperty2(obj, property, value) { + if (!obj || typeof obj !== "object" && typeof obj !== "function") { + throw new $TypeError("`obj` must be an object or a function`"); + } + if (typeof property !== "string" && typeof property !== "symbol") { + throw new $TypeError("`property` must be a string or a symbol`"); + } + if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) { + throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null"); + } + if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) { + throw new $TypeError("`nonWritable`, if provided, must be a boolean or null"); + } + if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) { + throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null"); + } + if (arguments.length > 6 && typeof arguments[6] !== "boolean") { + throw new $TypeError("`loose`, if provided, must be a boolean"); + } + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + var desc = !!gopd2 && gopd2(obj, property); + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) { + obj[property] = value; + } else { + throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable."); + } + }; + return defineDataProperty; +} +var hasPropertyDescriptors_1; +var hasRequiredHasPropertyDescriptors; +function requireHasPropertyDescriptors() { + if (hasRequiredHasPropertyDescriptors) return hasPropertyDescriptors_1; + hasRequiredHasPropertyDescriptors = 1; + var $defineProperty = /* @__PURE__ */ requireEsDefineProperty(); + var hasPropertyDescriptors = function hasPropertyDescriptors2() { + return !!$defineProperty; + }; + hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], "length", { value: 1 }).length !== 1; + } catch (e) { + return true; + } + }; + hasPropertyDescriptors_1 = hasPropertyDescriptors; + return hasPropertyDescriptors_1; +} +var setFunctionLength; +var hasRequiredSetFunctionLength; +function requireSetFunctionLength() { + if (hasRequiredSetFunctionLength) return setFunctionLength; + hasRequiredSetFunctionLength = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var define = /* @__PURE__ */ requireDefineDataProperty(); + var hasDescriptors = /* @__PURE__ */ requireHasPropertyDescriptors()(); + var gOPD2 = /* @__PURE__ */ requireGopd(); + var $TypeError = /* @__PURE__ */ requireType(); + var $floor = GetIntrinsic("%Math.floor%"); + setFunctionLength = function setFunctionLength2(fn, length) { + if (typeof fn !== "function") { + throw new $TypeError("`fn` is not a function"); + } + if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length) { + throw new $TypeError("`length` must be a positive 32-bit integer"); + } + var loose = arguments.length > 2 && !!arguments[2]; + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ("length" in fn && gOPD2) { + var desc = gOPD2(fn, "length"); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define( + /** @type {Parameters[0]} */ + fn, + "length", + length, + true, + true + ); + } else { + define( + /** @type {Parameters[0]} */ + fn, + "length", + length + ); + } + } + return fn; + }; + return setFunctionLength; +} +var applyBind; +var hasRequiredApplyBind; +function requireApplyBind() { + if (hasRequiredApplyBind) return applyBind; + hasRequiredApplyBind = 1; + var bind = requireFunctionBind(); + var $apply = requireFunctionApply(); + var actualApply2 = requireActualApply(); + applyBind = function applyBind2() { + return actualApply2(bind, $apply, arguments); + }; + return applyBind; +} +var hasRequiredCallBind; +function requireCallBind() { + if (hasRequiredCallBind) return callBind.exports; + hasRequiredCallBind = 1; + (function(module) { + var setFunctionLength2 = /* @__PURE__ */ requireSetFunctionLength(); + var $defineProperty = /* @__PURE__ */ requireEsDefineProperty(); + var callBindBasic = requireCallBindApplyHelpers(); + var applyBind2 = requireApplyBind(); + module.exports = function callBind2(originalFunction) { + var func = callBindBasic(arguments); + var adjustedLength = originalFunction.length - (arguments.length - 1); + return setFunctionLength2( + func, + 1 + (adjustedLength > 0 ? adjustedLength : 0), + true + ); + }; + if ($defineProperty) { + $defineProperty(module.exports, "apply", { value: applyBind2 }); + } else { + module.exports.apply = applyBind2; + } + })(callBind); + return callBind.exports; +} +var callBound$1; +var hasRequiredCallBound$1; +function requireCallBound$1() { + if (hasRequiredCallBound$1) return callBound$1; + hasRequiredCallBound$1 = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBind2 = requireCallBind(); + var $indexOf = callBind2(GetIntrinsic("String.prototype.indexOf")); + callBound$1 = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) { + return callBind2(intrinsic); + } + return intrinsic; + }; + return callBound$1; +} +var isArguments$1; +var hasRequiredIsArguments$1; +function requireIsArguments$1() { + if (hasRequiredIsArguments$1) return isArguments$1; + hasRequiredIsArguments$1 = 1; + var hasToStringTag = requireShams()(); + var callBound2 = requireCallBound$1(); + var $toString = callBound2("Object.prototype.toString"); + var isStandardArguments = function isArguments2(value) { + if (hasToStringTag && value && typeof value === "object" && Symbol.toStringTag in value) { + return false; + } + return $toString(value) === "[object Arguments]"; + }; + var isLegacyArguments = function isArguments2(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && $toString(value) !== "[object Array]" && $toString(value.callee) === "[object Function]"; + }; + var supportsStandardArguments = function() { + return isStandardArguments(arguments); + }(); + isStandardArguments.isLegacyArguments = isLegacyArguments; + isArguments$1 = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + return isArguments$1; +} +var isGeneratorFunction; +var hasRequiredIsGeneratorFunction; +function requireIsGeneratorFunction() { + if (hasRequiredIsGeneratorFunction) return isGeneratorFunction; + hasRequiredIsGeneratorFunction = 1; + var toStr = Object.prototype.toString; + var fnToStr = Function.prototype.toString; + var isFnRegex = /^\s*(?:function)?\*/; + var hasToStringTag = requireShams()(); + var getProto2 = Object.getPrototypeOf; + var getGeneratorFunc = function() { + if (!hasToStringTag) { + return false; + } + try { + return Function("return function*() {}")(); + } catch (e) { + } + }; + var GeneratorFunction; + isGeneratorFunction = function isGeneratorFunction2(fn) { + if (typeof fn !== "function") { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === "[object GeneratorFunction]"; + } + if (!getProto2) { + return false; + } + if (typeof GeneratorFunction === "undefined") { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto2(generatorFunc) : false; + } + return getProto2(fn) === GeneratorFunction; + }; + return isGeneratorFunction; +} +var isCallable; +var hasRequiredIsCallable; +function requireIsCallable() { + if (hasRequiredIsCallable) return isCallable; + hasRequiredIsCallable = 1; + var fnToStr = Function.prototype.toString; + var reflectApply2 = typeof Reflect === "object" && Reflect !== null && Reflect.apply; + var badArrayLike; + var isCallableMarker; + if (typeof reflectApply2 === "function" && typeof Object.defineProperty === "function") { + try { + badArrayLike = Object.defineProperty({}, "length", { + get: function() { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + reflectApply2(function() { + throw 42; + }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply2 = null; + } + } + } else { + reflectApply2 = null; + } + var constructorRegex = /^\s*class\b/; + var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; + } + }; + var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { + return false; + } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + var objectClass = "[object Object]"; + var fnClass = "[object Function]"; + var genClass = "[object GeneratorFunction]"; + var ddaClass = "[object HTMLAllCollection]"; + var ddaClass2 = "[object HTML document.all class]"; + var ddaClass3 = "[object HTMLCollection]"; + var hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag; + var isIE68 = !(0 in [,]); + var isDDA = function isDocumentDotAll() { + return false; + }; + if (typeof document === "object") { + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) { + try { + var str = toStr.call(value); + return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null; + } catch (e) { + } + } + return false; + }; + } + } + isCallable = reflectApply2 ? function isCallable2(value) { + if (isDDA(value)) { + return true; + } + if (!value) { + return false; + } + if (typeof value !== "function" && typeof value !== "object") { + return false; + } + try { + reflectApply2(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { + return false; + } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } : function isCallable2(value) { + if (isDDA(value)) { + return true; + } + if (!value) { + return false; + } + if (typeof value !== "function" && typeof value !== "object") { + return false; + } + if (hasToStringTag) { + return tryFunctionObject(value); + } + if (isES6ClassFn(value)) { + return false; + } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) { + return false; + } + return tryFunctionObject(value); + }; + return isCallable; +} +var forEach_1; +var hasRequiredForEach; +function requireForEach() { + if (hasRequiredForEach) return forEach_1; + hasRequiredForEach = 1; + var isCallable2 = requireIsCallable(); + var toStr = Object.prototype.toString; + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + var forEachArray = function forEachArray2(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty2.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } + }; + var forEachString = function forEachString2(string2, iterator, receiver) { + for (var i = 0, len = string2.length; i < len; i++) { + if (receiver == null) { + iterator(string2.charAt(i), i, string2); + } else { + iterator.call(receiver, string2.charAt(i), i, string2); + } + } + }; + var forEachObject = function forEachObject2(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty2.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } + }; + var forEach = function forEach2(list, iterator, thisArg) { + if (!isCallable2(iterator)) { + throw new TypeError("iterator must be a function"); + } + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + if (toStr.call(list) === "[object Array]") { + forEachArray(list, iterator, receiver); + } else if (typeof list === "string") { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } + }; + forEach_1 = forEach; + return forEach_1; +} +var possibleTypedArrayNames; +var hasRequiredPossibleTypedArrayNames; +function requirePossibleTypedArrayNames() { + if (hasRequiredPossibleTypedArrayNames) return possibleTypedArrayNames; + hasRequiredPossibleTypedArrayNames = 1; + possibleTypedArrayNames = [ + "Float32Array", + "Float64Array", + "Int8Array", + "Int16Array", + "Int32Array", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "BigInt64Array", + "BigUint64Array" + ]; + return possibleTypedArrayNames; +} +var availableTypedArrays; +var hasRequiredAvailableTypedArrays; +function requireAvailableTypedArrays() { + if (hasRequiredAvailableTypedArrays) return availableTypedArrays; + hasRequiredAvailableTypedArrays = 1; + var possibleNames = /* @__PURE__ */ requirePossibleTypedArrayNames(); + var g = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; + availableTypedArrays = function availableTypedArrays2() { + var out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === "function") { + out[out.length] = possibleNames[i]; + } + } + return out; + }; + return availableTypedArrays; +} +var callBound; +var hasRequiredCallBound; +function requireCallBound() { + if (hasRequiredCallBound) return callBound; + hasRequiredCallBound = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBindBasic = requireCallBindApplyHelpers(); + var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]); + callBound = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = ( + /** @type {Parameters[0][0]} */ + GetIntrinsic(name, !!allowMissing) + ); + if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) { + return callBindBasic([intrinsic]); + } + return intrinsic; + }; + return callBound; +} +var whichTypedArray; +var hasRequiredWhichTypedArray; +function requireWhichTypedArray() { + if (hasRequiredWhichTypedArray) return whichTypedArray; + hasRequiredWhichTypedArray = 1; + var forEach = requireForEach(); + var availableTypedArrays2 = /* @__PURE__ */ requireAvailableTypedArrays(); + var callBind2 = requireCallBind(); + var callBound2 = /* @__PURE__ */ requireCallBound(); + var gOPD2 = /* @__PURE__ */ requireGopd(); + var $toString = callBound2("Object.prototype.toString"); + var hasToStringTag = requireShams()(); + var g = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; + var typedArrays = availableTypedArrays2(); + var $slice = callBound2("String.prototype.slice"); + var getPrototypeOf = Object.getPrototypeOf; + var $indexOf = callBound2("Array.prototype.indexOf", true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; + }; + var cache = { __proto__: null }; + if (hasToStringTag && gOPD2 && getPrototypeOf) { + forEach(typedArrays, function(typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + var descriptor = gOPD2(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + descriptor = gOPD2(superProto, Symbol.toStringTag); + } + cache["$" + typedArray] = callBind2(descriptor.get); + } + }); + } else { + forEach(typedArrays, function(typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + cache["$" + typedArray] = callBind2(fn); + } + }); + } + var tryTypedArrays = function tryAllTypedArrays(value) { + var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ + /** @type {any} */ + cache, + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function(getter, typedArray) { + if (!found) { + try { + if ("$" + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { + } + } + } + ); + return found; + }; + var trySlices = function tryAllSlices(value) { + var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ + /** @type {any} */ + cache, + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ + function(getter, name) { + if (!found) { + try { + getter(value); + found = $slice(name, 1); + } catch (e) { + } + } + } + ); + return found; + }; + whichTypedArray = function whichTypedArray2(value) { + if (!value || typeof value !== "object") { + return false; + } + if (!hasToStringTag) { + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== "Object") { + return false; + } + return trySlices(value); + } + if (!gOPD2) { + return null; + } + return tryTypedArrays(value); + }; + return whichTypedArray; +} +var isTypedArray$1; +var hasRequiredIsTypedArray; +function requireIsTypedArray() { + if (hasRequiredIsTypedArray) return isTypedArray$1; + hasRequiredIsTypedArray = 1; + var whichTypedArray2 = /* @__PURE__ */ requireWhichTypedArray(); + isTypedArray$1 = function isTypedArray2(value) { + return !!whichTypedArray2(value); + }; + return isTypedArray$1; +} +var hasRequiredTypes; +function requireTypes() { + if (hasRequiredTypes) return types$3; + hasRequiredTypes = 1; + (function(exports) { + var isArgumentsObject = requireIsArguments$1(); + var isGeneratorFunction2 = requireIsGeneratorFunction(); + var whichTypedArray2 = /* @__PURE__ */ requireWhichTypedArray(); + var isTypedArray2 = /* @__PURE__ */ requireIsTypedArray(); + function uncurryThis(f) { + return f.call.bind(f); + } + var BigIntSupported = typeof BigInt !== "undefined"; + var SymbolSupported = typeof Symbol !== "undefined"; + var ObjectToString = uncurryThis(Object.prototype.toString); + var numberValue = uncurryThis(Number.prototype.valueOf); + var stringValue = uncurryThis(String.prototype.valueOf); + var booleanValue = uncurryThis(Boolean.prototype.valueOf); + if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); + } + if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); + } + function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== "object") { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch (e) { + return false; + } + } + exports.isArgumentsObject = isArgumentsObject; + exports.isGeneratorFunction = isGeneratorFunction2; + exports.isTypedArray = isTypedArray2; + function isPromise(input) { + return typeof Promise !== "undefined" && input instanceof Promise || input !== null && typeof input === "object" && typeof input.then === "function" && typeof input.catch === "function"; + } + exports.isPromise = isPromise; + function isArrayBufferView(value) { + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + return isTypedArray2(value) || isDataView(value); + } + exports.isArrayBufferView = isArrayBufferView; + function isUint8Array(value) { + return whichTypedArray2(value) === "Uint8Array"; + } + exports.isUint8Array = isUint8Array; + function isUint8ClampedArray(value) { + return whichTypedArray2(value) === "Uint8ClampedArray"; + } + exports.isUint8ClampedArray = isUint8ClampedArray; + function isUint16Array(value) { + return whichTypedArray2(value) === "Uint16Array"; + } + exports.isUint16Array = isUint16Array; + function isUint32Array(value) { + return whichTypedArray2(value) === "Uint32Array"; + } + exports.isUint32Array = isUint32Array; + function isInt8Array(value) { + return whichTypedArray2(value) === "Int8Array"; + } + exports.isInt8Array = isInt8Array; + function isInt16Array(value) { + return whichTypedArray2(value) === "Int16Array"; + } + exports.isInt16Array = isInt16Array; + function isInt32Array(value) { + return whichTypedArray2(value) === "Int32Array"; + } + exports.isInt32Array = isInt32Array; + function isFloat32Array(value) { + return whichTypedArray2(value) === "Float32Array"; + } + exports.isFloat32Array = isFloat32Array; + function isFloat64Array(value) { + return whichTypedArray2(value) === "Float64Array"; + } + exports.isFloat64Array = isFloat64Array; + function isBigInt64Array(value) { + return whichTypedArray2(value) === "BigInt64Array"; + } + exports.isBigInt64Array = isBigInt64Array; + function isBigUint64Array(value) { + return whichTypedArray2(value) === "BigUint64Array"; + } + exports.isBigUint64Array = isBigUint64Array; + function isMapToString(value) { + return ObjectToString(value) === "[object Map]"; + } + isMapToString.working = typeof Map !== "undefined" && isMapToString(/* @__PURE__ */ new Map()); + function isMap2(value) { + if (typeof Map === "undefined") { + return false; + } + return isMapToString.working ? isMapToString(value) : value instanceof Map; + } + exports.isMap = isMap2; + function isSetToString(value) { + return ObjectToString(value) === "[object Set]"; + } + isSetToString.working = typeof Set !== "undefined" && isSetToString(/* @__PURE__ */ new Set()); + function isSet(value) { + if (typeof Set === "undefined") { + return false; + } + return isSetToString.working ? isSetToString(value) : value instanceof Set; + } + exports.isSet = isSet; + function isWeakMapToString(value) { + return ObjectToString(value) === "[object WeakMap]"; + } + isWeakMapToString.working = typeof WeakMap !== "undefined" && isWeakMapToString(/* @__PURE__ */ new WeakMap()); + function isWeakMap(value) { + if (typeof WeakMap === "undefined") { + return false; + } + return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap; + } + exports.isWeakMap = isWeakMap; + function isWeakSetToString(value) { + return ObjectToString(value) === "[object WeakSet]"; + } + isWeakSetToString.working = typeof WeakSet !== "undefined" && isWeakSetToString(/* @__PURE__ */ new WeakSet()); + function isWeakSet(value) { + return isWeakSetToString(value); + } + exports.isWeakSet = isWeakSet; + function isArrayBufferToString(value) { + return ObjectToString(value) === "[object ArrayBuffer]"; + } + isArrayBufferToString.working = typeof ArrayBuffer !== "undefined" && isArrayBufferToString(new ArrayBuffer()); + function isArrayBuffer(value) { + if (typeof ArrayBuffer === "undefined") { + return false; + } + return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer; + } + exports.isArrayBuffer = isArrayBuffer; + function isDataViewToString(value) { + return ObjectToString(value) === "[object DataView]"; + } + isDataViewToString.working = typeof ArrayBuffer !== "undefined" && typeof DataView !== "undefined" && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)); + function isDataView(value) { + if (typeof DataView === "undefined") { + return false; + } + return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView; + } + exports.isDataView = isDataView; + var SharedArrayBufferCopy = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : void 0; + function isSharedArrayBufferToString(value) { + return ObjectToString(value) === "[object SharedArrayBuffer]"; + } + function isSharedArrayBuffer(value) { + if (typeof SharedArrayBufferCopy === "undefined") { + return false; + } + if (typeof isSharedArrayBufferToString.working === "undefined") { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy; + } + exports.isSharedArrayBuffer = isSharedArrayBuffer; + function isAsyncFunction(value) { + return ObjectToString(value) === "[object AsyncFunction]"; + } + exports.isAsyncFunction = isAsyncFunction; + function isMapIterator(value) { + return ObjectToString(value) === "[object Map Iterator]"; + } + exports.isMapIterator = isMapIterator; + function isSetIterator(value) { + return ObjectToString(value) === "[object Set Iterator]"; + } + exports.isSetIterator = isSetIterator; + function isGeneratorObject(value) { + return ObjectToString(value) === "[object Generator]"; + } + exports.isGeneratorObject = isGeneratorObject; + function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === "[object WebAssembly.Module]"; + } + exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); + } + exports.isNumberObject = isNumberObject; + function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); + } + exports.isStringObject = isStringObject; + function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); + } + exports.isBooleanObject = isBooleanObject; + function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); + } + exports.isBigIntObject = isBigIntObject; + function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); + } + exports.isSymbolObject = isSymbolObject; + function isBoxedPrimitive(value) { + return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value); + } + exports.isBoxedPrimitive = isBoxedPrimitive; + function isAnyArrayBuffer(value) { + return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value)); + } + exports.isAnyArrayBuffer = isAnyArrayBuffer; + ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + " is not supported in userland"); + } + }); + }); + })(types$3); + return types$3; +} +var isBufferBrowser$1; +var hasRequiredIsBufferBrowser$1; +function requireIsBufferBrowser$1() { + if (hasRequiredIsBufferBrowser$1) return isBufferBrowser$1; + hasRequiredIsBufferBrowser$1 = 1; + isBufferBrowser$1 = function isBuffer(arg) { + return arg && typeof arg === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function"; + }; + return isBufferBrowser$1; +} +var inherits_browser$1 = { exports: {} }; +var hasRequiredInherits_browser$1; +function requireInherits_browser$1() { + if (hasRequiredInherits_browser$1) return inherits_browser$1.exports; + hasRequiredInherits_browser$1 = 1; + if (typeof Object.create === "function") { + inherits_browser$1.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + inherits_browser$1.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + return inherits_browser$1.exports; +} +var hasRequiredUtil$5; +function requireUtil$5() { + if (hasRequiredUtil$5) return util$6; + hasRequiredUtil$5 = 1; + (function(exports) { + var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString2(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(" "); + } + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x2) { + if (x2 === "%%") return "%"; + if (i >= len) return x2; + switch (x2) { + case "%s": + return String(args[i++]); + case "%d": + return Number(args[i++]); + case "%j": + try { + return JSON.stringify(args[i++]); + } catch (_) { + return "[Circular]"; + } + default: + return x2; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject2(x)) { + str += " " + x; + } else { + str += " " + inspect(x); + } + } + return str; + }; + exports.deprecate = function(fn, msg) { + if (typeof process !== "undefined" && process.noDeprecation === true) { + return fn; + } + if (typeof process === "undefined") { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + return deprecated; + }; + var debugs = {}; + var debugEnvRegex = /^$/; + if (define_process_env_default.NODE_DEBUG) { + var debugEnv = define_process_env_default.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(); + debugEnvRegex = new RegExp("^" + debugEnv + "$", "i"); + } + exports.debuglog = function(set2) { + set2 = set2.toUpperCase(); + if (!debugs[set2]) { + if (debugEnvRegex.test(set2)) { + var pid = process.pid; + debugs[set2] = function() { + var msg = exports.format.apply(exports, arguments); + console.error("%s %d: %s", set2, pid, msg); + }; + } else { + debugs[set2] = function() { + }; + } + } + return debugs[set2]; + }; + function inspect(obj, opts) { + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + ctx.showHidden = opts; + } else if (opts) { + exports._extend(ctx, opts); + } + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue2(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + inspect.colors = { + "bold": [1, 22], + "italic": [3, 23], + "underline": [4, 24], + "inverse": [7, 27], + "white": [37, 39], + "grey": [90, 39], + "black": [30, 39], + "blue": [34, 39], + "cyan": [36, 39], + "green": [32, 39], + "magenta": [35, 39], + "red": [31, 39], + "yellow": [33, 39] + }; + inspect.styles = { + "special": "cyan", + "number": "yellow", + "boolean": "yellow", + "undefined": "grey", + "null": "bold", + "string": "green", + "date": "magenta", + // "name": intentionally not styling + "regexp": "red" + }; + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + if (style) { + return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m"; + } else { + return str; + } + } + function stylizeNoColor(str, styleType) { + return str; + } + function arrayToHash(array) { + var hash2 = {}; + array.forEach(function(val, idx) { + hash2[val] = true; + }); + return hash2; + } + function formatValue2(ctx, value, recurseTimes) { + if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString2(ret)) { + ret = formatValue2(ctx, ret, recurseTimes); + } + return ret; + } + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + if (isError2(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { + return formatError(value); + } + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ": " + value.name : ""; + return ctx.stylize("[Function" + name + "]", "special"); + } + if (isRegExp2(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } + if (isDate2(value)) { + return ctx.stylize(Date.prototype.toString.call(value), "date"); + } + if (isError2(value)) { + return formatError(value); + } + } + var base2 = "", array = false, braces = ["{", "}"]; + if (isArray2(value)) { + array = true; + braces = ["[", "]"]; + } + if (isFunction(value)) { + var n = value.name ? ": " + value.name : ""; + base2 = " [Function" + n + "]"; + } + if (isRegExp2(value)) { + base2 = " " + RegExp.prototype.toString.call(value); + } + if (isDate2(value)) { + base2 = " " + Date.prototype.toUTCString.call(value); + } + if (isError2(value)) { + base2 = " " + formatError(value); + } + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base2 + braces[1]; + } + if (recurseTimes < 0) { + if (isRegExp2(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } else { + return ctx.stylize("[Object]", "special"); + } + } + ctx.seen.push(value); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key2) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key2, array); + }); + } + ctx.seen.pop(); + return reduceToSingleString(output, base2, braces); + } + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize("undefined", "undefined"); + if (isString2(value)) { + var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; + return ctx.stylize(simple, "string"); + } + if (isNumber(value)) + return ctx.stylize("" + value, "number"); + if (isBoolean(value)) + return ctx.stylize("" + value, "boolean"); + if (isNull(value)) + return ctx.stylize("null", "null"); + } + function formatError(value) { + return "[" + Error.prototype.toString.call(value) + "]"; + } + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty2(value, String(i))) { + output.push(formatProperty( + ctx, + value, + recurseTimes, + visibleKeys, + String(i), + true + )); + } else { + output.push(""); + } + } + keys.forEach(function(key2) { + if (!key2.match(/^\d+$/)) { + output.push(formatProperty( + ctx, + value, + recurseTimes, + visibleKeys, + key2, + true + )); + } + }); + return output; + } + function formatProperty(ctx, value, recurseTimes, visibleKeys, key2, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key2) || { value: value[key2] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize("[Getter/Setter]", "special"); + } else { + str = ctx.stylize("[Getter]", "special"); + } + } else { + if (desc.set) { + str = ctx.stylize("[Setter]", "special"); + } + } + if (!hasOwnProperty2(visibleKeys, key2)) { + name = "[" + key2 + "]"; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue2(ctx, desc.value, null); + } else { + str = formatValue2(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf("\n") > -1) { + if (array) { + str = str.split("\n").map(function(line) { + return " " + line; + }).join("\n").slice(2); + } else { + str = "\n" + str.split("\n").map(function(line) { + return " " + line; + }).join("\n"); + } + } + } else { + str = ctx.stylize("[Circular]", "special"); + } + } + if (isUndefined(name)) { + if (array && key2.match(/^\d+$/)) { + return str; + } + name = JSON.stringify("" + key2); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, -1); + name = ctx.stylize(name, "name"); + } else { + name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, "string"); + } + } + return name + ": " + str; + } + function reduceToSingleString(output, base2, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf("\n") >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; + }, 0); + if (length > 60) { + return braces[0] + (base2 === "" ? "" : base2 + "\n ") + " " + output.join(",\n ") + " " + braces[1]; + } + return braces[0] + base2 + " " + output.join(", ") + " " + braces[1]; + } + exports.types = requireTypes(); + function isArray2(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray2; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === "number"; + } + exports.isNumber = isNumber; + function isString2(arg) { + return typeof arg === "string"; + } + exports.isString = isString2; + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports.isSymbol = isSymbol; + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + function isRegExp2(re2) { + return isObject2(re2) && objectToString(re2) === "[object RegExp]"; + } + exports.isRegExp = isRegExp2; + exports.types.isRegExp = isRegExp2; + function isObject2(arg) { + return typeof arg === "object" && arg !== null; + } + exports.isObject = isObject2; + function isDate2(d) { + return isObject2(d) && objectToString(d) === "[object Date]"; + } + exports.isDate = isDate2; + exports.types.isDate = isDate2; + function isError2(e) { + return isObject2(e) && (objectToString(e) === "[object Error]" || e instanceof Error); + } + exports.isError = isError2; + exports.types.isNativeError = isError2; + function isFunction(arg) { + return typeof arg === "function"; + } + exports.isFunction = isFunction; + function isPrimitive(arg) { + return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol + typeof arg === "undefined"; + } + exports.isPrimitive = isPrimitive; + exports.isBuffer = requireIsBufferBrowser$1(); + function objectToString(o) { + return Object.prototype.toString.call(o); + } + function pad(n) { + return n < 10 ? "0" + n.toString(10) : n.toString(10); + } + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ]; + function timestamp2() { + var d = /* @__PURE__ */ new Date(); + var time = [ + pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds()) + ].join(":"); + return [d.getDate(), months[d.getMonth()], time].join(" "); + } + exports.log = function() { + console.log("%s - %s", timestamp2(), exports.format.apply(exports, arguments)); + }; + exports.inherits = requireInherits_browser$1(); + exports._extend = function(origin, add) { + if (!add || !isObject2(add)) return origin; + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + function hasOwnProperty2(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : void 0; + exports.promisify = function promisify2(original) { + if (typeof original !== "function") + throw new TypeError('The "original" argument must be of type Function'); + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== "function") { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true + }); + return fn; + } + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function(resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function(err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + return promise; + } + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); + }; + exports.promisify.custom = kCustomPromisifiedSymbol; + function callbackifyOnRejected(reason, cb) { + if (!reason) { + var newReason = new Error("Promise was rejected with a falsy value"); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); + } + function callbackify(original) { + if (typeof original !== "function") { + throw new TypeError('The "original" argument must be of type Function'); + } + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + var maybeCb = args.pop(); + if (typeof maybeCb !== "function") { + throw new TypeError("The last argument must be of type Function"); + } + var self2 = this; + var cb = function() { + return maybeCb.apply(self2, arguments); + }; + original.apply(this, args).then( + function(ret) { + process.nextTick(cb.bind(null, null, ret)); + }, + function(rej) { + process.nextTick(callbackifyOnRejected.bind(null, rej, cb)); + } + ); + } + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties( + callbackified, + getOwnPropertyDescriptors(original) + ); + return callbackified; + } + exports.callbackify = callbackify; + })(util$6); + return util$6; +} +var hasRequiredErrors$2; +function requireErrors$2() { + if (hasRequiredErrors$2) return errors$2; + hasRequiredErrors$2 = 1; + function _typeof2(o) { + "@babel/helpers - typeof"; + return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { + return typeof o2; + } : function(o2) { + return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; + }, _typeof2(o); + } + function _createClass(Constructor, protoProps, staticProps) { + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); + Object.defineProperty(subClass, "prototype", { writable: false }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), result; + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self2, call) { + if (call && (_typeof2(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return _assertThisInitialized(self2); + } + function _assertThisInitialized(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; + } + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { + })); + return true; + } catch (e) { + return false; + } + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) { + return o2.__proto__ || Object.getPrototypeOf(o2); + }; + return _getPrototypeOf(o); + } + var codes = {}; + var assert2; + var util2; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /* @__PURE__ */ function(_Base) { + _inherits(NodeError2, _Base); + var _super = _createSuper(NodeError2); + function NodeError2(arg1, arg2, arg3) { + var _this; + _classCallCheck(this, NodeError2); + _this = _super.call(this, getMessage(arg1, arg2, arg3)); + _this.code = code; + return _this; + } + return _createClass(NodeError2); + }(Base); + codes[code] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function(i) { + return String(i); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } + function startsWith(str, search, pos) { + return str.substr(0, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_AMBIGUOUS_ARGUMENT", 'The "%s" argument is ambiguous. %s', TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + if (assert2 === void 0) assert2 = requireAssert(); + assert2(typeof name === "string", "'name' must be a string"); + var determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + var msg; + if (endsWith(name, " argument")) { + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } else { + var type2 = includes(name, ".") ? "property" : "argument"; + msg = 'The "'.concat(name, '" ').concat(type2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } + msg += ". Received type ".concat(_typeof2(actual)); + return msg; + }, TypeError); + createErrorType("ERR_INVALID_ARG_VALUE", function(name, value) { + var reason = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "is invalid"; + if (util2 === void 0) util2 = requireUtil$5(); + var inspected = util2.inspect(value); + if (inspected.length > 128) { + inspected = "".concat(inspected.slice(0, 128), "..."); + } + return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); + }, TypeError); + createErrorType("ERR_INVALID_RETURN_VALUE", function(input, name, value) { + var type2; + if (value && value.constructor && value.constructor.name) { + type2 = "instance of ".concat(value.constructor.name); + } else { + type2 = "type ".concat(_typeof2(value)); + } + return "Expected ".concat(input, ' to be returned from the "').concat(name, '"') + " function but got ".concat(type2, "."); + }, TypeError); + createErrorType("ERR_MISSING_ARGS", function() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (assert2 === void 0) assert2 = requireAssert(); + assert2(args.length > 0, "At least one arg needs to be specified"); + var msg = "The "; + var len = args.length; + args = args.map(function(a) { + return '"'.concat(a, '"'); + }); + switch (len) { + case 1: + msg += "".concat(args[0], " argument"); + break; + case 2: + msg += "".concat(args[0], " and ").concat(args[1], " arguments"); + break; + default: + msg += args.slice(0, len - 1).join(", "); + msg += ", and ".concat(args[len - 1], " arguments"); + break; + } + return "".concat(msg, " must be specified"); + }, TypeError); + errors$2.codes = codes; + return errors$2; +} +var assertion_error; +var hasRequiredAssertion_error; +function requireAssertion_error() { + if (hasRequiredAssertion_error) return assertion_error; + hasRequiredAssertion_error = 1; + function ownKeys2(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; + } + function _objectSpread(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys2(Object(t), true).forEach(function(r2) { + _defineProperty2(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys2(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; + } + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey2(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return _typeof2(key2) === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (_typeof2(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (_typeof2(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return String(input); + } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); + Object.defineProperty(subClass, "prototype", { writable: false }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), result; + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self2, call) { + if (call && (_typeof2(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return _assertThisInitialized(self2); + } + function _assertThisInitialized(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; + } + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0; + _wrapNativeSuper = function _wrapNativeSuper2(Class2) { + if (Class2 === null || !_isNativeFunction(Class2)) return Class2; + if (typeof Class2 !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class2)) return _cache.get(Class2); + _cache.set(Class2, Wrapper); + } + function Wrapper() { + return _construct(Class2, arguments, _getPrototypeOf(this).constructor); + } + Wrapper.prototype = Object.create(Class2.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); + return _setPrototypeOf(Wrapper, Class2); + }; + return _wrapNativeSuper(Class); + } + function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + _construct = function _construct2(Parent2, args2, Class2) { + var a = [null]; + a.push.apply(a, args2); + var Constructor = Function.bind.apply(Parent2, a); + var instance = new Constructor(); + if (Class2) _setPrototypeOf(instance, Class2.prototype); + return instance; + }; + } + return _construct.apply(null, arguments); + } + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { + })); + return true; + } catch (e) { + return false; + } + } + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) { + return o2.__proto__ || Object.getPrototypeOf(o2); + }; + return _getPrototypeOf(o); + } + function _typeof2(o) { + "@babel/helpers - typeof"; + return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { + return typeof o2; + } : function(o2) { + return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; + }, _typeof2(o); + } + var _require = requireUtil$5(), inspect = _require.inspect; + var _require2 = requireErrors$2(), ERR_INVALID_ARG_TYPE2 = _require2.codes.ERR_INVALID_ARG_TYPE; + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function repeat(str, count) { + count = Math.floor(count); + if (str.length == 0 || count == 0) return ""; + var maxCount = str.length * count; + count = Math.floor(Math.log(count) / Math.log(2)); + while (count) { + str += str; + count--; + } + str += str.substring(0, maxCount - str.length); + return str; + } + var blue = ""; + var green = ""; + var red = ""; + var white = ""; + var kReadableOperator = { + deepStrictEqual: "Expected values to be strictly deep-equal:", + strictEqual: "Expected values to be strictly equal:", + strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', + deepEqual: "Expected values to be loosely deep-equal:", + equal: "Expected values to be loosely equal:", + notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', + notStrictEqual: 'Expected "actual" to be strictly unequal to:', + notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', + notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', + notEqual: 'Expected "actual" to be loosely unequal to:', + notIdentical: "Values identical but not reference-equal:" + }; + var kMaxShortLength = 10; + function copyError(source2) { + var keys = Object.keys(source2); + var target = Object.create(Object.getPrototypeOf(source2)); + keys.forEach(function(key2) { + target[key2] = source2[key2]; + }); + Object.defineProperty(target, "message", { + value: source2.message + }); + return target; + } + function inspectValue(val) { + return inspect(val, { + compact: false, + customInspect: false, + depth: 1e3, + maxArrayLength: Infinity, + // Assert compares only enumerable properties (with a few exceptions). + showHidden: false, + // Having a long line as error is better than wrapping the line for + // comparison for now. + // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we + // have meta information about the inspected properties (i.e., know where + // in what line the property starts and ends). + breakLength: Infinity, + // Assert does not detect proxies currently. + showProxy: false, + sorted: true, + // Inspect getters as we also check them when comparing entries. + getters: true + }); + } + function createErrDiff(actual, expected, operator) { + var other2 = ""; + var res = ""; + var lastPos = 0; + var end = ""; + var skipped = false; + var actualInspected = inspectValue(actual); + var actualLines = actualInspected.split("\n"); + var expectedLines = inspectValue(expected).split("\n"); + var i = 0; + var indicator = ""; + if (operator === "strictEqual" && _typeof2(actual) === "object" && _typeof2(expected) === "object" && actual !== null && expected !== null) { + operator = "strictEqualObject"; + } + if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { + var inputLength = actualLines[0].length + expectedLines[0].length; + if (inputLength <= kMaxShortLength) { + if ((_typeof2(actual) !== "object" || actual === null) && (_typeof2(expected) !== "object" || expected === null) && (actual !== 0 || expected !== 0)) { + return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); + } + } else if (operator !== "strictEqualObject") { + var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; + if (inputLength < maxLength) { + while (actualLines[0][i] === expectedLines[0][i]) { + i++; + } + if (i > 2) { + indicator = "\n ".concat(repeat(" ", i), "^"); + i = 0; + } + } + } + } + var a = actualLines[actualLines.length - 1]; + var b = expectedLines[expectedLines.length - 1]; + while (a === b) { + if (i++ < 2) { + end = "\n ".concat(a).concat(end); + } else { + other2 = a; + } + actualLines.pop(); + expectedLines.pop(); + if (actualLines.length === 0 || expectedLines.length === 0) break; + a = actualLines[actualLines.length - 1]; + b = expectedLines[expectedLines.length - 1]; + } + var maxLines = Math.max(actualLines.length, expectedLines.length); + if (maxLines === 0) { + var _actualLines = actualInspected.split("\n"); + if (_actualLines.length > 30) { + _actualLines[26] = "".concat(blue, "...").concat(white); + while (_actualLines.length > 27) { + _actualLines.pop(); + } + } + return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join("\n"), "\n"); + } + if (i > 3) { + end = "\n".concat(blue, "...").concat(white).concat(end); + skipped = true; + } + if (other2 !== "") { + end = "\n ".concat(other2).concat(end); + other2 = ""; + } + var printedLines = 0; + var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); + var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); + for (i = 0; i < maxLines; i++) { + var cur = i - lastPos; + if (actualLines.length < i + 1) { + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(expectedLines[i - 2]); + printedLines++; + } + res += "\n ".concat(expectedLines[i - 1]); + printedLines++; + } + lastPos = i; + other2 += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); + printedLines++; + } else if (expectedLines.length < i + 1) { + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + lastPos = i; + res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); + printedLines++; + } else { + var expectedLine = expectedLines[i]; + var actualLine = actualLines[i]; + var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ",") || actualLine.slice(0, -1) !== expectedLine); + if (divergingLines && endsWith(expectedLine, ",") && expectedLine.slice(0, -1) === actualLine) { + divergingLines = false; + actualLine += ","; + } + if (divergingLines) { + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + lastPos = i; + res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); + other2 += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); + printedLines += 2; + } else { + res += other2; + other2 = ""; + if (cur === 1 || i === 0) { + res += "\n ".concat(actualLine); + printedLines++; + } + } + } + if (printedLines > 20 && i < maxLines - 2) { + return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other2, "\n") + "".concat(blue, "...").concat(white); + } + } + return "".concat(msg).concat(skipped ? skippedMsg : "", "\n").concat(res).concat(other2).concat(end).concat(indicator); + } + var AssertionError = /* @__PURE__ */ function(_Error, _inspect$custom) { + _inherits(AssertionError2, _Error); + var _super = _createSuper(AssertionError2); + function AssertionError2(options2) { + var _this; + _classCallCheck(this, AssertionError2); + if (_typeof2(options2) !== "object" || options2 === null) { + throw new ERR_INVALID_ARG_TYPE2("options", "Object", options2); + } + var message = options2.message, operator = options2.operator, stackStartFn = options2.stackStartFn; + var actual = options2.actual, expected = options2.expected; + var limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + if (message != null) { + _this = _super.call(this, String(message)); + } else { + if (process.stderr && process.stderr.isTTY) { + if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { + blue = "\x1B[34m"; + green = "\x1B[32m"; + white = "\x1B[39m"; + red = "\x1B[31m"; + } else { + blue = ""; + green = ""; + white = ""; + red = ""; + } + } + if (_typeof2(actual) === "object" && actual !== null && _typeof2(expected) === "object" && expected !== null && "stack" in actual && actual instanceof Error && "stack" in expected && expected instanceof Error) { + actual = copyError(actual); + expected = copyError(expected); + } + if (operator === "deepStrictEqual" || operator === "strictEqual") { + _this = _super.call(this, createErrDiff(actual, expected, operator)); + } else if (operator === "notDeepStrictEqual" || operator === "notStrictEqual") { + var base2 = kReadableOperator[operator]; + var res = inspectValue(actual).split("\n"); + if (operator === "notStrictEqual" && _typeof2(actual) === "object" && actual !== null) { + base2 = kReadableOperator.notStrictEqualObject; + } + if (res.length > 30) { + res[26] = "".concat(blue, "...").concat(white); + while (res.length > 27) { + res.pop(); + } + } + if (res.length === 1) { + _this = _super.call(this, "".concat(base2, " ").concat(res[0])); + } else { + _this = _super.call(this, "".concat(base2, "\n\n").concat(res.join("\n"), "\n")); + } + } else { + var _res = inspectValue(actual); + var other2 = ""; + var knownOperators = kReadableOperator[operator]; + if (operator === "notDeepEqual" || operator === "notEqual") { + _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); + if (_res.length > 1024) { + _res = "".concat(_res.slice(0, 1021), "..."); + } + } else { + other2 = "".concat(inspectValue(expected)); + if (_res.length > 512) { + _res = "".concat(_res.slice(0, 509), "..."); + } + if (other2.length > 512) { + other2 = "".concat(other2.slice(0, 509), "..."); + } + if (operator === "deepEqual" || operator === "equal") { + _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); + } else { + other2 = " ".concat(operator, " ").concat(other2); + } + } + _this = _super.call(this, "".concat(_res).concat(other2)); + } + } + Error.stackTraceLimit = limit; + _this.generatedMessage = !message; + Object.defineProperty(_assertThisInitialized(_this), "name", { + value: "AssertionError [ERR_ASSERTION]", + enumerable: false, + writable: true, + configurable: true + }); + _this.code = "ERR_ASSERTION"; + _this.actual = actual; + _this.expected = expected; + _this.operator = operator; + if (Error.captureStackTrace) { + Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); + } + _this.stack; + _this.name = "AssertionError"; + return _possibleConstructorReturn(_this); + } + _createClass(AssertionError2, [{ + key: "toString", + value: function toString2() { + return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); + } + }, { + key: _inspect$custom, + value: function value(recurseTimes, ctx) { + return inspect(this, _objectSpread(_objectSpread({}, ctx), {}, { + customInspect: false, + depth: 0 + })); + } + }]); + return AssertionError2; + }(/* @__PURE__ */ _wrapNativeSuper(Error), inspect.custom); + assertion_error = AssertionError; + return assertion_error; +} +var isArguments; +var hasRequiredIsArguments; +function requireIsArguments() { + if (hasRequiredIsArguments) return isArguments; + hasRequiredIsArguments = 1; + var toStr = Object.prototype.toString; + isArguments = function isArguments2(value) { + var str = toStr.call(value); + var isArgs = str === "[object Arguments]"; + if (!isArgs) { + isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr.call(value.callee) === "[object Function]"; + } + return isArgs; + }; + return isArguments; +} +var implementation$3; +var hasRequiredImplementation$3; +function requireImplementation$3() { + if (hasRequiredImplementation$3) return implementation$3; + hasRequiredImplementation$3 = 1; + var keysShim; + if (!Object.keys) { + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = requireIsArguments(); + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString"); + var hasProtoEnumBug = isEnumerable.call(function() { + }, "prototype"); + var dontEnums = [ + "toString", + "toLocaleString", + "valueOf", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "constructor" + ]; + var equalsConstructorPrototype = function(o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = function() { + if (typeof window === "undefined") { + return false; + } + for (var k in window) { + try { + if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }(); + var equalsConstructorPrototypeIfNotBuggy = function(o) { + if (typeof window === "undefined" || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + keysShim = function keys(object) { + var isObject2 = object !== null && typeof object === "object"; + var isFunction = toStr.call(object) === "[object Function]"; + var isArguments2 = isArgs(object); + var isString2 = isObject2 && toStr.call(object) === "[object String]"; + var theKeys = []; + if (!isObject2 && !isFunction && !isArguments2) { + throw new TypeError("Object.keys called on a non-object"); + } + var skipProto = hasProtoEnumBug && isFunction; + if (isString2 && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + if (isArguments2 && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === "prototype") && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; + } + implementation$3 = keysShim; + return implementation$3; +} +var objectKeys; +var hasRequiredObjectKeys; +function requireObjectKeys() { + if (hasRequiredObjectKeys) return objectKeys; + hasRequiredObjectKeys = 1; + var slice = Array.prototype.slice; + var isArgs = requireIsArguments(); + var origKeys = Object.keys; + var keysShim = origKeys ? function keys(o) { + return origKeys(o); + } : requireImplementation$3(); + var originalKeys = Object.keys; + keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = function() { + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; + }; + objectKeys = keysShim; + return objectKeys; +} +var implementation$2; +var hasRequiredImplementation$2; +function requireImplementation$2() { + if (hasRequiredImplementation$2) return implementation$2; + hasRequiredImplementation$2 = 1; + var objectKeys2 = requireObjectKeys(); + var hasSymbols2 = requireShams$1()(); + var callBound2 = /* @__PURE__ */ requireCallBound(); + var $Object = /* @__PURE__ */ requireEsObjectAtoms(); + var $push = callBound2("Array.prototype.push"); + var $propIsEnumerable = callBound2("Object.prototype.propertyIsEnumerable"); + var originalGetSymbols = hasSymbols2 ? $Object.getOwnPropertySymbols : null; + implementation$2 = function assign(target, source1) { + if (target == null) { + throw new TypeError("target must be an object"); + } + var to = $Object(target); + if (arguments.length === 1) { + return to; + } + for (var s = 1; s < arguments.length; ++s) { + var from2 = $Object(arguments[s]); + var keys = objectKeys2(from2); + var getSymbols = hasSymbols2 && ($Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from2); + for (var j = 0; j < syms.length; ++j) { + var key2 = syms[j]; + if ($propIsEnumerable(from2, key2)) { + $push(keys, key2); + } + } + } + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from2, nextKey)) { + var propValue = from2[nextKey]; + to[nextKey] = propValue; + } + } + } + return to; + }; + return implementation$2; +} +var polyfill$2; +var hasRequiredPolyfill$2; +function requirePolyfill$2() { + if (hasRequiredPolyfill$2) return polyfill$2; + hasRequiredPolyfill$2 = 1; + var implementation2 = requireImplementation$2(); + var lacksProperEnumerationOrder = function() { + if (!Object.assign) { + return false; + } + var str = "abcdefghijklmnopqrst"; + var letters = str.split(""); + var map2 = {}; + for (var i = 0; i < letters.length; ++i) { + map2[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map2); + var actual = ""; + for (var k in obj) { + actual += k; + } + return str !== actual; + }; + var assignHasPendingExceptions = function() { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, "xy"); + } catch (e) { + return thrower[1] === "y"; + } + return false; + }; + polyfill$2 = function getPolyfill() { + if (!Object.assign) { + return implementation2; + } + if (lacksProperEnumerationOrder()) { + return implementation2; + } + if (assignHasPendingExceptions()) { + return implementation2; + } + return Object.assign; + }; + return polyfill$2; +} +var implementation$1; +var hasRequiredImplementation$1; +function requireImplementation$1() { + if (hasRequiredImplementation$1) return implementation$1; + hasRequiredImplementation$1 = 1; + var numberIsNaN = function(value) { + return value !== value; + }; + implementation$1 = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } + if (a === b) { + return true; + } + if (numberIsNaN(a) && numberIsNaN(b)) { + return true; + } + return false; + }; + return implementation$1; +} +var polyfill$1; +var hasRequiredPolyfill$1; +function requirePolyfill$1() { + if (hasRequiredPolyfill$1) return polyfill$1; + hasRequiredPolyfill$1 = 1; + var implementation2 = requireImplementation$1(); + polyfill$1 = function getPolyfill() { + return typeof Object.is === "function" ? Object.is : implementation2; + }; + return polyfill$1; +} +var defineProperties_1; +var hasRequiredDefineProperties; +function requireDefineProperties() { + if (hasRequiredDefineProperties) return defineProperties_1; + hasRequiredDefineProperties = 1; + var keys = requireObjectKeys(); + var hasSymbols2 = typeof Symbol === "function" && typeof Symbol("foo") === "symbol"; + var toStr = Object.prototype.toString; + var concat = Array.prototype.concat; + var defineDataProperty2 = /* @__PURE__ */ requireDefineDataProperty(); + var isFunction = function(fn) { + return typeof fn === "function" && toStr.call(fn) === "[object Function]"; + }; + var supportsDescriptors = /* @__PURE__ */ requireHasPropertyDescriptors()(); + var defineProperty = function(object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction(predicate) || !predicate()) { + return; + } + } + if (supportsDescriptors) { + defineDataProperty2(object, name, value, true); + } else { + defineDataProperty2(object, name, value); + } + }; + var defineProperties = function(object, map2) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map2); + if (hasSymbols2) { + props = concat.call(props, Object.getOwnPropertySymbols(map2)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map2[props[i]], predicates[props[i]]); + } + }; + defineProperties.supportsDescriptors = !!supportsDescriptors; + defineProperties_1 = defineProperties; + return defineProperties_1; +} +var shim$1; +var hasRequiredShim$1; +function requireShim$1() { + if (hasRequiredShim$1) return shim$1; + hasRequiredShim$1 = 1; + var getPolyfill = requirePolyfill$1(); + var define = requireDefineProperties(); + shim$1 = function shimObjectIs() { + var polyfill2 = getPolyfill(); + define(Object, { is: polyfill2 }, { + is: function testObjectIs() { + return Object.is !== polyfill2; + } + }); + return polyfill2; + }; + return shim$1; +} +var objectIs; +var hasRequiredObjectIs; +function requireObjectIs() { + if (hasRequiredObjectIs) return objectIs; + hasRequiredObjectIs = 1; + var define = requireDefineProperties(); + var callBind2 = requireCallBind(); + var implementation2 = requireImplementation$1(); + var getPolyfill = requirePolyfill$1(); + var shim2 = requireShim$1(); + var polyfill2 = callBind2(getPolyfill(), Object); + define(polyfill2, { + getPolyfill, + implementation: implementation2, + shim: shim2 + }); + objectIs = polyfill2; + return objectIs; +} +var implementation; +var hasRequiredImplementation; +function requireImplementation() { + if (hasRequiredImplementation) return implementation; + hasRequiredImplementation = 1; + implementation = function isNaN2(value) { + return value !== value; + }; + return implementation; +} +var polyfill; +var hasRequiredPolyfill; +function requirePolyfill() { + if (hasRequiredPolyfill) return polyfill; + hasRequiredPolyfill = 1; + var implementation2 = requireImplementation(); + polyfill = function getPolyfill() { + if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN("a")) { + return Number.isNaN; + } + return implementation2; + }; + return polyfill; +} +var shim; +var hasRequiredShim; +function requireShim() { + if (hasRequiredShim) return shim; + hasRequiredShim = 1; + var define = requireDefineProperties(); + var getPolyfill = requirePolyfill(); + shim = function shimNumberIsNaN() { + var polyfill2 = getPolyfill(); + define(Number, { isNaN: polyfill2 }, { + isNaN: function testIsNaN() { + return Number.isNaN !== polyfill2; + } + }); + return polyfill2; + }; + return shim; +} +var isNan; +var hasRequiredIsNan; +function requireIsNan() { + if (hasRequiredIsNan) return isNan; + hasRequiredIsNan = 1; + var callBind2 = requireCallBind(); + var define = requireDefineProperties(); + var implementation2 = requireImplementation(); + var getPolyfill = requirePolyfill(); + var shim2 = requireShim(); + var polyfill2 = callBind2(getPolyfill(), Number); + define(polyfill2, { + getPolyfill, + implementation: implementation2, + shim: shim2 + }); + isNan = polyfill2; + return isNan; +} +var comparisons; +var hasRequiredComparisons; +function requireComparisons() { + if (hasRequiredComparisons) return comparisons; + hasRequiredComparisons = 1; + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray2(arr, i) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _unsupportedIterableToArray2(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray2(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray2(o, minLen); + } + function _arrayLikeToArray2(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; + } + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, n, i, u, a = [], f = true, o = false; + try { + if (i = (t = t.call(r)).next, 0 === l) ; + else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true) ; + } catch (r2) { + o = true, n = r2; + } finally { + try { + if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; + } finally { + if (o) throw n; + } + } + return a; + } + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _typeof2(o) { + "@babel/helpers - typeof"; + return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { + return typeof o2; + } : function(o2) { + return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; + }, _typeof2(o); + } + var regexFlagsSupported = /a/g.flags !== void 0; + var arrayFromSet = function arrayFromSet2(set2) { + var array = []; + set2.forEach(function(value) { + return array.push(value); + }); + return array; + }; + var arrayFromMap = function arrayFromMap2(map2) { + var array = []; + map2.forEach(function(value, key2) { + return array.push([key2, value]); + }); + return array; + }; + var objectIs2 = Object.is ? Object.is : requireObjectIs(); + var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function() { + return []; + }; + var numberIsNaN = Number.isNaN ? Number.isNaN : requireIsNan(); + function uncurryThis(f) { + return f.call.bind(f); + } + var hasOwnProperty2 = uncurryThis(Object.prototype.hasOwnProperty); + var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); + var objectToString = uncurryThis(Object.prototype.toString); + var _require$types = requireUtil$5().types, isAnyArrayBuffer = _require$types.isAnyArrayBuffer, isArrayBufferView = _require$types.isArrayBufferView, isDate2 = _require$types.isDate, isMap2 = _require$types.isMap, isRegExp2 = _require$types.isRegExp, isSet = _require$types.isSet, isNativeError = _require$types.isNativeError, isBoxedPrimitive = _require$types.isBoxedPrimitive, isNumberObject = _require$types.isNumberObject, isStringObject = _require$types.isStringObject, isBooleanObject = _require$types.isBooleanObject, isBigIntObject = _require$types.isBigIntObject, isSymbolObject = _require$types.isSymbolObject, isFloat32Array = _require$types.isFloat32Array, isFloat64Array = _require$types.isFloat64Array; + function isNonIndex(key2) { + if (key2.length === 0 || key2.length > 10) return true; + for (var i = 0; i < key2.length; i++) { + var code = key2.charCodeAt(i); + if (code < 48 || code > 57) return true; + } + return key2.length === 10 && key2 >= Math.pow(2, 32); + } + function getOwnNonIndexProperties(value) { + return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); + } + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + function compare2(a, b) { + if (a === b) { + return 0; + } + var x = a.length; + var y = b.length; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; + } + var kStrict = true; + var kLoose = false; + var kNoIterator = 0; + var kIsArray = 1; + var kIsSet = 2; + var kIsMap = 3; + function areSimilarRegExps(a, b) { + return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); + } + function areSimilarFloatArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (var offset2 = 0; offset2 < a.byteLength; offset2++) { + if (a[offset2] !== b[offset2]) { + return false; + } + } + return true; + } + function areSimilarTypedArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + return compare2(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; + } + function areEqualArrayBuffers(buf1, buf2) { + return buf1.byteLength === buf2.byteLength && compare2(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; + } + function isEqualBoxedPrimitive(val1, val2) { + if (isNumberObject(val1)) { + return isNumberObject(val2) && objectIs2(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); + } + if (isStringObject(val1)) { + return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); + } + if (isBooleanObject(val1)) { + return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); + } + if (isBigIntObject(val1)) { + return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); + } + return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); + } + function innerDeepEqual(val1, val2, strict, memos) { + if (val1 === val2) { + if (val1 !== 0) return true; + return strict ? objectIs2(val1, val2) : true; + } + if (strict) { + if (_typeof2(val1) !== "object") { + return typeof val1 === "number" && numberIsNaN(val1) && numberIsNaN(val2); + } + if (_typeof2(val2) !== "object" || val1 === null || val2 === null) { + return false; + } + if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { + return false; + } + } else { + if (val1 === null || _typeof2(val1) !== "object") { + if (val2 === null || _typeof2(val2) !== "object") { + return val1 == val2; + } + return false; + } + if (val2 === null || _typeof2(val2) !== "object") { + return false; + } + } + var val1Tag = objectToString(val1); + var val2Tag = objectToString(val2); + if (val1Tag !== val2Tag) { + return false; + } + if (Array.isArray(val1)) { + if (val1.length !== val2.length) { + return false; + } + var keys1 = getOwnNonIndexProperties(val1); + var keys2 = getOwnNonIndexProperties(val2); + if (keys1.length !== keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsArray, keys1); + } + if (val1Tag === "[object Object]") { + if (!isMap2(val1) && isMap2(val2) || !isSet(val1) && isSet(val2)) { + return false; + } + } + if (isDate2(val1)) { + if (!isDate2(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { + return false; + } + } else if (isRegExp2(val1)) { + if (!isRegExp2(val2) || !areSimilarRegExps(val1, val2)) { + return false; + } + } else if (isNativeError(val1) || val1 instanceof Error) { + if (val1.message !== val2.message || val1.name !== val2.name) { + return false; + } + } else if (isArrayBufferView(val1)) { + if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { + if (!areSimilarFloatArrays(val1, val2)) { + return false; + } + } else if (!areSimilarTypedArrays(val1, val2)) { + return false; + } + var _keys = getOwnNonIndexProperties(val1); + var _keys2 = getOwnNonIndexProperties(val2); + if (_keys.length !== _keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); + } else if (isSet(val1)) { + if (!isSet(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsSet); + } else if (isMap2(val1)) { + if (!isMap2(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsMap); + } else if (isAnyArrayBuffer(val1)) { + if (!areEqualArrayBuffers(val1, val2)) { + return false; + } + } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator); + } + function getEnumerables(val, keys) { + return keys.filter(function(k) { + return propertyIsEnumerable(val, k); + }); + } + function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { + if (arguments.length === 5) { + aKeys = Object.keys(val1); + var bKeys = Object.keys(val2); + if (aKeys.length !== bKeys.length) { + return false; + } + } + var i = 0; + for (; i < aKeys.length; i++) { + if (!hasOwnProperty2(val2, aKeys[i])) { + return false; + } + } + if (strict && arguments.length === 5) { + var symbolKeysA = objectGetOwnPropertySymbols(val1); + if (symbolKeysA.length !== 0) { + var count = 0; + for (i = 0; i < symbolKeysA.length; i++) { + var key2 = symbolKeysA[i]; + if (propertyIsEnumerable(val1, key2)) { + if (!propertyIsEnumerable(val2, key2)) { + return false; + } + aKeys.push(key2); + count++; + } else if (propertyIsEnumerable(val2, key2)) { + return false; + } + } + var symbolKeysB = objectGetOwnPropertySymbols(val2); + if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { + return false; + } + } else { + var _symbolKeysB = objectGetOwnPropertySymbols(val2); + if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { + return false; + } + } + } + if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { + return true; + } + if (memos === void 0) { + memos = { + val1: /* @__PURE__ */ new Map(), + val2: /* @__PURE__ */ new Map(), + position: 0 + }; + } else { + var val2MemoA = memos.val1.get(val1); + if (val2MemoA !== void 0) { + var val2MemoB = memos.val2.get(val2); + if (val2MemoB !== void 0) { + return val2MemoA === val2MemoB; + } + } + memos.position++; + } + memos.val1.set(val1, memos.position); + memos.val2.set(val2, memos.position); + var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); + memos.val1.delete(val1); + memos.val2.delete(val2); + return areEq; + } + function setHasEqualElement(set2, val1, strict, memo) { + var setValues = arrayFromSet(set2); + for (var i = 0; i < setValues.length; i++) { + var val2 = setValues[i]; + if (innerDeepEqual(val1, val2, strict, memo)) { + set2.delete(val2); + return true; + } + } + return false; + } + function findLooseMatchingPrimitives(prim) { + switch (_typeof2(prim)) { + case "undefined": + return null; + case "object": + return void 0; + case "symbol": + return false; + case "string": + prim = +prim; + // Loose equal entries exist only if the string is possible to convert to + // a regular number and not NaN. + // Fall through + case "number": + if (numberIsNaN(prim)) { + return false; + } + } + return true; + } + function setMightHaveLoosePrim(a, b, prim) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) return altValue; + return b.has(altValue) && !a.has(altValue); + } + function mapMightHaveLoosePrim(a, b, prim, item, memo) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) { + return altValue; + } + var curB = b.get(altValue); + if (curB === void 0 && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { + return false; + } + return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); + } + function setEquiv(a, b, strict, memo) { + var set2 = null; + var aValues = arrayFromSet(a); + for (var i = 0; i < aValues.length; i++) { + var val = aValues[i]; + if (_typeof2(val) === "object" && val !== null) { + if (set2 === null) { + set2 = /* @__PURE__ */ new Set(); + } + set2.add(val); + } else if (!b.has(val)) { + if (strict) return false; + if (!setMightHaveLoosePrim(a, b, val)) { + return false; + } + if (set2 === null) { + set2 = /* @__PURE__ */ new Set(); + } + set2.add(val); + } + } + if (set2 !== null) { + var bValues = arrayFromSet(b); + for (var _i2 = 0; _i2 < bValues.length; _i2++) { + var _val = bValues[_i2]; + if (_typeof2(_val) === "object" && _val !== null) { + if (!setHasEqualElement(set2, _val, strict, memo)) return false; + } else if (!strict && !a.has(_val) && !setHasEqualElement(set2, _val, strict, memo)) { + return false; + } + } + return set2.size === 0; + } + return true; + } + function mapHasEqualEntry(set2, map2, key1, item1, strict, memo) { + var setValues = arrayFromSet(set2); + for (var i = 0; i < setValues.length; i++) { + var key2 = setValues[i]; + if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map2.get(key2), strict, memo)) { + set2.delete(key2); + return true; + } + } + return false; + } + function mapEquiv(a, b, strict, memo) { + var set2 = null; + var aEntries = arrayFromMap(a); + for (var i = 0; i < aEntries.length; i++) { + var _aEntries$i = _slicedToArray(aEntries[i], 2), key2 = _aEntries$i[0], item1 = _aEntries$i[1]; + if (_typeof2(key2) === "object" && key2 !== null) { + if (set2 === null) { + set2 = /* @__PURE__ */ new Set(); + } + set2.add(key2); + } else { + var item2 = b.get(key2); + if (item2 === void 0 && !b.has(key2) || !innerDeepEqual(item1, item2, strict, memo)) { + if (strict) return false; + if (!mapMightHaveLoosePrim(a, b, key2, item1, memo)) return false; + if (set2 === null) { + set2 = /* @__PURE__ */ new Set(); + } + set2.add(key2); + } + } + } + if (set2 !== null) { + var bEntries = arrayFromMap(b); + for (var _i2 = 0; _i2 < bEntries.length; _i2++) { + var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), _key = _bEntries$_i[0], item = _bEntries$_i[1]; + if (_typeof2(_key) === "object" && _key !== null) { + if (!mapHasEqualEntry(set2, a, _key, item, strict, memo)) return false; + } else if (!strict && (!a.has(_key) || !innerDeepEqual(a.get(_key), item, false, memo)) && !mapHasEqualEntry(set2, a, _key, item, false, memo)) { + return false; + } + } + return set2.size === 0; + } + return true; + } + function objEquiv(a, b, strict, keys, memos, iterationType) { + var i = 0; + if (iterationType === kIsSet) { + if (!setEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsMap) { + if (!mapEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsArray) { + for (; i < a.length; i++) { + if (hasOwnProperty2(a, i)) { + if (!hasOwnProperty2(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { + return false; + } + } else if (hasOwnProperty2(b, i)) { + return false; + } else { + var keysA = Object.keys(a); + for (; i < keysA.length; i++) { + var key2 = keysA[i]; + if (!hasOwnProperty2(b, key2) || !innerDeepEqual(a[key2], b[key2], strict, memos)) { + return false; + } + } + if (keysA.length !== Object.keys(b).length) { + return false; + } + return true; + } + } + } + for (i = 0; i < keys.length; i++) { + var _key2 = keys[i]; + if (!innerDeepEqual(a[_key2], b[_key2], strict, memos)) { + return false; + } + } + return true; + } + function isDeepEqual(val1, val2) { + return innerDeepEqual(val1, val2, kLoose); + } + function isDeepStrictEqual(val1, val2) { + return innerDeepEqual(val1, val2, kStrict); + } + comparisons = { + isDeepEqual, + isDeepStrictEqual + }; + return comparisons; +} +var hasRequiredAssert; +function requireAssert() { + if (hasRequiredAssert) return assert$1.exports; + hasRequiredAssert = 1; + function _typeof2(o) { + "@babel/helpers - typeof"; + return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { + return typeof o2; + } : function(o2) { + return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; + }, _typeof2(o); + } + function _createClass(Constructor, protoProps, staticProps) { + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + var _require = requireErrors$2(), _require$codes = _require.codes, ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var AssertionError = requireAssertion_error(); + var _require2 = requireUtil$5(), inspect = _require2.inspect; + var _require$types = requireUtil$5().types, isPromise = _require$types.isPromise, isRegExp2 = _require$types.isRegExp; + var objectAssign = requirePolyfill$2()(); + var objectIs2 = requirePolyfill$1()(); + var RegExpPrototypeTest = requireCallBound$1()("RegExp.prototype.test"); + var isDeepEqual; + var isDeepStrictEqual; + function lazyLoadComparison() { + var comparison = requireComparisons(); + isDeepEqual = comparison.isDeepEqual; + isDeepStrictEqual = comparison.isDeepStrictEqual; + } + var warned = false; + var assert2 = assert$1.exports = ok; + var NO_EXCEPTION_SENTINEL = {}; + function innerFail(obj) { + if (obj.message instanceof Error) throw obj.message; + throw new AssertionError(obj); + } + function fail(actual, expected, message, operator, stackStartFn) { + var argsLen = arguments.length; + var internalMessage; + if (argsLen === 0) { + internalMessage = "Failed"; + } else if (argsLen === 1) { + message = actual; + actual = void 0; + } else { + if (warned === false) { + warned = true; + var warn2 = process.emitWarning ? process.emitWarning : console.warn.bind(console); + warn2("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.", "DeprecationWarning", "DEP0094"); + } + if (argsLen === 2) operator = "!="; + } + if (message instanceof Error) throw message; + var errArgs = { + actual, + expected, + operator: operator === void 0 ? "fail" : operator, + stackStartFn: stackStartFn || fail + }; + if (message !== void 0) { + errArgs.message = message; + } + var err = new AssertionError(errArgs); + if (internalMessage) { + err.message = internalMessage; + err.generatedMessage = true; + } + throw err; + } + assert2.fail = fail; + assert2.AssertionError = AssertionError; + function innerOk(fn, argLen, value, message) { + if (!value) { + var generatedMessage = false; + if (argLen === 0) { + generatedMessage = true; + message = "No value argument passed to `assert.ok()`"; + } else if (message instanceof Error) { + throw message; + } + var err = new AssertionError({ + actual: value, + expected: true, + message, + operator: "==", + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } + } + function ok() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + innerOk.apply(void 0, [ok, args.length].concat(args)); + } + assert2.ok = ok; + assert2.equal = function equal(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (actual != expected) { + innerFail({ + actual, + expected, + message, + operator: "==", + stackStartFn: equal + }); + } + }; + assert2.notEqual = function notEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (actual == expected) { + innerFail({ + actual, + expected, + message, + operator: "!=", + stackStartFn: notEqual + }); + } + }; + assert2.deepEqual = function deepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (isDeepEqual === void 0) lazyLoadComparison(); + if (!isDeepEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "deepEqual", + stackStartFn: deepEqual + }); + } + }; + assert2.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (isDeepEqual === void 0) lazyLoadComparison(); + if (isDeepEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "notDeepEqual", + stackStartFn: notDeepEqual + }); + } + }; + assert2.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (isDeepEqual === void 0) lazyLoadComparison(); + if (!isDeepStrictEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "deepStrictEqual", + stackStartFn: deepStrictEqual + }); + } + }; + assert2.notDeepStrictEqual = notDeepStrictEqual; + function notDeepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (isDeepEqual === void 0) lazyLoadComparison(); + if (isDeepStrictEqual(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "notDeepStrictEqual", + stackStartFn: notDeepStrictEqual + }); + } + } + assert2.strictEqual = function strictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (!objectIs2(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "strictEqual", + stackStartFn: strictEqual + }); + } + }; + assert2.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS("actual", "expected"); + } + if (objectIs2(actual, expected)) { + innerFail({ + actual, + expected, + message, + operator: "notStrictEqual", + stackStartFn: notStrictEqual + }); + } + }; + var Comparison = /* @__PURE__ */ _createClass(function Comparison2(obj, keys, actual) { + var _this = this; + _classCallCheck(this, Comparison2); + keys.forEach(function(key2) { + if (key2 in obj) { + if (actual !== void 0 && typeof actual[key2] === "string" && isRegExp2(obj[key2]) && RegExpPrototypeTest(obj[key2], actual[key2])) { + _this[key2] = actual[key2]; + } else { + _this[key2] = obj[key2]; + } + } + }); + }); + function compareExceptionKey(actual, expected, key2, message, keys, fn) { + if (!(key2 in actual) || !isDeepStrictEqual(actual[key2], expected[key2])) { + if (!message) { + var a = new Comparison(actual, keys); + var b = new Comparison(expected, keys, actual); + var err = new AssertionError({ + actual: a, + expected: b, + operator: "deepStrictEqual", + stackStartFn: fn + }); + err.actual = actual; + err.expected = expected; + err.operator = fn.name; + throw err; + } + innerFail({ + actual, + expected, + message, + operator: fn.name, + stackStartFn: fn + }); + } + } + function expectedException(actual, expected, msg, fn) { + if (typeof expected !== "function") { + if (isRegExp2(expected)) return RegExpPrototypeTest(expected, actual); + if (arguments.length === 2) { + throw new ERR_INVALID_ARG_TYPE2("expected", ["Function", "RegExp"], expected); + } + if (_typeof2(actual) !== "object" || actual === null) { + var err = new AssertionError({ + actual, + expected, + message: msg, + operator: "deepStrictEqual", + stackStartFn: fn + }); + err.operator = fn.name; + throw err; + } + var keys = Object.keys(expected); + if (expected instanceof Error) { + keys.push("name", "message"); + } else if (keys.length === 0) { + throw new ERR_INVALID_ARG_VALUE("error", expected, "may not be an empty object"); + } + if (isDeepEqual === void 0) lazyLoadComparison(); + keys.forEach(function(key2) { + if (typeof actual[key2] === "string" && isRegExp2(expected[key2]) && RegExpPrototypeTest(expected[key2], actual[key2])) { + return; + } + compareExceptionKey(actual, expected, key2, msg, keys, fn); + }); + return true; + } + if (expected.prototype !== void 0 && actual instanceof expected) { + return true; + } + if (Error.isPrototypeOf(expected)) { + return false; + } + return expected.call({}, actual) === true; + } + function getActual(fn) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", "Function", fn); + } + try { + fn(); + } catch (e) { + return e; + } + return NO_EXCEPTION_SENTINEL; + } + function checkIsPromise(obj) { + return isPromise(obj) || obj !== null && _typeof2(obj) === "object" && typeof obj.then === "function" && typeof obj.catch === "function"; + } + function waitForActual(promiseFn) { + return Promise.resolve().then(function() { + var resultPromise; + if (typeof promiseFn === "function") { + resultPromise = promiseFn(); + if (!checkIsPromise(resultPromise)) { + throw new ERR_INVALID_RETURN_VALUE("instance of Promise", "promiseFn", resultPromise); + } + } else if (checkIsPromise(promiseFn)) { + resultPromise = promiseFn; + } else { + throw new ERR_INVALID_ARG_TYPE2("promiseFn", ["Function", "Promise"], promiseFn); + } + return Promise.resolve().then(function() { + return resultPromise; + }).then(function() { + return NO_EXCEPTION_SENTINEL; + }).catch(function(e) { + return e; + }); + }); + } + function expectsError(stackStartFn, actual, error2, message) { + if (typeof error2 === "string") { + if (arguments.length === 4) { + throw new ERR_INVALID_ARG_TYPE2("error", ["Object", "Error", "Function", "RegExp"], error2); + } + if (_typeof2(actual) === "object" && actual !== null) { + if (actual.message === error2) { + throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error message "'.concat(actual.message, '" is identical to the message.')); + } + } else if (actual === error2) { + throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error "'.concat(actual, '" is identical to the message.')); + } + message = error2; + error2 = void 0; + } else if (error2 != null && _typeof2(error2) !== "object" && typeof error2 !== "function") { + throw new ERR_INVALID_ARG_TYPE2("error", ["Object", "Error", "Function", "RegExp"], error2); + } + if (actual === NO_EXCEPTION_SENTINEL) { + var details = ""; + if (error2 && error2.name) { + details += " (".concat(error2.name, ")"); + } + details += message ? ": ".concat(message) : "."; + var fnType = stackStartFn.name === "rejects" ? "rejection" : "exception"; + innerFail({ + actual: void 0, + expected: error2, + operator: stackStartFn.name, + message: "Missing expected ".concat(fnType).concat(details), + stackStartFn + }); + } + if (error2 && !expectedException(actual, error2, message, stackStartFn)) { + throw actual; + } + } + function expectsNoError(stackStartFn, actual, error2, message) { + if (actual === NO_EXCEPTION_SENTINEL) return; + if (typeof error2 === "string") { + message = error2; + error2 = void 0; + } + if (!error2 || expectedException(actual, error2)) { + var details = message ? ": ".concat(message) : "."; + var fnType = stackStartFn.name === "doesNotReject" ? "rejection" : "exception"; + innerFail({ + actual, + expected: error2, + operator: stackStartFn.name, + message: "Got unwanted ".concat(fnType).concat(details, "\n") + 'Actual message: "'.concat(actual && actual.message, '"'), + stackStartFn + }); + } + throw actual; + } + assert2.throws = function throws(promiseFn) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); + }; + assert2.rejects = function rejects(promiseFn) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return waitForActual(promiseFn).then(function(result) { + return expectsError.apply(void 0, [rejects, result].concat(args)); + }); + }; + assert2.doesNotThrow = function doesNotThrow(fn) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); + }; + assert2.doesNotReject = function doesNotReject(fn) { + for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + return waitForActual(fn).then(function(result) { + return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); + }); + }; + assert2.ifError = function ifError(err) { + if (err !== null && err !== void 0) { + var message = "ifError got unwanted exception: "; + if (_typeof2(err) === "object" && typeof err.message === "string") { + if (err.message.length === 0 && err.constructor) { + message += err.constructor.name; + } else { + message += err.message; + } + } else { + message += inspect(err); + } + var newErr = new AssertionError({ + actual: err, + expected: null, + operator: "ifError", + message, + stackStartFn: ifError + }); + var origStack = err.stack; + if (typeof origStack === "string") { + var tmp2 = origStack.split("\n"); + tmp2.shift(); + var tmp1 = newErr.stack.split("\n"); + for (var i = 0; i < tmp2.length; i++) { + var pos = tmp1.indexOf(tmp2[i]); + if (pos !== -1) { + tmp1 = tmp1.slice(0, pos); + break; + } + } + newErr.stack = "".concat(tmp1.join("\n"), "\n").concat(tmp2.join("\n")); + } + throw newErr; + } + }; + function internalMatch(string2, regexp, message, fn, fnName) { + if (!isRegExp2(regexp)) { + throw new ERR_INVALID_ARG_TYPE2("regexp", "RegExp", regexp); + } + var match = fnName === "match"; + if (typeof string2 !== "string" || RegExpPrototypeTest(regexp, string2) !== match) { + if (message instanceof Error) { + throw message; + } + var generatedMessage = !message; + message = message || (typeof string2 !== "string" ? 'The "string" argument must be of type string. Received type ' + "".concat(_typeof2(string2), " (").concat(inspect(string2), ")") : (match ? "The input did not match the regular expression " : "The input was expected to not match the regular expression ") + "".concat(inspect(regexp), ". Input:\n\n").concat(inspect(string2), "\n")); + var err = new AssertionError({ + actual: string2, + expected: regexp, + message, + operator: fnName, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } + } + assert2.match = function match(string2, regexp, message) { + internalMatch(string2, regexp, message, match, "match"); + }; + assert2.doesNotMatch = function doesNotMatch(string2, regexp, message) { + internalMatch(string2, regexp, message, doesNotMatch, "doesNotMatch"); + }; + function strict() { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + innerOk.apply(void 0, [strict, args.length].concat(args)); + } + assert2.strict = objectAssign(strict, assert2, { + equal: assert2.strictEqual, + deepEqual: assert2.deepStrictEqual, + notEqual: assert2.notStrictEqual, + notDeepEqual: assert2.notDeepStrictEqual + }); + assert2.strict.strict = assert2.strict; + return assert$1.exports; +} +var hasRequiredErrors$1; +function requireErrors$1() { + if (hasRequiredErrors$1) return errors$3; + hasRequiredErrors$1 = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.E = exports.AssertionError = exports.message = exports.RangeError = exports.TypeError = exports.Error = void 0; + const assert2 = requireAssert(); + const util2 = requireUtil$5(); + const kCode = typeof Symbol === "undefined" ? "_kCode" : Symbol("code"); + const messages2 = {}; + function makeNodeError(Base) { + return class NodeError extends Base { + constructor(key2, ...args) { + super(message(key2, args)); + this.code = key2; + this[kCode] = key2; + this.name = `${super.name} [${this[kCode]}]`; + } + }; + } + const g = typeof globalThis !== "undefined" ? globalThis : commonjsGlobal; + class AssertionError extends g.Error { + constructor(options2) { + if (typeof options2 !== "object" || options2 === null) { + throw new exports.TypeError("ERR_INVALID_ARG_TYPE", "options", "object"); + } + if (options2.message) { + super(options2.message); + } else { + super(`${util2.inspect(options2.actual).slice(0, 128)} ${options2.operator} ${util2.inspect(options2.expected).slice(0, 128)}`); + } + this.generatedMessage = !options2.message; + this.name = "AssertionError [ERR_ASSERTION]"; + this.code = "ERR_ASSERTION"; + this.actual = options2.actual; + this.expected = options2.expected; + this.operator = options2.operator; + exports.Error.captureStackTrace(this, options2.stackStartFunction); + } + } + exports.AssertionError = AssertionError; + function message(key2, args) { + assert2.strictEqual(typeof key2, "string"); + const msg = messages2[key2]; + assert2(msg, `An invalid error message key was used: ${key2}.`); + let fmt; + if (typeof msg === "function") { + fmt = msg; + } else { + fmt = util2.format; + if (args === void 0 || args.length === 0) + return msg; + args.unshift(msg); + } + return String(fmt.apply(null, args)); + } + exports.message = message; + function E(sym, val) { + messages2[sym] = typeof val === "function" ? val : String(val); + } + exports.E = E; + exports.Error = makeNodeError(g.Error); + exports.TypeError = makeNodeError(g.TypeError); + exports.RangeError = makeNodeError(g.RangeError); + E("ERR_ARG_NOT_ITERABLE", "%s must be iterable"); + E("ERR_ASSERTION", "%s"); + E("ERR_BUFFER_OUT_OF_BOUNDS", bufferOutOfBounds); + E("ERR_CHILD_CLOSED_BEFORE_REPLY", "Child closed before reply received"); + E("ERR_CONSOLE_WRITABLE_STREAM", "Console expects a writable stream instance for %s"); + E("ERR_CPU_USAGE", "Unable to obtain cpu usage %s"); + E("ERR_DNS_SET_SERVERS_FAILED", (err, servers) => `c-ares failed to set servers: "${err}" [${servers}]`); + E("ERR_FALSY_VALUE_REJECTION", "Promise was rejected with falsy value"); + E("ERR_ENCODING_NOT_SUPPORTED", (enc) => `The "${enc}" encoding is not supported`); + E("ERR_ENCODING_INVALID_ENCODED_DATA", (enc) => `The encoded data was not valid for encoding ${enc}`); + E("ERR_HTTP_HEADERS_SENT", "Cannot render headers after they are sent to the client"); + E("ERR_HTTP_INVALID_STATUS_CODE", "Invalid status code: %s"); + E("ERR_HTTP_TRAILER_INVALID", "Trailers are invalid with this transfer encoding"); + E("ERR_INDEX_OUT_OF_RANGE", "Index out of range"); + E("ERR_INVALID_ARG_TYPE", invalidArgType); + E("ERR_INVALID_ARRAY_LENGTH", (name, len, actual) => { + assert2.strictEqual(typeof actual, "number"); + return `The array "${name}" (length ${actual}) must be of length ${len}.`; + }); + E("ERR_INVALID_BUFFER_SIZE", "Buffer size must be a multiple of %s"); + E("ERR_INVALID_CALLBACK", "Callback must be a function"); + E("ERR_INVALID_CHAR", "Invalid character in %s"); + E("ERR_INVALID_CURSOR_POS", "Cannot set cursor row without setting its column"); + E("ERR_INVALID_FD", '"fd" must be a positive integer: %s'); + E("ERR_INVALID_FILE_URL_HOST", 'File URL host must be "localhost" or empty on %s'); + E("ERR_INVALID_FILE_URL_PATH", "File URL path %s"); + E("ERR_INVALID_HANDLE_TYPE", "This handle type cannot be sent"); + E("ERR_INVALID_IP_ADDRESS", "Invalid IP address: %s"); + E("ERR_INVALID_OPT_VALUE", (name, value) => { + return `The value "${String(value)}" is invalid for option "${name}"`; + }); + E("ERR_INVALID_OPT_VALUE_ENCODING", (value) => `The value "${String(value)}" is invalid for option "encoding"`); + E("ERR_INVALID_REPL_EVAL_CONFIG", 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL'); + E("ERR_INVALID_SYNC_FORK_INPUT", "Asynchronous forks do not support Buffer, Uint8Array or string input: %s"); + E("ERR_INVALID_THIS", 'Value of "this" must be of type %s'); + E("ERR_INVALID_TUPLE", "%s must be an iterable %s tuple"); + E("ERR_INVALID_URL", "Invalid URL: %s"); + E("ERR_INVALID_URL_SCHEME", (expected) => `The URL must be ${oneOf(expected, "scheme")}`); + E("ERR_IPC_CHANNEL_CLOSED", "Channel closed"); + E("ERR_IPC_DISCONNECTED", "IPC channel is already disconnected"); + E("ERR_IPC_ONE_PIPE", "Child process can have only one IPC pipe"); + E("ERR_IPC_SYNC_FORK", "IPC cannot be used with synchronous forks"); + E("ERR_MISSING_ARGS", missingArgs); + E("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + E("ERR_NAPI_CONS_FUNCTION", "Constructor must be a function"); + E("ERR_NAPI_CONS_PROTOTYPE_OBJECT", "Constructor.prototype must be an object"); + E("ERR_NO_CRYPTO", "Node.js is not compiled with OpenSSL crypto support"); + E("ERR_NO_LONGER_SUPPORTED", "%s is no longer supported"); + E("ERR_PARSE_HISTORY_DATA", "Could not parse history data in %s"); + E("ERR_SOCKET_ALREADY_BOUND", "Socket is already bound"); + E("ERR_SOCKET_BAD_PORT", "Port should be > 0 and < 65536"); + E("ERR_SOCKET_BAD_TYPE", "Bad socket type specified. Valid types are: udp4, udp6"); + E("ERR_SOCKET_CANNOT_SEND", "Unable to send data"); + E("ERR_SOCKET_CLOSED", "Socket is closed"); + E("ERR_SOCKET_DGRAM_NOT_RUNNING", "Not running"); + E("ERR_STDERR_CLOSE", "process.stderr cannot be closed"); + E("ERR_STDOUT_CLOSE", "process.stdout cannot be closed"); + E("ERR_STREAM_WRAP", "Stream has StringDecoder set or is in objectMode"); + E("ERR_TLS_CERT_ALTNAME_INVALID", "Hostname/IP does not match certificate's altnames: %s"); + E("ERR_TLS_DH_PARAM_SIZE", (size) => `DH parameter size ${size} is less than 2048`); + E("ERR_TLS_HANDSHAKE_TIMEOUT", "TLS handshake timeout"); + E("ERR_TLS_RENEGOTIATION_FAILED", "Failed to renegotiate"); + E("ERR_TLS_REQUIRED_SERVER_NAME", '"servername" is required parameter for Server.addContext'); + E("ERR_TLS_SESSION_ATTACK", "TSL session renegotiation attack detected"); + E("ERR_TRANSFORM_ALREADY_TRANSFORMING", "Calling transform done when still transforming"); + E("ERR_TRANSFORM_WITH_LENGTH_0", "Calling transform done when writableState.length != 0"); + E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s"); + E("ERR_UNKNOWN_SIGNAL", "Unknown signal: %s"); + E("ERR_UNKNOWN_STDIN_TYPE", "Unknown stdin file type"); + E("ERR_UNKNOWN_STREAM_TYPE", "Unknown stream file type"); + E("ERR_V8BREAKITERATOR", "Full ICU data not installed. See https://github.com/nodejs/node/wiki/Intl"); + function invalidArgType(name, expected, actual) { + assert2(name, "name is required"); + let determiner; + if (expected.includes("not ")) { + determiner = "must not be"; + expected = expected.split("not ")[1]; + } else { + determiner = "must be"; + } + let msg; + if (Array.isArray(name)) { + const names = name.map((val) => `"${val}"`).join(", "); + msg = `The ${names} arguments ${determiner} ${oneOf(expected, "type")}`; + } else if (name.includes(" argument")) { + msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; + } else { + const type2 = name.includes(".") ? "property" : "argument"; + msg = `The "${name}" ${type2} ${determiner} ${oneOf(expected, "type")}`; + } + if (arguments.length >= 3) { + msg += `. Received type ${actual !== null ? typeof actual : "null"}`; + } + return msg; + } + function missingArgs(...args) { + assert2(args.length > 0, "At least one arg needs to be specified"); + let msg = "The "; + const len = args.length; + args = args.map((a) => `"${a}"`); + switch (len) { + case 1: + msg += `${args[0]} argument`; + break; + case 2: + msg += `${args[0]} and ${args[1]} arguments`; + break; + default: + msg += args.slice(0, len - 1).join(", "); + msg += `, and ${args[len - 1]} arguments`; + break; + } + return `${msg} must be specified`; + } + function oneOf(expected, thing) { + assert2(expected, "expected is required"); + assert2(typeof thing === "string", "thing is required"); + if (Array.isArray(expected)) { + const len = expected.length; + assert2(len > 0, "At least one expected value needs to be specified"); + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + function bufferOutOfBounds(name, isWriting) { + if (isWriting) { + return "Attempt to write outside buffer bounds"; + } else { + return `"${name}" is outside of buffer bounds`; + } + } + })(errors$3); + return errors$3; +} +var hasRequiredEncoding; +function requireEncoding() { + if (hasRequiredEncoding) return encoding; + hasRequiredEncoding = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.strToEncoding = exports.assertEncoding = exports.ENCODING_UTF8 = void 0; + const buffer_1 = requireBuffer$1(); + const errors2 = requireErrors$1(); + exports.ENCODING_UTF8 = "utf8"; + function assertEncoding(encoding2) { + if (encoding2 && !buffer_1.Buffer.isEncoding(encoding2)) + throw new errors2.TypeError("ERR_INVALID_OPT_VALUE_ENCODING", encoding2); + } + exports.assertEncoding = assertEncoding; + function strToEncoding(str, encoding2) { + if (!encoding2 || encoding2 === exports.ENCODING_UTF8) + return str; + if (encoding2 === "buffer") + return new buffer_1.Buffer(str); + return new buffer_1.Buffer(str).toString(encoding2); + } + exports.strToEncoding = strToEncoding; + })(encoding); + return encoding; +} +var hasRequiredDirent; +function requireDirent() { + if (hasRequiredDirent) return Dirent$1; + hasRequiredDirent = 1; + Object.defineProperty(Dirent$1, "__esModule", { value: true }); + Dirent$1.Dirent = void 0; + const constants_1 = requireConstants$7(); + const encoding_1 = requireEncoding(); + const { S_IFMT, S_IFDIR, S_IFREG, S_IFBLK, S_IFCHR, S_IFLNK, S_IFIFO, S_IFSOCK } = constants_1.constants; + class Dirent2 { + constructor() { + this.name = ""; + this.path = ""; + this.mode = 0; + } + static build(link2, encoding2) { + const dirent = new Dirent2(); + const { mode } = link2.getNode(); + dirent.name = (0, encoding_1.strToEncoding)(link2.getName(), encoding2); + dirent.mode = mode; + dirent.path = link2.getPath(); + return dirent; + } + _checkModeProperty(property) { + return (this.mode & S_IFMT) === property; + } + isDirectory() { + return this._checkModeProperty(S_IFDIR); + } + isFile() { + return this._checkModeProperty(S_IFREG); + } + isBlockDevice() { + return this._checkModeProperty(S_IFBLK); + } + isCharacterDevice() { + return this._checkModeProperty(S_IFCHR); + } + isSymbolicLink() { + return this._checkModeProperty(S_IFLNK); + } + isFIFO() { + return this._checkModeProperty(S_IFIFO); + } + isSocket() { + return this._checkModeProperty(S_IFSOCK); + } + } + Dirent$1.Dirent = Dirent2; + Dirent$1.default = Dirent2; + return Dirent$1; +} +var volume = {}; +var path$1 = { exports: {} }; +var util$5 = {}; +var isBufferBrowser; +var hasRequiredIsBufferBrowser; +function requireIsBufferBrowser() { + if (hasRequiredIsBufferBrowser) return isBufferBrowser; + hasRequiredIsBufferBrowser = 1; + isBufferBrowser = function isBuffer(arg) { + return arg && typeof arg === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function"; + }; + return isBufferBrowser; +} +var inherits_browser = { exports: {} }; +var hasRequiredInherits_browser; +function requireInherits_browser() { + if (hasRequiredInherits_browser) return inherits_browser.exports; + hasRequiredInherits_browser = 1; + if (typeof Object.create === "function") { + inherits_browser.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits_browser.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + return inherits_browser.exports; +} +var hasRequiredUtil$4; +function requireUtil$4() { + if (hasRequiredUtil$4) return util$5; + hasRequiredUtil$4 = 1; + (function(exports) { + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString2(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(" "); + } + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x2) { + if (x2 === "%%") return "%"; + if (i >= len) return x2; + switch (x2) { + case "%s": + return String(args[i++]); + case "%d": + return Number(args[i++]); + case "%j": + try { + return JSON.stringify(args[i++]); + } catch (_) { + return "[Circular]"; + } + default: + return x2; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject2(x)) { + str += " " + x; + } else { + str += " " + inspect(x); + } + } + return str; + }; + exports.deprecate = function(fn, msg) { + if (isUndefined(commonjsGlobal.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + if (process.noDeprecation === true) { + return fn; + } + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + return deprecated; + }; + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set2) { + if (isUndefined(debugEnviron)) + debugEnviron = define_process_env_default.NODE_DEBUG || ""; + set2 = set2.toUpperCase(); + if (!debugs[set2]) { + if (new RegExp("\\b" + set2 + "\\b", "i").test(debugEnviron)) { + var pid = process.pid; + debugs[set2] = function() { + var msg = exports.format.apply(exports, arguments); + console.error("%s %d: %s", set2, pid, msg); + }; + } else { + debugs[set2] = function() { + }; + } + } + return debugs[set2]; + }; + function inspect(obj, opts) { + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + ctx.showHidden = opts; + } else if (opts) { + exports._extend(ctx, opts); + } + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue2(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + inspect.colors = { + "bold": [1, 22], + "italic": [3, 23], + "underline": [4, 24], + "inverse": [7, 27], + "white": [37, 39], + "grey": [90, 39], + "black": [30, 39], + "blue": [34, 39], + "cyan": [36, 39], + "green": [32, 39], + "magenta": [35, 39], + "red": [31, 39], + "yellow": [33, 39] + }; + inspect.styles = { + "special": "cyan", + "number": "yellow", + "boolean": "yellow", + "undefined": "grey", + "null": "bold", + "string": "green", + "date": "magenta", + // "name": intentionally not styling + "regexp": "red" + }; + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + if (style) { + return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m"; + } else { + return str; + } + } + function stylizeNoColor(str, styleType) { + return str; + } + function arrayToHash(array) { + var hash2 = {}; + array.forEach(function(val, idx) { + hash2[val] = true; + }); + return hash2; + } + function formatValue2(ctx, value, recurseTimes) { + if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString2(ret)) { + ret = formatValue2(ctx, ret, recurseTimes); + } + return ret; + } + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + if (isError2(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { + return formatError(value); + } + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ": " + value.name : ""; + return ctx.stylize("[Function" + name + "]", "special"); + } + if (isRegExp2(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } + if (isDate2(value)) { + return ctx.stylize(Date.prototype.toString.call(value), "date"); + } + if (isError2(value)) { + return formatError(value); + } + } + var base2 = "", array = false, braces = ["{", "}"]; + if (isArray2(value)) { + array = true; + braces = ["[", "]"]; + } + if (isFunction(value)) { + var n = value.name ? ": " + value.name : ""; + base2 = " [Function" + n + "]"; + } + if (isRegExp2(value)) { + base2 = " " + RegExp.prototype.toString.call(value); + } + if (isDate2(value)) { + base2 = " " + Date.prototype.toUTCString.call(value); + } + if (isError2(value)) { + base2 = " " + formatError(value); + } + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base2 + braces[1]; + } + if (recurseTimes < 0) { + if (isRegExp2(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } else { + return ctx.stylize("[Object]", "special"); + } + } + ctx.seen.push(value); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key2) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key2, array); + }); + } + ctx.seen.pop(); + return reduceToSingleString(output, base2, braces); + } + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize("undefined", "undefined"); + if (isString2(value)) { + var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; + return ctx.stylize(simple, "string"); + } + if (isNumber(value)) + return ctx.stylize("" + value, "number"); + if (isBoolean(value)) + return ctx.stylize("" + value, "boolean"); + if (isNull(value)) + return ctx.stylize("null", "null"); + } + function formatError(value) { + return "[" + Error.prototype.toString.call(value) + "]"; + } + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty2(value, String(i))) { + output.push(formatProperty( + ctx, + value, + recurseTimes, + visibleKeys, + String(i), + true + )); + } else { + output.push(""); + } + } + keys.forEach(function(key2) { + if (!key2.match(/^\d+$/)) { + output.push(formatProperty( + ctx, + value, + recurseTimes, + visibleKeys, + key2, + true + )); + } + }); + return output; + } + function formatProperty(ctx, value, recurseTimes, visibleKeys, key2, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key2) || { value: value[key2] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize("[Getter/Setter]", "special"); + } else { + str = ctx.stylize("[Getter]", "special"); + } + } else { + if (desc.set) { + str = ctx.stylize("[Setter]", "special"); + } + } + if (!hasOwnProperty2(visibleKeys, key2)) { + name = "[" + key2 + "]"; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue2(ctx, desc.value, null); + } else { + str = formatValue2(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf("\n") > -1) { + if (array) { + str = str.split("\n").map(function(line) { + return " " + line; + }).join("\n").substr(2); + } else { + str = "\n" + str.split("\n").map(function(line) { + return " " + line; + }).join("\n"); + } + } + } else { + str = ctx.stylize("[Circular]", "special"); + } + } + if (isUndefined(name)) { + if (array && key2.match(/^\d+$/)) { + return str; + } + name = JSON.stringify("" + key2); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, "name"); + } else { + name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, "string"); + } + } + return name + ": " + str; + } + function reduceToSingleString(output, base2, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf("\n") >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; + }, 0); + if (length > 60) { + return braces[0] + (base2 === "" ? "" : base2 + "\n ") + " " + output.join(",\n ") + " " + braces[1]; + } + return braces[0] + base2 + " " + output.join(", ") + " " + braces[1]; + } + function isArray2(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray2; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === "number"; + } + exports.isNumber = isNumber; + function isString2(arg) { + return typeof arg === "string"; + } + exports.isString = isString2; + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports.isSymbol = isSymbol; + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + function isRegExp2(re2) { + return isObject2(re2) && objectToString(re2) === "[object RegExp]"; + } + exports.isRegExp = isRegExp2; + function isObject2(arg) { + return typeof arg === "object" && arg !== null; + } + exports.isObject = isObject2; + function isDate2(d) { + return isObject2(d) && objectToString(d) === "[object Date]"; + } + exports.isDate = isDate2; + function isError2(e) { + return isObject2(e) && (objectToString(e) === "[object Error]" || e instanceof Error); + } + exports.isError = isError2; + function isFunction(arg) { + return typeof arg === "function"; + } + exports.isFunction = isFunction; + function isPrimitive(arg) { + return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol + typeof arg === "undefined"; + } + exports.isPrimitive = isPrimitive; + exports.isBuffer = requireIsBufferBrowser(); + function objectToString(o) { + return Object.prototype.toString.call(o); + } + function pad(n) { + return n < 10 ? "0" + n.toString(10) : n.toString(10); + } + var months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ]; + function timestamp2() { + var d = /* @__PURE__ */ new Date(); + var time = [ + pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds()) + ].join(":"); + return [d.getDate(), months[d.getMonth()], time].join(" "); + } + exports.log = function() { + console.log("%s - %s", timestamp2(), exports.format.apply(exports, arguments)); + }; + exports.inherits = requireInherits_browser(); + exports._extend = function(origin, add) { + if (!add || !isObject2(add)) return origin; + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + function hasOwnProperty2(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + })(util$5); + return util$5; +} +var hasRequiredPath; +function requirePath() { + if (hasRequiredPath) return path$1.exports; + hasRequiredPath = 1; + var isWindows = process.platform === "win32"; + var util2 = requireUtil$4(); + function normalizeArray(parts, allowAboveRoot) { + var res = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + if (!p || p === ".") + continue; + if (p === "..") { + if (res.length && res[res.length - 1] !== "..") { + res.pop(); + } else if (allowAboveRoot) { + res.push(".."); + } + } else { + res.push(p); + } + } + return res; + } + function trimArray(arr) { + var lastIndex = arr.length - 1; + var start = 0; + for (; start <= lastIndex; start++) { + if (arr[start]) + break; + } + var end = lastIndex; + for (; end >= 0; end--) { + if (arr[end]) + break; + } + if (start === 0 && end === lastIndex) + return arr; + if (start > end) + return []; + return arr.slice(start, end + 1); + } + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; + var win32 = {}; + function win32SplitPath(filename) { + var result = splitDeviceRe.exec(filename), device = (result[1] || "") + (result[2] || ""), tail = result[3] || ""; + var result2 = splitTailRe.exec(tail), dir = result2[1], basename = result2[2], ext = result2[3]; + return [device, dir, basename, ext]; + } + function win32StatPath(path2) { + var result = splitDeviceRe.exec(path2), device = result[1] || "", isUnc = !!device && device[1] !== ":"; + return { + device, + isUnc, + isAbsolute: isUnc || !!result[2], + // UNC paths are always absolute + tail: result[3] + }; + } + function normalizeUNCRoot(device) { + return "\\\\" + device.replace(/^[\\\/]+/, "").replace(/[\\\/]+/g, "\\"); + } + win32.resolve = function() { + var resolvedDevice = "", resolvedTail = "", resolvedAbsolute = false; + for (var i = arguments.length - 1; i >= -1; i--) { + var path2; + if (i >= 0) { + path2 = arguments[i]; + } else if (!resolvedDevice) { + path2 = process.cwd(); + } else { + path2 = define_process_env_default["=" + resolvedDevice]; + if (!path2 || path2.substr(0, 3).toLowerCase() !== resolvedDevice.toLowerCase() + "\\") { + path2 = resolvedDevice + "\\"; + } + } + if (!util2.isString(path2)) { + throw new TypeError("Arguments to path.resolve must be strings"); + } else if (!path2) { + continue; + } + var result = win32StatPath(path2), device = result.device, isUnc = result.isUnc, isAbsolute = result.isAbsolute, tail = result.tail; + if (device && resolvedDevice && device.toLowerCase() !== resolvedDevice.toLowerCase()) { + continue; + } + if (!resolvedDevice) { + resolvedDevice = device; + } + if (!resolvedAbsolute) { + resolvedTail = tail + "\\" + resolvedTail; + resolvedAbsolute = isAbsolute; + } + if (resolvedDevice && resolvedAbsolute) { + break; + } + } + if (isUnc) { + resolvedDevice = normalizeUNCRoot(resolvedDevice); + } + resolvedTail = normalizeArray( + resolvedTail.split(/[\\\/]+/), + !resolvedAbsolute + ).join("\\"); + return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "."; + }; + win32.normalize = function(path2) { + var result = win32StatPath(path2), device = result.device, isUnc = result.isUnc, isAbsolute = result.isAbsolute, tail = result.tail, trailingSlash = /[\\\/]$/.test(tail); + tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join("\\"); + if (!tail && !isAbsolute) { + tail = "."; + } + if (tail && trailingSlash) { + tail += "\\"; + } + if (isUnc) { + device = normalizeUNCRoot(device); + } + return device + (isAbsolute ? "\\" : "") + tail; + }; + win32.isAbsolute = function(path2) { + return win32StatPath(path2).isAbsolute; + }; + win32.join = function() { + var paths = []; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (!util2.isString(arg)) { + throw new TypeError("Arguments to path.join must be strings"); + } + if (arg) { + paths.push(arg); + } + } + var joined = paths.join("\\"); + if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) { + joined = joined.replace(/^[\\\/]{2,}/, "\\"); + } + return win32.normalize(joined); + }; + win32.relative = function(from2, to) { + from2 = win32.resolve(from2); + to = win32.resolve(to); + var lowerFrom = from2.toLowerCase(); + var lowerTo = to.toLowerCase(); + var toParts = trimArray(to.split("\\")); + var lowerFromParts = trimArray(lowerFrom.split("\\")); + var lowerToParts = trimArray(lowerTo.split("\\")); + var length = Math.min(lowerFromParts.length, lowerToParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (lowerFromParts[i] !== lowerToParts[i]) { + samePartsLength = i; + break; + } + } + if (samePartsLength == 0) { + return to; + } + var outputParts = []; + for (var i = samePartsLength; i < lowerFromParts.length; i++) { + outputParts.push(".."); + } + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join("\\"); + }; + win32._makeLong = function(path2) { + if (!util2.isString(path2)) + return path2; + if (!path2) { + return ""; + } + var resolvedPath = win32.resolve(path2); + if (/^[a-zA-Z]\:\\/.test(resolvedPath)) { + return "\\\\?\\" + resolvedPath; + } else if (/^\\\\[^?.]/.test(resolvedPath)) { + return "\\\\?\\UNC\\" + resolvedPath.substring(2); + } + return path2; + }; + win32.dirname = function(path2) { + var result = win32SplitPath(path2), root = result[0], dir = result[1]; + if (!root && !dir) { + return "."; + } + if (dir) { + dir = dir.substr(0, dir.length - 1); + } + return root + dir; + }; + win32.basename = function(path2, ext) { + var f = win32SplitPath(path2)[2]; + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; + }; + win32.extname = function(path2) { + return win32SplitPath(path2)[3]; + }; + win32.format = function(pathObject) { + if (!util2.isObject(pathObject)) { + throw new TypeError( + "Parameter 'pathObject' must be an object, not " + typeof pathObject + ); + } + var root = pathObject.root || ""; + if (!util2.isString(root)) { + throw new TypeError( + "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root + ); + } + var dir = pathObject.dir; + var base2 = pathObject.base || ""; + if (!dir) { + return base2; + } + if (dir[dir.length - 1] === win32.sep) { + return dir + base2; + } + return dir + win32.sep + base2; + }; + win32.parse = function(pathString) { + if (!util2.isString(pathString)) { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; + }; + win32.sep = "\\"; + win32.delimiter = ";"; + var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; + var posix = {}; + function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); + } + posix.resolve = function() { + var resolvedPath = "", resolvedAbsolute = false; + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path2 = i >= 0 ? arguments[i] : process.cwd(); + if (!util2.isString(path2)) { + throw new TypeError("Arguments to path.resolve must be strings"); + } else if (!path2) { + continue; + } + resolvedPath = path2 + "/" + resolvedPath; + resolvedAbsolute = path2[0] === "/"; + } + resolvedPath = normalizeArray( + resolvedPath.split("/"), + !resolvedAbsolute + ).join("/"); + return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; + }; + posix.normalize = function(path2) { + var isAbsolute = posix.isAbsolute(path2), trailingSlash = path2 && path2[path2.length - 1] === "/"; + path2 = normalizeArray(path2.split("/"), !isAbsolute).join("/"); + if (!path2 && !isAbsolute) { + path2 = "."; + } + if (path2 && trailingSlash) { + path2 += "/"; + } + return (isAbsolute ? "/" : "") + path2; + }; + posix.isAbsolute = function(path2) { + return path2.charAt(0) === "/"; + }; + posix.join = function() { + var path2 = ""; + for (var i = 0; i < arguments.length; i++) { + var segment = arguments[i]; + if (!util2.isString(segment)) { + throw new TypeError("Arguments to path.join must be strings"); + } + if (segment) { + if (!path2) { + path2 += segment; + } else { + path2 += "/" + segment; + } + } + } + return posix.normalize(path2); + }; + posix.relative = function(from2, to) { + from2 = posix.resolve(from2).substr(1); + to = posix.resolve(to).substr(1); + var fromParts = trimArray(from2.split("/")); + var toParts = trimArray(to.split("/")); + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push(".."); + } + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join("/"); + }; + posix._makeLong = function(path2) { + return path2; + }; + posix.dirname = function(path2) { + var result = posixSplitPath(path2), root = result[0], dir = result[1]; + if (!root && !dir) { + return "."; + } + if (dir) { + dir = dir.substr(0, dir.length - 1); + } + return root + dir; + }; + posix.basename = function(path2, ext) { + var f = posixSplitPath(path2)[2]; + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; + }; + posix.extname = function(path2) { + return posixSplitPath(path2)[3]; + }; + posix.format = function(pathObject) { + if (!util2.isObject(pathObject)) { + throw new TypeError( + "Parameter 'pathObject' must be an object, not " + typeof pathObject + ); + } + var root = pathObject.root || ""; + if (!util2.isString(root)) { + throw new TypeError( + "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root + ); + } + var dir = pathObject.dir ? pathObject.dir + posix.sep : ""; + var base2 = pathObject.base || ""; + return dir + base2; + }; + posix.parse = function(pathString) { + if (!util2.isString(pathString)) { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + allParts[1] = allParts[1] || ""; + allParts[2] = allParts[2] || ""; + allParts[3] = allParts[3] || ""; + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; + }; + posix.sep = "/"; + posix.delimiter = ":"; + if (isWindows) + path$1.exports = win32; + else + path$1.exports = posix; + path$1.exports.posix = posix; + path$1.exports.win32 = win32; + return path$1.exports; +} +var node$1 = {}; +var process$1 = {}; +var hasRequiredProcess; +function requireProcess() { + if (hasRequiredProcess) return process$1; + hasRequiredProcess = 1; + Object.defineProperty(process$1, "__esModule", { value: true }); + process$1.createProcess = void 0; + const maybeReturnProcess = () => { + if (typeof process !== "undefined") { + return process; + } + try { + return requireBrowser$j(); + } catch (_a2) { + return void 0; + } + }; + function createProcess() { + const p = maybeReturnProcess() || {}; + if (!p.cwd) + p.cwd = () => "/"; + if (!p.emitWarning) + p.emitWarning = (message, type2) => { + console.warn(`${type2}${type2 ? ": " : ""}${message}`); + }; + if (!p.env) + p.env = {}; + return p; + } + process$1.createProcess = createProcess; + process$1.default = createProcess(); + return process$1; +} +var events = { exports: {} }; +var hasRequiredEvents; +function requireEvents() { + if (hasRequiredEvents) return events.exports; + hasRequiredEvents = 1; + var R = typeof Reflect === "object" ? Reflect : null; + var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }; + var ReflectOwnKeys; + if (R && typeof R.ownKeys === "function") { + ReflectOwnKeys = R.ownKeys; + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target); + }; + } + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); + } + var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { + return value !== value; + }; + function EventEmitter2() { + EventEmitter2.init.call(this); + } + events.exports = EventEmitter2; + events.exports.once = once2; + EventEmitter2.EventEmitter = EventEmitter2; + EventEmitter2.prototype._events = void 0; + EventEmitter2.prototype._eventsCount = 0; + EventEmitter2.prototype._maxListeners = void 0; + var defaultMaxListeners = 10; + function checkListener2(listener) { + if (typeof listener !== "function") { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + } + Object.defineProperty(EventEmitter2, "defaultMaxListeners", { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); + } + defaultMaxListeners = arg; + } + }); + EventEmitter2.init = function() { + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + }; + EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); + } + this._maxListeners = n; + return this; + }; + function _getMaxListeners(that) { + if (that._maxListeners === void 0) + return EventEmitter2.defaultMaxListeners; + return that._maxListeners; + } + EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; + EventEmitter2.prototype.emit = function emit(type2) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = type2 === "error"; + var events2 = this._events; + if (events2 !== void 0) + doError = doError && events2.error === void 0; + else if (!doError) + return false; + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + throw er; + } + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); + err.context = er; + throw err; + } + var handler = events2[type2]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + return true; + }; + function _addListener(target, type2, listener, prepend) { + var m; + var events2; + var existing; + checkListener2(listener); + events2 = target._events; + if (events2 === void 0) { + events2 = target._events = /* @__PURE__ */ Object.create(null); + target._eventsCount = 0; + } else { + if (events2.newListener !== void 0) { + target.emit( + "newListener", + type2, + listener.listener ? listener.listener : listener + ); + events2 = target._events; + } + existing = events2[type2]; + } + if (existing === void 0) { + existing = events2[type2] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events2[type2] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type2) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = target; + w.type = type2; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + return target; + } + EventEmitter2.prototype.addListener = function addListener(type2, listener) { + return _addListener(this, type2, listener, false); + }; + EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; + EventEmitter2.prototype.prependListener = function prependListener(type2, listener) { + return _addListener(this, type2, listener, true); + }; + function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } + } + function _onceWrap(target, type2, listener) { + var state2 = { fired: false, wrapFn: void 0, target, type: type2, listener }; + var wrapped = onceWrapper.bind(state2); + wrapped.listener = listener; + state2.wrapFn = wrapped; + return wrapped; + } + EventEmitter2.prototype.once = function once3(type2, listener) { + checkListener2(listener); + this.on(type2, _onceWrap(this, type2, listener)); + return this; + }; + EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type2, listener) { + checkListener2(listener); + this.prependListener(type2, _onceWrap(this, type2, listener)); + return this; + }; + EventEmitter2.prototype.removeListener = function removeListener(type2, listener) { + var list, events2, position, i, originalListener; + checkListener2(listener); + events2 = this._events; + if (events2 === void 0) + return this; + list = events2[type2]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else { + delete events2[type2]; + if (events2.removeListener) + this.emit("removeListener", type2, list.listener || listener); + } + } else if (typeof list !== "function") { + position = -1; + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events2[type2] = list[0]; + if (events2.removeListener !== void 0) + this.emit("removeListener", type2, originalListener || listener); + } + return this; + }; + EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; + EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type2) { + var listeners, events2, i; + events2 = this._events; + if (events2 === void 0) + return this; + if (events2.removeListener === void 0) { + if (arguments.length === 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events2[type2] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events2[type2]; + } + return this; + } + if (arguments.length === 0) { + var keys = Object.keys(events2); + var key2; + for (i = 0; i < keys.length; ++i) { + key2 = keys[i]; + if (key2 === "removeListener") continue; + this.removeAllListeners(key2); + } + this.removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return this; + } + listeners = events2[type2]; + if (typeof listeners === "function") { + this.removeListener(type2, listeners); + } else if (listeners !== void 0) { + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type2, listeners[i]); + } + } + return this; + }; + function _listeners(target, type2, unwrap) { + var events2 = target._events; + if (events2 === void 0) + return []; + var evlistener = events2[type2]; + if (evlistener === void 0) + return []; + if (typeof evlistener === "function") + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap ? unwrapListeners2(evlistener) : arrayClone(evlistener, evlistener.length); + } + EventEmitter2.prototype.listeners = function listeners(type2) { + return _listeners(this, type2, true); + }; + EventEmitter2.prototype.rawListeners = function rawListeners(type2) { + return _listeners(this, type2, false); + }; + EventEmitter2.listenerCount = function(emitter, type2) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type2); + } else { + return listenerCount.call(emitter, type2); + } + }; + EventEmitter2.prototype.listenerCount = listenerCount; + function listenerCount(type2) { + var events2 = this._events; + if (events2 !== void 0) { + var evlistener = events2[type2]; + if (typeof evlistener === "function") { + return 1; + } else if (evlistener !== void 0) { + return evlistener.length; + } + } + return 0; + } + EventEmitter2.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; + } + function spliceOne(list, index2) { + for (; index2 + 1 < list.length; index2++) + list[index2] = list[index2 + 1]; + list.pop(); + } + function unwrapListeners2(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + function once2(emitter, name) { + return new Promise(function(resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + function resolver() { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + resolve([].slice.call(arguments)); + } + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== "error") { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); + } + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === "function") { + eventTargetAgnosticAddListener(emitter, "error", handler, flags); + } + } + function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, function wrapListener(arg) { + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } + return events.exports; +} +var hasRequiredNode$1; +function requireNode$1() { + if (hasRequiredNode$1) return node$1; + hasRequiredNode$1 = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.File = exports.Link = exports.Node = exports.SEP = void 0; + const process_1 = requireProcess(); + const buffer_1 = requireBuffer$1(); + const constants_1 = requireConstants$7(); + const events_1 = requireEvents(); + const Stats_1 = requireStats(); + const { S_IFMT, S_IFDIR, S_IFREG, S_IFLNK, O_APPEND } = constants_1.constants; + const getuid = () => { + var _a2, _b2; + return (_b2 = (_a2 = process_1.default.getuid) === null || _a2 === void 0 ? void 0 : _a2.call(process_1.default)) !== null && _b2 !== void 0 ? _b2 : 0; + }; + const getgid = () => { + var _a2, _b2; + return (_b2 = (_a2 = process_1.default.getgid) === null || _a2 === void 0 ? void 0 : _a2.call(process_1.default)) !== null && _b2 !== void 0 ? _b2 : 0; + }; + exports.SEP = "/"; + class Node3 extends events_1.EventEmitter { + constructor(ino, perm = 438) { + super(); + this._uid = getuid(); + this._gid = getgid(); + this._atime = /* @__PURE__ */ new Date(); + this._mtime = /* @__PURE__ */ new Date(); + this._ctime = /* @__PURE__ */ new Date(); + this._perm = 438; + this.mode = S_IFREG; + this._nlink = 1; + this._perm = perm; + this.mode |= perm; + this.ino = ino; + } + set ctime(ctime) { + this._ctime = ctime; + } + get ctime() { + return this._ctime; + } + set uid(uid) { + this._uid = uid; + this.ctime = /* @__PURE__ */ new Date(); + } + get uid() { + return this._uid; + } + set gid(gid) { + this._gid = gid; + this.ctime = /* @__PURE__ */ new Date(); + } + get gid() { + return this._gid; + } + set atime(atime) { + this._atime = atime; + this.ctime = /* @__PURE__ */ new Date(); + } + get atime() { + return this._atime; + } + set mtime(mtime) { + this._mtime = mtime; + this.ctime = /* @__PURE__ */ new Date(); + } + get mtime() { + return this._mtime; + } + set perm(perm) { + this._perm = perm; + this.ctime = /* @__PURE__ */ new Date(); + } + get perm() { + return this._perm; + } + set nlink(nlink) { + this._nlink = nlink; + this.ctime = /* @__PURE__ */ new Date(); + } + get nlink() { + return this._nlink; + } + getString(encoding2 = "utf8") { + this.atime = /* @__PURE__ */ new Date(); + return this.getBuffer().toString(encoding2); + } + setString(str) { + this.buf = (0, buffer_1.bufferFrom)(str, "utf8"); + this.touch(); + } + getBuffer() { + this.atime = /* @__PURE__ */ new Date(); + if (!this.buf) + this.setBuffer((0, buffer_1.bufferAllocUnsafe)(0)); + return (0, buffer_1.bufferFrom)(this.buf); + } + setBuffer(buf) { + this.buf = (0, buffer_1.bufferFrom)(buf); + this.touch(); + } + getSize() { + return this.buf ? this.buf.length : 0; + } + setModeProperty(property) { + this.mode = this.mode & ~S_IFMT | property; + } + setIsFile() { + this.setModeProperty(S_IFREG); + } + setIsDirectory() { + this.setModeProperty(S_IFDIR); + } + setIsSymlink() { + this.setModeProperty(S_IFLNK); + } + isFile() { + return (this.mode & S_IFMT) === S_IFREG; + } + isDirectory() { + return (this.mode & S_IFMT) === S_IFDIR; + } + isSymlink() { + return (this.mode & S_IFMT) === S_IFLNK; + } + makeSymlink(steps) { + this.symlink = steps; + this.setIsSymlink(); + } + write(buf, off = 0, len = buf.length, pos = 0) { + if (!this.buf) + this.buf = (0, buffer_1.bufferAllocUnsafe)(0); + if (pos + len > this.buf.length) { + const newBuf = (0, buffer_1.bufferAllocUnsafe)(pos + len); + this.buf.copy(newBuf, 0, 0, this.buf.length); + this.buf = newBuf; + } + buf.copy(this.buf, pos, off, off + len); + this.touch(); + return len; + } + // Returns the number of bytes read. + read(buf, off = 0, len = buf.byteLength, pos = 0) { + this.atime = /* @__PURE__ */ new Date(); + if (!this.buf) + this.buf = (0, buffer_1.bufferAllocUnsafe)(0); + let actualLen = len; + if (actualLen > buf.byteLength) { + actualLen = buf.byteLength; + } + if (actualLen + pos > this.buf.length) { + actualLen = this.buf.length - pos; + } + const buf2 = buf instanceof buffer_1.Buffer ? buf : buffer_1.Buffer.from(buf.buffer); + this.buf.copy(buf2, off, pos, pos + actualLen); + return actualLen; + } + truncate(len = 0) { + if (!len) + this.buf = (0, buffer_1.bufferAllocUnsafe)(0); + else { + if (!this.buf) + this.buf = (0, buffer_1.bufferAllocUnsafe)(0); + if (len <= this.buf.length) { + this.buf = this.buf.slice(0, len); + } else { + const buf = (0, buffer_1.bufferAllocUnsafe)(len); + this.buf.copy(buf); + buf.fill(0, this.buf.length); + this.buf = buf; + } + } + this.touch(); + } + chmod(perm) { + this.perm = perm; + this.mode = this.mode & -512 | perm; + this.touch(); + } + chown(uid, gid) { + this.uid = uid; + this.gid = gid; + this.touch(); + } + touch() { + this.mtime = /* @__PURE__ */ new Date(); + this.emit("change", this); + } + canRead(uid = getuid(), gid = getgid()) { + if (this.perm & 4) { + return true; + } + if (gid === this.gid) { + if (this.perm & 32) { + return true; + } + } + if (uid === this.uid) { + if (this.perm & 256) { + return true; + } + } + return false; + } + canWrite(uid = getuid(), gid = getgid()) { + if (this.perm & 2) { + return true; + } + if (gid === this.gid) { + if (this.perm & 16) { + return true; + } + } + if (uid === this.uid) { + if (this.perm & 128) { + return true; + } + } + return false; + } + del() { + this.emit("delete", this); + } + toJSON() { + return { + ino: this.ino, + uid: this.uid, + gid: this.gid, + atime: this.atime.getTime(), + mtime: this.mtime.getTime(), + ctime: this.ctime.getTime(), + perm: this.perm, + mode: this.mode, + nlink: this.nlink, + symlink: this.symlink, + data: this.getString() + }; + } + } + exports.Node = Node3; + class Link extends events_1.EventEmitter { + get steps() { + return this._steps; + } + // Recursively sync children steps, e.g. in case of dir rename + set steps(val) { + this._steps = val; + for (const [child, link2] of this.children.entries()) { + if (child === "." || child === "..") { + continue; + } + link2 === null || link2 === void 0 ? void 0 : link2.syncSteps(); + } + } + constructor(vol, parent, name) { + super(); + this.children = /* @__PURE__ */ new Map(); + this._steps = []; + this.ino = 0; + this.length = 0; + this.vol = vol; + this.parent = parent; + this.name = name; + this.syncSteps(); + } + setNode(node2) { + this.node = node2; + this.ino = node2.ino; + } + getNode() { + return this.node; + } + createChild(name, node2 = this.vol.createNode()) { + const link2 = new Link(this.vol, this, name); + link2.setNode(node2); + if (node2.isDirectory()) { + link2.children.set(".", link2); + link2.getNode().nlink++; + } + this.setChild(name, link2); + return link2; + } + setChild(name, link2 = new Link(this.vol, this, name)) { + this.children.set(name, link2); + link2.parent = this; + this.length++; + const node2 = link2.getNode(); + if (node2.isDirectory()) { + link2.children.set("..", this); + this.getNode().nlink++; + } + this.getNode().mtime = /* @__PURE__ */ new Date(); + this.emit("child:add", link2, this); + return link2; + } + deleteChild(link2) { + const node2 = link2.getNode(); + if (node2.isDirectory()) { + link2.children.delete(".."); + this.getNode().nlink--; + } + this.children.delete(link2.getName()); + this.length--; + this.getNode().mtime = /* @__PURE__ */ new Date(); + this.emit("child:delete", link2, this); + } + getChild(name) { + this.getNode().mtime = /* @__PURE__ */ new Date(); + return this.children.get(name); + } + getPath() { + return this.steps.join(exports.SEP); + } + getName() { + return this.steps[this.steps.length - 1]; + } + // del() { + // const parent = this.parent; + // if(parent) { + // parent.deleteChild(link); + // } + // this.parent = null; + // this.vol = null; + // } + /** + * Walk the tree path and return the `Link` at that location, if any. + * @param steps {string[]} Desired location. + * @param stop {number} Max steps to go into. + * @param i {number} Current step in the `steps` array. + * + * @return {Link|null} + */ + walk(steps, stop = steps.length, i = 0) { + if (i >= steps.length) + return this; + if (i >= stop) + return this; + const step = steps[i]; + const link2 = this.getChild(step); + if (!link2) + return null; + return link2.walk(steps, stop, i + 1); + } + toJSON() { + return { + steps: this.steps, + ino: this.ino, + children: Array.from(this.children.keys()) + }; + } + syncSteps() { + this.steps = this.parent ? this.parent.steps.concat([this.name]) : [this.name]; + } + } + exports.Link = Link; + class File { + /** + * Open a Link-Node pair. `node` is provided separately as that might be a different node + * rather the one `link` points to, because it might be a symlink. + * @param link + * @param node + * @param flags + * @param fd + */ + constructor(link2, node2, flags, fd) { + this.link = link2; + this.node = node2; + this.flags = flags; + this.fd = fd; + this.position = 0; + if (this.flags & O_APPEND) + this.position = this.getSize(); + } + getString(encoding2 = "utf8") { + return this.node.getString(); + } + setString(str) { + this.node.setString(str); + } + getBuffer() { + return this.node.getBuffer(); + } + setBuffer(buf) { + this.node.setBuffer(buf); + } + getSize() { + return this.node.getSize(); + } + truncate(len) { + this.node.truncate(len); + } + seekTo(position) { + this.position = position; + } + stats() { + return Stats_1.default.build(this.node); + } + write(buf, offset2 = 0, length = buf.length, position) { + if (typeof position !== "number") + position = this.position; + const bytes = this.node.write(buf, offset2, length, position); + this.position = position + bytes; + return bytes; + } + read(buf, offset2 = 0, length = buf.byteLength, position) { + if (typeof position !== "number") + position = this.position; + const bytes = this.node.read(buf, offset2, length, position); + this.position = position + bytes; + return bytes; + } + chmod(perm) { + this.node.chmod(perm); + } + chown(uid, gid) { + this.node.chown(uid, gid); + } + } + exports.File = File; + })(node$1); + return node$1; +} +var setImmediate$1 = {}; +var hasRequiredSetImmediate; +function requireSetImmediate() { + if (hasRequiredSetImmediate) return setImmediate$1; + hasRequiredSetImmediate = 1; + Object.defineProperty(setImmediate$1, "__esModule", { value: true }); + let _setImmediate; + if (typeof setImmediate === "function") + _setImmediate = setImmediate.bind(typeof globalThis !== "undefined" ? globalThis : commonjsGlobal); + else + _setImmediate = setTimeout.bind(typeof globalThis !== "undefined" ? globalThis : commonjsGlobal); + setImmediate$1.default = _setImmediate; + return setImmediate$1; +} +var queueMicrotask$1 = {}; +var hasRequiredQueueMicrotask; +function requireQueueMicrotask() { + if (hasRequiredQueueMicrotask) return queueMicrotask$1; + hasRequiredQueueMicrotask = 1; + Object.defineProperty(queueMicrotask$1, "__esModule", { value: true }); + queueMicrotask$1.default = typeof queueMicrotask === "function" ? queueMicrotask : (cb) => Promise.resolve().then(() => cb()).catch(() => { + }); + return queueMicrotask$1; +} +var setTimeoutUnref = {}; +var hasRequiredSetTimeoutUnref; +function requireSetTimeoutUnref() { + if (hasRequiredSetTimeoutUnref) return setTimeoutUnref; + hasRequiredSetTimeoutUnref = 1; + Object.defineProperty(setTimeoutUnref, "__esModule", { value: true }); + function setTimeoutUnref$1(callback, time, args) { + const ref2 = setTimeout.apply(typeof globalThis !== "undefined" ? globalThis : commonjsGlobal, arguments); + if (ref2 && typeof ref2 === "object" && typeof ref2.unref === "function") + ref2.unref(); + return ref2; + } + setTimeoutUnref.default = setTimeoutUnref$1; + return setTimeoutUnref; +} +var browser$i = { exports: {} }; +var stream$1 = { exports: {} }; +var primordials; +var hasRequiredPrimordials; +function requirePrimordials() { + if (hasRequiredPrimordials) return primordials; + hasRequiredPrimordials = 1; + primordials = { + ArrayIsArray(self2) { + return Array.isArray(self2); + }, + ArrayPrototypeIncludes(self2, el) { + return self2.includes(el); + }, + ArrayPrototypeIndexOf(self2, el) { + return self2.indexOf(el); + }, + ArrayPrototypeJoin(self2, sep) { + return self2.join(sep); + }, + ArrayPrototypeMap(self2, fn) { + return self2.map(fn); + }, + ArrayPrototypePop(self2, el) { + return self2.pop(el); + }, + ArrayPrototypePush(self2, el) { + return self2.push(el); + }, + ArrayPrototypeSlice(self2, start, end) { + return self2.slice(start, end); + }, + Error, + FunctionPrototypeCall(fn, thisArgs, ...args) { + return fn.call(thisArgs, ...args); + }, + FunctionPrototypeSymbolHasInstance(self2, instance) { + return Function.prototype[Symbol.hasInstance].call(self2, instance); + }, + MathFloor: Math.floor, + Number, + NumberIsInteger: Number.isInteger, + NumberIsNaN: Number.isNaN, + NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, + NumberParseInt: Number.parseInt, + ObjectDefineProperties(self2, props) { + return Object.defineProperties(self2, props); + }, + ObjectDefineProperty(self2, name, prop) { + return Object.defineProperty(self2, name, prop); + }, + ObjectGetOwnPropertyDescriptor(self2, name) { + return Object.getOwnPropertyDescriptor(self2, name); + }, + ObjectKeys(obj) { + return Object.keys(obj); + }, + ObjectSetPrototypeOf(target, proto) { + return Object.setPrototypeOf(target, proto); + }, + Promise, + PromisePrototypeCatch(self2, fn) { + return self2.catch(fn); + }, + PromisePrototypeThen(self2, thenFn, catchFn) { + return self2.then(thenFn, catchFn); + }, + PromiseReject(err) { + return Promise.reject(err); + }, + PromiseResolve(val) { + return Promise.resolve(val); + }, + ReflectApply: Reflect.apply, + RegExpPrototypeTest(self2, value) { + return self2.test(value); + }, + SafeSet: Set, + String, + StringPrototypeSlice(self2, start, end) { + return self2.slice(start, end); + }, + StringPrototypeToLowerCase(self2) { + return self2.toLowerCase(); + }, + StringPrototypeToUpperCase(self2) { + return self2.toUpperCase(); + }, + StringPrototypeTrim(self2) { + return self2.trim(); + }, + Symbol, + SymbolFor: Symbol.for, + SymbolAsyncIterator: Symbol.asyncIterator, + SymbolHasInstance: Symbol.hasInstance, + SymbolIterator: Symbol.iterator, + SymbolDispose: Symbol.dispose || Symbol("Symbol.dispose"), + SymbolAsyncDispose: Symbol.asyncDispose || Symbol("Symbol.asyncDispose"), + TypedArrayPrototypeSet(self2, buf, len) { + return self2.set(buf, len); + }, + Boolean, + Uint8Array + }; + return primordials; +} +var util$4 = { exports: {} }; +var browser$h = { exports: {} }; +var hasRequiredBrowser$i; +function requireBrowser$i() { + if (hasRequiredBrowser$i) return browser$h.exports; + hasRequiredBrowser$i = 1; + const { AbortController: AbortController2, AbortSignal } = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : ( + /* otherwise */ + void 0 + ); + browser$h.exports = AbortController2; + browser$h.exports.AbortSignal = AbortSignal; + browser$h.exports.default = AbortController2; + return browser$h.exports; +} +var hasRequiredUtil$3; +function requireUtil$3() { + if (hasRequiredUtil$3) return util$4.exports; + hasRequiredUtil$3 = 1; + (function(module) { + const bufferModule = requireBuffer$2(); + const { kResistStopPropagation, SymbolDispose } = requirePrimordials(); + const AbortSignal = globalThis.AbortSignal || requireBrowser$i().AbortSignal; + const AbortController2 = globalThis.AbortController || requireBrowser$i().AbortController; + const AsyncFunction = Object.getPrototypeOf(async function() { + }).constructor; + const Blob2 = globalThis.Blob || bufferModule.Blob; + const isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { + return b instanceof Blob2; + } : function isBlob2(b) { + return false; + }; + const validateAbortSignal = (signal, name) => { + if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); + } + }; + const validateFunction = (value, name) => { + if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE(name, "Function", value); + }; + class AggregateError2 extends Error { + constructor(errors2) { + if (!Array.isArray(errors2)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors2}`); + } + let message = ""; + for (let i = 0; i < errors2.length; i++) { + message += ` ${errors2[i].stack} +`; + } + super(message); + this.name = "AggregateError"; + this.errors = errors2; + } + } + module.exports = { + AggregateError: AggregateError2, + kEmptyObject: Object.freeze({}), + once(callback) { + let called = false; + return function(...args) { + if (called) { + return; + } + called = true; + callback.apply(this, args); + }; + }, + createDeferredPromise: function() { + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { + promise, + resolve, + reject + }; + }, + promisify(fn) { + return new Promise((resolve, reject) => { + fn((err, ...args) => { + if (err) { + return reject(err); + } + return resolve(...args); + }); + }); + }, + debuglog() { + return function() { + }; + }, + format(format, ...args) { + return format.replace(/%([sdifj])/g, function(...[_unused, type2]) { + const replacement = args.shift(); + if (type2 === "f") { + return replacement.toFixed(6); + } else if (type2 === "j") { + return JSON.stringify(replacement); + } else if (type2 === "s" && typeof replacement === "object") { + const ctor = replacement.constructor !== Object ? replacement.constructor.name : ""; + return `${ctor} {}`.trim(); + } else { + return replacement.toString(); + } + }); + }, + inspect(value) { + switch (typeof value) { + case "string": + if (value.includes("'")) { + if (!value.includes('"')) { + return `"${value}"`; + } else if (!value.includes("`") && !value.includes("${")) { + return `\`${value}\``; + } + } + return `'${value}'`; + case "number": + if (isNaN(value)) { + return "NaN"; + } else if (Object.is(value, -0)) { + return String(value); + } + return value; + case "bigint": + return `${String(value)}n`; + case "boolean": + case "undefined": + return String(value); + case "object": + return "{}"; + } + }, + types: { + isAsyncFunction(fn) { + return fn instanceof AsyncFunction; + }, + isArrayBufferView(arr) { + return ArrayBuffer.isView(arr); + } + }, + isBlob, + deprecate(fn, message) { + return fn; + }, + addAbortListener: requireEvents().addAbortListener || function addAbortListener(signal, listener) { + if (signal === void 0) { + throw new ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal); + } + validateAbortSignal(signal, "signal"); + validateFunction(listener, "listener"); + let removeEventListener; + if (signal.aborted) { + queueMicrotask(() => listener()); + } else { + signal.addEventListener("abort", listener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }); + removeEventListener = () => { + signal.removeEventListener("abort", listener); + }; + } + return { + __proto__: null, + [SymbolDispose]() { + var _removeEventListener; + (_removeEventListener = removeEventListener) === null || _removeEventListener === void 0 ? void 0 : _removeEventListener(); + } + }; + }, + AbortSignalAny: AbortSignal.any || function AbortSignalAny(signals2) { + if (signals2.length === 1) { + return signals2[0]; + } + const ac = new AbortController2(); + const abort = () => ac.abort(); + signals2.forEach((signal) => { + validateAbortSignal(signal, "signals"); + signal.addEventListener("abort", abort, { + once: true + }); + }); + ac.signal.addEventListener( + "abort", + () => { + signals2.forEach((signal) => signal.removeEventListener("abort", abort)); + }, + { + once: true + } + ); + return ac.signal; + } + }; + module.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); + })(util$4); + return util$4.exports; +} +var operators = {}; +var errors$1; +var hasRequiredErrors; +function requireErrors() { + if (hasRequiredErrors) return errors$1; + hasRequiredErrors = 1; + const { format, inspect, AggregateError: CustomAggregateError } = requireUtil$3(); + const AggregateError2 = globalThis.AggregateError || CustomAggregateError; + const kIsNodeError = Symbol("kIsNodeError"); + const kTypes = [ + "string", + "function", + "number", + "object", + // Accept 'Function' and 'Object' as alternative to the lower cased version. + "Function", + "Object", + "boolean", + "bigint", + "symbol" + ]; + const classRegExp = /^([A-Z][a-z0-9]*)+$/; + const nodeInternalPrefix = "__node_internal_"; + const codes = {}; + function assert2(value, message) { + if (!value) { + throw new codes.ERR_INTERNAL_ASSERTION(message); + } + } + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}`; + } + function getMessage(key2, msg, args) { + if (typeof msg === "function") { + assert2( + msg.length <= args.length, + // Default options do not count. + `Code: ${key2}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` + ); + return msg(...args); + } + const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length; + assert2( + expectedLength === args.length, + `Code: ${key2}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` + ); + if (args.length === 0) { + return msg; + } + return format(msg, ...args); + } + function E(code, message, Base) { + if (!Base) { + Base = Error; + } + class NodeError extends Base { + constructor(...args) { + super(getMessage(code, message, args)); + } + toString() { + return `${this.name} [${code}]: ${this.message}`; + } + } + Object.defineProperties(NodeError.prototype, { + name: { + value: Base.name, + writable: true, + enumerable: false, + configurable: true + }, + toString: { + value() { + return `${this.name} [${code}]: ${this.message}`; + }, + writable: true, + enumerable: false, + configurable: true + } + }); + NodeError.prototype.code = code; + NodeError.prototype[kIsNodeError] = true; + codes[code] = NodeError; + } + function hideStackFrames(fn) { + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, "name", { + value: hidden + }); + return fn; + } + function aggregateTwoErrors(innerError, outerError) { + if (innerError && outerError && innerError !== outerError) { + if (Array.isArray(outerError.errors)) { + outerError.errors.push(innerError); + return outerError; + } + const err = new AggregateError2([outerError, innerError], outerError.message); + err.code = outerError.code; + return err; + } + return innerError || outerError; + } + class AbortError extends Error { + constructor(message = "The operation was aborted", options2 = void 0) { + if (options2 !== void 0 && typeof options2 !== "object") { + throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options2); + } + super(message, options2); + this.code = "ABORT_ERR"; + this.name = "AbortError"; + } + } + E("ERR_ASSERTION", "%s", Error); + E( + "ERR_INVALID_ARG_TYPE", + (name, expected, actual) => { + assert2(typeof name === "string", "'name' must be a string"); + if (!Array.isArray(expected)) { + expected = [expected]; + } + let msg = "The "; + if (name.endsWith(" argument")) { + msg += `${name} `; + } else { + msg += `"${name}" ${name.includes(".") ? "property" : "argument"} `; + } + msg += "must be "; + const types2 = []; + const instances = []; + const other2 = []; + for (const value of expected) { + assert2(typeof value === "string", "All expected entries have to be of type string"); + if (kTypes.includes(value)) { + types2.push(value.toLowerCase()); + } else if (classRegExp.test(value)) { + instances.push(value); + } else { + assert2(value !== "object", 'The value "object" should be written as "Object"'); + other2.push(value); + } + } + if (instances.length > 0) { + const pos = types2.indexOf("object"); + if (pos !== -1) { + types2.splice(types2, pos, 1); + instances.push("Object"); + } + } + if (types2.length > 0) { + switch (types2.length) { + case 1: + msg += `of type ${types2[0]}`; + break; + case 2: + msg += `one of type ${types2[0]} or ${types2[1]}`; + break; + default: { + const last = types2.pop(); + msg += `one of type ${types2.join(", ")}, or ${last}`; + } + } + if (instances.length > 0 || other2.length > 0) { + msg += " or "; + } + } + if (instances.length > 0) { + switch (instances.length) { + case 1: + msg += `an instance of ${instances[0]}`; + break; + case 2: + msg += `an instance of ${instances[0]} or ${instances[1]}`; + break; + default: { + const last = instances.pop(); + msg += `an instance of ${instances.join(", ")}, or ${last}`; + } + } + if (other2.length > 0) { + msg += " or "; + } + } + switch (other2.length) { + case 0: + break; + case 1: + if (other2[0].toLowerCase() !== other2[0]) { + msg += "an "; + } + msg += `${other2[0]}`; + break; + case 2: + msg += `one of ${other2[0]} or ${other2[1]}`; + break; + default: { + const last = other2.pop(); + msg += `one of ${other2.join(", ")}, or ${last}`; + } + } + if (actual == null) { + msg += `. Received ${actual}`; + } else if (typeof actual === "function" && actual.name) { + msg += `. Received function ${actual.name}`; + } else if (typeof actual === "object") { + var _actual$constructor; + if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) { + msg += `. Received an instance of ${actual.constructor.name}`; + } else { + const inspected = inspect(actual, { + depth: -1 + }); + msg += `. Received ${inspected}`; + } + } else { + let inspected = inspect(actual, { + colors: false + }); + if (inspected.length > 25) { + inspected = `${inspected.slice(0, 25)}...`; + } + msg += `. Received type ${typeof actual} (${inspected})`; + } + return msg; + }, + TypeError + ); + E( + "ERR_INVALID_ARG_VALUE", + (name, value, reason = "is invalid") => { + let inspected = inspect(value); + if (inspected.length > 128) { + inspected = inspected.slice(0, 128) + "..."; + } + const type2 = name.includes(".") ? "property" : "argument"; + return `The ${type2} '${name}' ${reason}. Received ${inspected}`; + }, + TypeError + ); + E( + "ERR_INVALID_RETURN_VALUE", + (input, name, value) => { + var _value$constructor; + const type2 = value !== null && value !== void 0 && (_value$constructor = value.constructor) !== null && _value$constructor !== void 0 && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}`; + return `Expected ${input} to be returned from the "${name}" function but got ${type2}.`; + }, + TypeError + ); + E( + "ERR_MISSING_ARGS", + (...args) => { + assert2(args.length > 0, "At least one arg needs to be specified"); + let msg; + const len = args.length; + args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(" or "); + switch (len) { + case 1: + msg += `The ${args[0]} argument`; + break; + case 2: + msg += `The ${args[0]} and ${args[1]} arguments`; + break; + default: + { + const last = args.pop(); + msg += `The ${args.join(", ")}, and ${last} arguments`; + } + break; + } + return `${msg} must be specified`; + }, + TypeError + ); + E( + "ERR_OUT_OF_RANGE", + (str, range2, input) => { + assert2(range2, 'Missing "range" argument'); + let received; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > 2n ** 32n || input < -(2n ** 32n)) { + received = addNumericalSeparator(received); + } + received += "n"; + } else { + received = inspect(input); + } + return `The value of "${str}" is out of range. It must be ${range2}. Received ${received}`; + }, + RangeError + ); + E("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); + E("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); + E("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); + E("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); + E("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); + E("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + E("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); + E("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); + E("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); + E("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); + E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); + errors$1 = { + AbortError, + aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), + hideStackFrames, + codes + }; + return errors$1; +} +var validators; +var hasRequiredValidators; +function requireValidators() { + if (hasRequiredValidators) return validators; + hasRequiredValidators = 1; + const { + ArrayIsArray, + ArrayPrototypeIncludes, + ArrayPrototypeJoin, + ArrayPrototypeMap, + NumberIsInteger, + NumberIsNaN, + NumberMAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER, + NumberParseInt, + ObjectPrototypeHasOwnProperty, + RegExpPrototypeExec, + String: String2, + StringPrototypeToUpperCase, + StringPrototypeTrim + } = requirePrimordials(); + const { + hideStackFrames, + codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } + } = requireErrors(); + const { normalizeEncoding } = requireUtil$3(); + const { isAsyncFunction, isArrayBufferView } = requireUtil$3().types; + const signals2 = {}; + function isInt32(value) { + return value === (value | 0); + } + function isUint32(value) { + return value === value >>> 0; + } + const octalReg = /^[0-7]+$/; + const modeDesc = "must be a 32-bit unsigned integer or an octal string"; + function parseFileMode(value, name, def) { + if (typeof value === "undefined") { + value = def; + } + if (typeof value === "string") { + if (RegExpPrototypeExec(octalReg, value) === null) { + throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc); + } + value = NumberParseInt(value, 8); + } + validateUint32(value, name); + return value; + } + const validateInteger = hideStackFrames((value, name, min2 = NumberMIN_SAFE_INTEGER, max2 = NumberMAX_SAFE_INTEGER) => { + if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, "an integer", value); + if (value < min2 || value > max2) throw new ERR_OUT_OF_RANGE(name, `>= ${min2} && <= ${max2}`, value); + }); + const validateInt32 = hideStackFrames((value, name, min2 = -2147483648, max2 = 2147483647) => { + if (typeof value !== "number") { + throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, "an integer", value); + } + if (value < min2 || value > max2) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min2} && <= ${max2}`, value); + } + }); + const validateUint32 = hideStackFrames((value, name, positive = false) => { + if (typeof value !== "number") { + throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, "an integer", value); + } + const min2 = positive ? 1 : 0; + const max2 = 4294967295; + if (value < min2 || value > max2) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min2} && <= ${max2}`, value); + } + }); + function validateString(value, name) { + if (typeof value !== "string") throw new ERR_INVALID_ARG_TYPE2(name, "string", value); + } + function validateNumber(value, name, min2 = void 0, max2) { + if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value); + if (min2 != null && value < min2 || max2 != null && value > max2 || (min2 != null || max2 != null) && NumberIsNaN(value)) { + throw new ERR_OUT_OF_RANGE( + name, + `${min2 != null ? `>= ${min2}` : ""}${min2 != null && max2 != null ? " && " : ""}${max2 != null ? `<= ${max2}` : ""}`, + value + ); + } + } + const validateOneOf = hideStackFrames((value, name, oneOf) => { + if (!ArrayPrototypeIncludes(oneOf, value)) { + const allowed = ArrayPrototypeJoin( + ArrayPrototypeMap(oneOf, (v) => typeof v === "string" ? `'${v}'` : String2(v)), + ", " + ); + const reason = "must be one of: " + allowed; + throw new ERR_INVALID_ARG_VALUE(name, value, reason); + } + }); + function validateBoolean(value, name) { + if (typeof value !== "boolean") throw new ERR_INVALID_ARG_TYPE2(name, "boolean", value); + } + function getOwnPropertyValueOrDefault(options2, key2, defaultValue) { + return options2 == null || !ObjectPrototypeHasOwnProperty(options2, key2) ? defaultValue : options2[key2]; + } + const validateObject = hideStackFrames((value, name, options2 = null) => { + const allowArray = getOwnPropertyValueOrDefault(options2, "allowArray", false); + const allowFunction = getOwnPropertyValueOrDefault(options2, "allowFunction", false); + const nullable = getOwnPropertyValueOrDefault(options2, "nullable", false); + if (!nullable && value === null || !allowArray && ArrayIsArray(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function")) { + throw new ERR_INVALID_ARG_TYPE2(name, "Object", value); + } + }); + const validateDictionary = hideStackFrames((value, name) => { + if (value != null && typeof value !== "object" && typeof value !== "function") { + throw new ERR_INVALID_ARG_TYPE2(name, "a dictionary", value); + } + }); + const validateArray = hideStackFrames((value, name, minLength = 0) => { + if (!ArrayIsArray(value)) { + throw new ERR_INVALID_ARG_TYPE2(name, "Array", value); + } + if (value.length < minLength) { + const reason = `must be longer than ${minLength}`; + throw new ERR_INVALID_ARG_VALUE(name, value, reason); + } + }); + function validateStringArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateString(value[i], `${name}[${i}]`); + } + } + function validateBooleanArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateBoolean(value[i], `${name}[${i}]`); + } + } + function validateAbortSignalArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + const signal = value[i]; + const indexedName = `${name}[${i}]`; + if (signal == null) { + throw new ERR_INVALID_ARG_TYPE2(indexedName, "AbortSignal", signal); + } + validateAbortSignal(signal, indexedName); + } + } + function validateSignalName(signal, name = "signal") { + validateString(signal, name); + if (signals2[signal] === void 0) { + if (signals2[StringPrototypeToUpperCase(signal)] !== void 0) { + throw new ERR_UNKNOWN_SIGNAL(signal + " (signals must use all capital letters)"); + } + throw new ERR_UNKNOWN_SIGNAL(signal); + } + } + const validateBuffer2 = hideStackFrames((buffer2, name = "buffer") => { + if (!isArrayBufferView(buffer2)) { + throw new ERR_INVALID_ARG_TYPE2(name, ["Buffer", "TypedArray", "DataView"], buffer2); + } + }); + function validateEncoding(data2, encoding2) { + const normalizedEncoding = normalizeEncoding(encoding2); + const length = data2.length; + if (normalizedEncoding === "hex" && length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE("encoding", encoding2, `is invalid for data of length ${length}`); + } + } + function validatePort(port, name = "Port", allowZero = true) { + if (typeof port !== "number" && typeof port !== "string" || typeof port === "string" && StringPrototypeTrim(port).length === 0 || +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero) { + throw new ERR_SOCKET_BAD_PORT(name, port, allowZero); + } + return port | 0; + } + const validateAbortSignal = hideStackFrames((signal, name) => { + if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) { + throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal); + } + }); + const validateFunction = hideStackFrames((value, name) => { + if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE2(name, "Function", value); + }); + const validatePlainFunction = hideStackFrames((value, name) => { + if (typeof value !== "function" || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE2(name, "Function", value); + }); + const validateUndefined = hideStackFrames((value, name) => { + if (value !== void 0) throw new ERR_INVALID_ARG_TYPE2(name, "undefined", value); + }); + function validateUnion(value, name, union) { + if (!ArrayPrototypeIncludes(union, value)) { + throw new ERR_INVALID_ARG_TYPE2(name, `('${ArrayPrototypeJoin(union, "|")}')`, value); + } + } + const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/; + function validateLinkHeaderFormat(value, name) { + if (typeof value === "undefined" || !RegExpPrototypeExec(linkValueRegExp, value)) { + throw new ERR_INVALID_ARG_VALUE( + name, + value, + 'must be an array or string of format "; rel=preload; as=style"' + ); + } + } + function validateLinkHeaderValue(hints) { + if (typeof hints === "string") { + validateLinkHeaderFormat(hints, "hints"); + return hints; + } else if (ArrayIsArray(hints)) { + const hintsLength = hints.length; + let result = ""; + if (hintsLength === 0) { + return result; + } + for (let i = 0; i < hintsLength; i++) { + const link2 = hints[i]; + validateLinkHeaderFormat(link2, "hints"); + result += link2; + if (i !== hintsLength - 1) { + result += ", "; + } + } + return result; + } + throw new ERR_INVALID_ARG_VALUE( + "hints", + hints, + 'must be an array or string of format "; rel=preload; as=style"' + ); + } + validators = { + isInt32, + isUint32, + parseFileMode, + validateArray, + validateStringArray, + validateBooleanArray, + validateAbortSignalArray, + validateBoolean, + validateBuffer: validateBuffer2, + validateDictionary, + validateEncoding, + validateFunction, + validateInt32, + validateInteger, + validateNumber, + validateObject, + validateOneOf, + validatePlainFunction, + validatePort, + validateSignalName, + validateString, + validateUint32, + validateUndefined, + validateUnion, + validateAbortSignal, + validateLinkHeaderValue + }; + return validators; +} +var endOfStream$4 = { exports: {} }; +var utils$6; +var hasRequiredUtils$6; +function requireUtils$6() { + if (hasRequiredUtils$6) return utils$6; + hasRequiredUtils$6 = 1; + const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = requirePrimordials(); + const kIsDestroyed = SymbolFor("nodejs.stream.destroyed"); + const kIsErrored = SymbolFor("nodejs.stream.errored"); + const kIsReadable = SymbolFor("nodejs.stream.readable"); + const kIsWritable = SymbolFor("nodejs.stream.writable"); + const kIsDisturbed = SymbolFor("nodejs.stream.disturbed"); + const kIsClosedPromise = SymbolFor("nodejs.webstream.isClosedPromise"); + const kControllerErrorFunction = SymbolFor("nodejs.webstream.controllerErrorFunction"); + function isReadableNodeStream(obj, strict = false) { + var _obj$_readableState; + return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === void 0 ? void 0 : _obj$_readableState.readable) !== false) && // Duplex + (!obj._writableState || obj._readableState)); + } + function isWritableNodeStream(obj) { + var _obj$_writableState; + return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === void 0 ? void 0 : _obj$_writableState.writable) !== false)); + } + function isDuplexNodeStream(obj) { + return !!(obj && typeof obj.pipe === "function" && obj._readableState && typeof obj.on === "function" && typeof obj.write === "function"); + } + function isNodeStream(obj) { + return obj && (obj._readableState || obj._writableState || typeof obj.write === "function" && typeof obj.on === "function" || typeof obj.pipe === "function" && typeof obj.on === "function"); + } + function isReadableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.pipeThrough === "function" && typeof obj.getReader === "function" && typeof obj.cancel === "function"); + } + function isWritableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === "function" && typeof obj.abort === "function"); + } + function isTransformStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.readable === "object" && typeof obj.writable === "object"); + } + function isWebStream(obj) { + return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj); + } + function isIterable(obj, isAsync) { + if (obj == null) return false; + if (isAsync === true) return typeof obj[SymbolAsyncIterator] === "function"; + if (isAsync === false) return typeof obj[SymbolIterator] === "function"; + return typeof obj[SymbolAsyncIterator] === "function" || typeof obj[SymbolIterator] === "function"; + } + function isDestroyed(stream2) { + if (!isNodeStream(stream2)) return null; + const wState = stream2._writableState; + const rState = stream2._readableState; + const state2 = wState || rState; + return !!(stream2.destroyed || stream2[kIsDestroyed] || state2 !== null && state2 !== void 0 && state2.destroyed); + } + function isWritableEnded(stream2) { + if (!isWritableNodeStream(stream2)) return null; + if (stream2.writableEnded === true) return true; + const wState = stream2._writableState; + if (wState !== null && wState !== void 0 && wState.errored) return false; + if (typeof (wState === null || wState === void 0 ? void 0 : wState.ended) !== "boolean") return null; + return wState.ended; + } + function isWritableFinished(stream2, strict) { + if (!isWritableNodeStream(stream2)) return null; + if (stream2.writableFinished === true) return true; + const wState = stream2._writableState; + if (wState !== null && wState !== void 0 && wState.errored) return false; + if (typeof (wState === null || wState === void 0 ? void 0 : wState.finished) !== "boolean") return null; + return !!(wState.finished || strict === false && wState.ended === true && wState.length === 0); + } + function isReadableEnded(stream2) { + if (!isReadableNodeStream(stream2)) return null; + if (stream2.readableEnded === true) return true; + const rState = stream2._readableState; + if (!rState || rState.errored) return false; + if (typeof (rState === null || rState === void 0 ? void 0 : rState.ended) !== "boolean") return null; + return rState.ended; + } + function isReadableFinished(stream2, strict) { + if (!isReadableNodeStream(stream2)) return null; + const rState = stream2._readableState; + if (rState !== null && rState !== void 0 && rState.errored) return false; + if (typeof (rState === null || rState === void 0 ? void 0 : rState.endEmitted) !== "boolean") return null; + return !!(rState.endEmitted || strict === false && rState.ended === true && rState.length === 0); + } + function isReadable(stream2) { + if (stream2 && stream2[kIsReadable] != null) return stream2[kIsReadable]; + if (typeof (stream2 === null || stream2 === void 0 ? void 0 : stream2.readable) !== "boolean") return null; + if (isDestroyed(stream2)) return false; + return isReadableNodeStream(stream2) && stream2.readable && !isReadableFinished(stream2); + } + function isWritable(stream2) { + if (stream2 && stream2[kIsWritable] != null) return stream2[kIsWritable]; + if (typeof (stream2 === null || stream2 === void 0 ? void 0 : stream2.writable) !== "boolean") return null; + if (isDestroyed(stream2)) return false; + return isWritableNodeStream(stream2) && stream2.writable && !isWritableEnded(stream2); + } + function isFinished(stream2, opts) { + if (!isNodeStream(stream2)) { + return null; + } + if (isDestroyed(stream2)) { + return true; + } + if ((opts === null || opts === void 0 ? void 0 : opts.readable) !== false && isReadable(stream2)) { + return false; + } + if ((opts === null || opts === void 0 ? void 0 : opts.writable) !== false && isWritable(stream2)) { + return false; + } + return true; + } + function isWritableErrored(stream2) { + var _stream$_writableStat, _stream$_writableStat2; + if (!isNodeStream(stream2)) { + return null; + } + if (stream2.writableErrored) { + return stream2.writableErrored; + } + return (_stream$_writableStat = (_stream$_writableStat2 = stream2._writableState) === null || _stream$_writableStat2 === void 0 ? void 0 : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== void 0 ? _stream$_writableStat : null; + } + function isReadableErrored(stream2) { + var _stream$_readableStat, _stream$_readableStat2; + if (!isNodeStream(stream2)) { + return null; + } + if (stream2.readableErrored) { + return stream2.readableErrored; + } + return (_stream$_readableStat = (_stream$_readableStat2 = stream2._readableState) === null || _stream$_readableStat2 === void 0 ? void 0 : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== void 0 ? _stream$_readableStat : null; + } + function isClosed(stream2) { + if (!isNodeStream(stream2)) { + return null; + } + if (typeof stream2.closed === "boolean") { + return stream2.closed; + } + const wState = stream2._writableState; + const rState = stream2._readableState; + if (typeof (wState === null || wState === void 0 ? void 0 : wState.closed) === "boolean" || typeof (rState === null || rState === void 0 ? void 0 : rState.closed) === "boolean") { + return (wState === null || wState === void 0 ? void 0 : wState.closed) || (rState === null || rState === void 0 ? void 0 : rState.closed); + } + if (typeof stream2._closed === "boolean" && isOutgoingMessage(stream2)) { + return stream2._closed; + } + return null; + } + function isOutgoingMessage(stream2) { + return typeof stream2._closed === "boolean" && typeof stream2._defaultKeepAlive === "boolean" && typeof stream2._removedConnection === "boolean" && typeof stream2._removedContLen === "boolean"; + } + function isServerResponse(stream2) { + return typeof stream2._sent100 === "boolean" && isOutgoingMessage(stream2); + } + function isServerRequest(stream2) { + var _stream$req; + return typeof stream2._consuming === "boolean" && typeof stream2._dumped === "boolean" && ((_stream$req = stream2.req) === null || _stream$req === void 0 ? void 0 : _stream$req.upgradeOrConnect) === void 0; + } + function willEmitClose(stream2) { + if (!isNodeStream(stream2)) return null; + const wState = stream2._writableState; + const rState = stream2._readableState; + const state2 = wState || rState; + return !state2 && isServerResponse(stream2) || !!(state2 && state2.autoDestroy && state2.emitClose && state2.closed === false); + } + function isDisturbed(stream2) { + var _stream$kIsDisturbed; + return !!(stream2 && ((_stream$kIsDisturbed = stream2[kIsDisturbed]) !== null && _stream$kIsDisturbed !== void 0 ? _stream$kIsDisturbed : stream2.readableDidRead || stream2.readableAborted)); + } + function isErrored(stream2) { + var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4; + return !!(stream2 && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream2[kIsErrored]) !== null && _stream$kIsErrored !== void 0 ? _stream$kIsErrored : stream2.readableErrored) !== null && _ref5 !== void 0 ? _ref5 : stream2.writableErrored) !== null && _ref4 !== void 0 ? _ref4 : (_stream$_readableStat3 = stream2._readableState) === null || _stream$_readableStat3 === void 0 ? void 0 : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== void 0 ? _ref3 : (_stream$_writableStat3 = stream2._writableState) === null || _stream$_writableStat3 === void 0 ? void 0 : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== void 0 ? _ref2 : (_stream$_readableStat4 = stream2._readableState) === null || _stream$_readableStat4 === void 0 ? void 0 : _stream$_readableStat4.errored) !== null && _ref !== void 0 ? _ref : (_stream$_writableStat4 = stream2._writableState) === null || _stream$_writableStat4 === void 0 ? void 0 : _stream$_writableStat4.errored)); + } + utils$6 = { + isDestroyed, + kIsDestroyed, + isDisturbed, + kIsDisturbed, + isErrored, + kIsErrored, + isReadable, + kIsReadable, + kIsClosedPromise, + kControllerErrorFunction, + kIsWritable, + isClosed, + isDuplexNodeStream, + isFinished, + isIterable, + isReadableNodeStream, + isReadableStream, + isReadableEnded, + isReadableFinished, + isReadableErrored, + isNodeStream, + isWebStream, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableEnded, + isWritableFinished, + isWritableErrored, + isServerRequest, + isServerResponse, + willEmitClose, + isTransformStream + }; + return utils$6; +} +var hasRequiredEndOfStream$4; +function requireEndOfStream$4() { + if (hasRequiredEndOfStream$4) return endOfStream$4.exports; + hasRequiredEndOfStream$4 = 1; + const process2 = requireBrowser$j(); + const { AbortError, codes } = requireErrors(); + const { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_PREMATURE_CLOSE } = codes; + const { kEmptyObject, once: once2 } = requireUtil$3(); + const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = requireValidators(); + const { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = requirePrimordials(); + const { + isClosed, + isReadable, + isReadableNodeStream, + isReadableStream, + isReadableFinished, + isReadableErrored, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableFinished, + isWritableErrored, + isNodeStream, + willEmitClose: _willEmitClose, + kIsClosedPromise + } = requireUtils$6(); + let addAbortListener; + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + const nop = () => { + }; + function eos(stream2, options2, callback) { + var _options$readable, _options$writable; + if (arguments.length === 2) { + callback = options2; + options2 = kEmptyObject; + } else if (options2 == null) { + options2 = kEmptyObject; + } else { + validateObject(options2, "options"); + } + validateFunction(callback, "callback"); + validateAbortSignal(options2.signal, "options.signal"); + callback = once2(callback); + if (isReadableStream(stream2) || isWritableStream(stream2)) { + return eosWeb(stream2, options2, callback); + } + if (!isNodeStream(stream2)) { + throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream2); + } + const readable2 = (_options$readable = options2.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream(stream2); + const writable2 = (_options$writable = options2.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream(stream2); + const wState = stream2._writableState; + const rState = stream2._readableState; + const onlegacyfinish = () => { + if (!stream2.writable) { + onfinish(); + } + }; + let willEmitClose = _willEmitClose(stream2) && isReadableNodeStream(stream2) === readable2 && isWritableNodeStream(stream2) === writable2; + let writableFinished = isWritableFinished(stream2, false); + const onfinish = () => { + writableFinished = true; + if (stream2.destroyed) { + willEmitClose = false; + } + if (willEmitClose && (!stream2.readable || readable2)) { + return; + } + if (!readable2 || readableFinished) { + callback.call(stream2); + } + }; + let readableFinished = isReadableFinished(stream2, false); + const onend = () => { + readableFinished = true; + if (stream2.destroyed) { + willEmitClose = false; + } + if (willEmitClose && (!stream2.writable || writable2)) { + return; + } + if (!writable2 || writableFinished) { + callback.call(stream2); + } + }; + const onerror = (err) => { + callback.call(stream2, err); + }; + let closed = isClosed(stream2); + const onclose = () => { + closed = true; + const errored = isWritableErrored(stream2) || isReadableErrored(stream2); + if (errored && typeof errored !== "boolean") { + return callback.call(stream2, errored); + } + if (readable2 && !readableFinished && isReadableNodeStream(stream2, true)) { + if (!isReadableFinished(stream2, false)) return callback.call(stream2, new ERR_STREAM_PREMATURE_CLOSE()); + } + if (writable2 && !writableFinished) { + if (!isWritableFinished(stream2, false)) return callback.call(stream2, new ERR_STREAM_PREMATURE_CLOSE()); + } + callback.call(stream2); + }; + const onclosed = () => { + closed = true; + const errored = isWritableErrored(stream2) || isReadableErrored(stream2); + if (errored && typeof errored !== "boolean") { + return callback.call(stream2, errored); + } + callback.call(stream2); + }; + const onrequest = () => { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + if (!willEmitClose) { + stream2.on("abort", onclose); + } + if (stream2.req) { + onrequest(); + } else { + stream2.on("request", onrequest); + } + } else if (writable2 && !wState) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + if (!willEmitClose && typeof stream2.aborted === "boolean") { + stream2.on("aborted", onclose); + } + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (options2.error !== false) { + stream2.on("error", onerror); + } + stream2.on("close", onclose); + if (closed) { + process2.nextTick(onclose); + } else if (wState !== null && wState !== void 0 && wState.errorEmitted || rState !== null && rState !== void 0 && rState.errorEmitted) { + if (!willEmitClose) { + process2.nextTick(onclosed); + } + } else if (!readable2 && (!willEmitClose || isReadable(stream2)) && (writableFinished || isWritable(stream2) === false)) { + process2.nextTick(onclosed); + } else if (!writable2 && (!willEmitClose || isWritable(stream2)) && (readableFinished || isReadable(stream2) === false)) { + process2.nextTick(onclosed); + } else if (rState && stream2.req && stream2.aborted) { + process2.nextTick(onclosed); + } + const cleanup = () => { + callback = nop; + stream2.removeListener("aborted", onclose); + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.removeListener("close", onclose); + }; + if (options2.signal && !closed) { + const abort = () => { + const endCallback = callback; + cleanup(); + endCallback.call( + stream2, + new AbortError(void 0, { + cause: options2.signal.reason + }) + ); + }; + if (options2.signal.aborted) { + process2.nextTick(abort); + } else { + addAbortListener = addAbortListener || requireUtil$3().addAbortListener; + const disposable = addAbortListener(options2.signal, abort); + const originalCallback = callback; + callback = once2((...args) => { + disposable[SymbolDispose](); + originalCallback.apply(stream2, args); + }); + } + } + return cleanup; + } + function eosWeb(stream2, options2, callback) { + let isAborted = false; + let abort = nop; + if (options2.signal) { + abort = () => { + isAborted = true; + callback.call( + stream2, + new AbortError(void 0, { + cause: options2.signal.reason + }) + ); + }; + if (options2.signal.aborted) { + process2.nextTick(abort); + } else { + addAbortListener = addAbortListener || requireUtil$3().addAbortListener; + const disposable = addAbortListener(options2.signal, abort); + const originalCallback = callback; + callback = once2((...args) => { + disposable[SymbolDispose](); + originalCallback.apply(stream2, args); + }); + } + } + const resolverFn = (...args) => { + if (!isAborted) { + process2.nextTick(() => callback.apply(stream2, args)); + } + }; + PromisePrototypeThen(stream2[kIsClosedPromise].promise, resolverFn, resolverFn); + return nop; + } + function finished(stream2, opts) { + var _opts; + let autoCleanup = false; + if (opts === null) { + opts = kEmptyObject; + } + if ((_opts = opts) !== null && _opts !== void 0 && _opts.cleanup) { + validateBoolean(opts.cleanup, "cleanup"); + autoCleanup = opts.cleanup; + } + return new Promise2((resolve, reject) => { + const cleanup = eos(stream2, opts, (err) => { + if (autoCleanup) { + cleanup(); + } + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); + } + endOfStream$4.exports = eos; + endOfStream$4.exports.finished = finished; + return endOfStream$4.exports; +} +var destroy_1$3; +var hasRequiredDestroy$3; +function requireDestroy$3() { + if (hasRequiredDestroy$3) return destroy_1$3; + hasRequiredDestroy$3 = 1; + const process2 = requireBrowser$j(); + const { + aggregateTwoErrors, + codes: { ERR_MULTIPLE_CALLBACK }, + AbortError + } = requireErrors(); + const { Symbol: Symbol2 } = requirePrimordials(); + const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = requireUtils$6(); + const kDestroy = Symbol2("kDestroy"); + const kConstruct = Symbol2("kConstruct"); + function checkError(err, w, r) { + if (err) { + err.stack; + if (w && !w.errored) { + w.errored = err; + } + if (r && !r.errored) { + r.errored = err; + } + } + } + function destroy(err, cb) { + const r = this._readableState; + const w = this._writableState; + const s = w || r; + if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) { + if (typeof cb === "function") { + cb(); + } + return this; + } + checkError(err, w, r); + if (w) { + w.destroyed = true; + } + if (r) { + r.destroyed = true; + } + if (!s.constructed) { + this.once(kDestroy, function(er) { + _destroy(this, aggregateTwoErrors(er, err), cb); + }); + } else { + _destroy(this, err, cb); + } + return this; + } + function _destroy(self2, err, cb) { + let called = false; + function onDestroy(err2) { + if (called) { + return; + } + called = true; + const r = self2._readableState; + const w = self2._writableState; + checkError(err2, w, r); + if (w) { + w.closed = true; + } + if (r) { + r.closed = true; + } + if (typeof cb === "function") { + cb(err2); + } + if (err2) { + process2.nextTick(emitErrorCloseNT, self2, err2); + } else { + process2.nextTick(emitCloseNT, self2); + } + } + try { + self2._destroy(err || null, onDestroy); + } catch (err2) { + onDestroy(err2); + } + } + function emitErrorCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + const r = self2._readableState; + const w = self2._writableState; + if (w) { + w.closeEmitted = true; + } + if (r) { + r.closeEmitted = true; + } + if (w !== null && w !== void 0 && w.emitClose || r !== null && r !== void 0 && r.emitClose) { + self2.emit("close"); + } + } + function emitErrorNT(self2, err) { + const r = self2._readableState; + const w = self2._writableState; + if (w !== null && w !== void 0 && w.errorEmitted || r !== null && r !== void 0 && r.errorEmitted) { + return; + } + if (w) { + w.errorEmitted = true; + } + if (r) { + r.errorEmitted = true; + } + self2.emit("error", err); + } + function undestroy() { + const r = this._readableState; + const w = this._writableState; + if (r) { + r.constructed = true; + r.closed = false; + r.closeEmitted = false; + r.destroyed = false; + r.errored = null; + r.errorEmitted = false; + r.reading = false; + r.ended = r.readable === false; + r.endEmitted = r.readable === false; + } + if (w) { + w.constructed = true; + w.destroyed = false; + w.closed = false; + w.closeEmitted = false; + w.errored = null; + w.errorEmitted = false; + w.finalCalled = false; + w.prefinished = false; + w.ended = w.writable === false; + w.ending = w.writable === false; + w.finished = w.writable === false; + } + } + function errorOrDestroy(stream2, err, sync) { + const r = stream2._readableState; + const w = stream2._writableState; + if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) { + return this; + } + if (r !== null && r !== void 0 && r.autoDestroy || w !== null && w !== void 0 && w.autoDestroy) + stream2.destroy(err); + else if (err) { + err.stack; + if (w && !w.errored) { + w.errored = err; + } + if (r && !r.errored) { + r.errored = err; + } + if (sync) { + process2.nextTick(emitErrorNT, stream2, err); + } else { + emitErrorNT(stream2, err); + } + } + } + function construct(stream2, cb) { + if (typeof stream2._construct !== "function") { + return; + } + const r = stream2._readableState; + const w = stream2._writableState; + if (r) { + r.constructed = false; + } + if (w) { + w.constructed = false; + } + stream2.once(kConstruct, cb); + if (stream2.listenerCount(kConstruct) > 1) { + return; + } + process2.nextTick(constructNT, stream2); + } + function constructNT(stream2) { + let called = false; + function onConstruct(err) { + if (called) { + errorOrDestroy(stream2, err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK()); + return; + } + called = true; + const r = stream2._readableState; + const w = stream2._writableState; + const s = w || r; + if (r) { + r.constructed = true; + } + if (w) { + w.constructed = true; + } + if (s.destroyed) { + stream2.emit(kDestroy, err); + } else if (err) { + errorOrDestroy(stream2, err, true); + } else { + process2.nextTick(emitConstructNT, stream2); + } + } + try { + stream2._construct((err) => { + process2.nextTick(onConstruct, err); + }); + } catch (err) { + process2.nextTick(onConstruct, err); + } + } + function emitConstructNT(stream2) { + stream2.emit(kConstruct); + } + function isRequest(stream2) { + return (stream2 === null || stream2 === void 0 ? void 0 : stream2.setHeader) && typeof stream2.abort === "function"; + } + function emitCloseLegacy(stream2) { + stream2.emit("close"); + } + function emitErrorCloseLegacy(stream2, err) { + stream2.emit("error", err); + process2.nextTick(emitCloseLegacy, stream2); + } + function destroyer(stream2, err) { + if (!stream2 || isDestroyed(stream2)) { + return; + } + if (!err && !isFinished(stream2)) { + err = new AbortError(); + } + if (isServerRequest(stream2)) { + stream2.socket = null; + stream2.destroy(err); + } else if (isRequest(stream2)) { + stream2.abort(); + } else if (isRequest(stream2.req)) { + stream2.req.abort(); + } else if (typeof stream2.destroy === "function") { + stream2.destroy(err); + } else if (typeof stream2.close === "function") { + stream2.close(); + } else if (err) { + process2.nextTick(emitErrorCloseLegacy, stream2, err); + } else { + process2.nextTick(emitCloseLegacy, stream2); + } + if (!stream2.destroyed) { + stream2[kIsDestroyed] = true; + } + } + destroy_1$3 = { + construct, + destroyer, + destroy, + undestroy, + errorOrDestroy + }; + return destroy_1$3; +} +var legacy$1; +var hasRequiredLegacy$1; +function requireLegacy$1() { + if (hasRequiredLegacy$1) return legacy$1; + hasRequiredLegacy$1 = 1; + const { ArrayIsArray, ObjectSetPrototypeOf } = requirePrimordials(); + const { EventEmitter: EE } = requireEvents(); + function Stream2(opts) { + EE.call(this, opts); + } + ObjectSetPrototypeOf(Stream2.prototype, EE.prototype); + ObjectSetPrototypeOf(Stream2, EE); + Stream2.prototype.pipe = function(dest, options2) { + const source2 = this; + function ondata(chunk) { + if (dest.writable && dest.write(chunk) === false && source2.pause) { + source2.pause(); + } + } + source2.on("data", ondata); + function ondrain() { + if (source2.readable && source2.resume) { + source2.resume(); + } + } + dest.on("drain", ondrain); + if (!dest._isStdio && (!options2 || options2.end !== false)) { + source2.on("end", onend); + source2.on("close", onclose); + } + let didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + dest.end(); + } + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + if (typeof dest.destroy === "function") dest.destroy(); + } + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, "error") === 0) { + this.emit("error", er); + } + } + prependListener(source2, "error", onerror); + prependListener(dest, "error", onerror); + function cleanup() { + source2.removeListener("data", ondata); + dest.removeListener("drain", ondrain); + source2.removeListener("end", onend); + source2.removeListener("close", onclose); + source2.removeListener("error", onerror); + dest.removeListener("error", onerror); + source2.removeListener("end", cleanup); + source2.removeListener("close", cleanup); + dest.removeListener("close", cleanup); + } + source2.on("end", cleanup); + source2.on("close", cleanup); + dest.on("close", cleanup); + dest.emit("pipe", source2); + return dest; + }; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + legacy$1 = { + Stream: Stream2, + prependListener + }; + return legacy$1; +} +var addAbortSignal = { exports: {} }; +var hasRequiredAddAbortSignal; +function requireAddAbortSignal() { + if (hasRequiredAddAbortSignal) return addAbortSignal.exports; + hasRequiredAddAbortSignal = 1; + (function(module) { + const { SymbolDispose } = requirePrimordials(); + const { AbortError, codes } = requireErrors(); + const { isNodeStream, isWebStream, kControllerErrorFunction } = requireUtils$6(); + const eos = requireEndOfStream$4(); + const { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2 } = codes; + let addAbortListener; + const validateAbortSignal = (signal, name) => { + if (typeof signal !== "object" || !("aborted" in signal)) { + throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal); + } + }; + module.exports.addAbortSignal = function addAbortSignal2(signal, stream2) { + validateAbortSignal(signal, "signal"); + if (!isNodeStream(stream2) && !isWebStream(stream2)) { + throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream2); + } + return module.exports.addAbortSignalNoValidate(signal, stream2); + }; + module.exports.addAbortSignalNoValidate = function(signal, stream2) { + if (typeof signal !== "object" || !("aborted" in signal)) { + return stream2; + } + const onAbort = isNodeStream(stream2) ? () => { + stream2.destroy( + new AbortError(void 0, { + cause: signal.reason + }) + ); + } : () => { + stream2[kControllerErrorFunction]( + new AbortError(void 0, { + cause: signal.reason + }) + ); + }; + if (signal.aborted) { + onAbort(); + } else { + addAbortListener = addAbortListener || requireUtil$3().addAbortListener; + const disposable = addAbortListener(signal, onAbort); + eos(stream2, disposable[SymbolDispose]); + } + return stream2; + }; + })(addAbortSignal); + return addAbortSignal.exports; +} +var buffer_list$3; +var hasRequiredBuffer_list$3; +function requireBuffer_list$3() { + if (hasRequiredBuffer_list$3) return buffer_list$3; + hasRequiredBuffer_list$3 = 1; + const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = requirePrimordials(); + const { Buffer: Buffer2 } = requireBuffer$2(); + const { inspect } = requireUtil$3(); + buffer_list$3 = class BufferList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; + } + push(v) { + const entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + unshift(v) { + const entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + shift() { + if (this.length === 0) return; + const ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + clear() { + this.head = this.tail = null; + this.length = 0; + } + join(s) { + if (this.length === 0) return ""; + let p = this.head; + let ret = "" + p.data; + while ((p = p.next) !== null) ret += s + p.data; + return ret; + } + concat(n) { + if (this.length === 0) return Buffer2.alloc(0); + const ret = Buffer2.allocUnsafe(n >>> 0); + let p = this.head; + let i = 0; + while (p) { + TypedArrayPrototypeSet(ret, p.data, i); + i += p.data.length; + p = p.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + consume(n, hasStrings) { + const data2 = this.head.data; + if (n < data2.length) { + const slice = data2.slice(0, n); + this.head.data = data2.slice(n); + return slice; + } + if (n === data2.length) { + return this.shift(); + } + return hasStrings ? this._getString(n) : this._getBuffer(n); + } + first() { + return this.head.data; + } + *[SymbolIterator]() { + for (let p = this.head; p; p = p.next) { + yield p.data; + } + } + // Consumes a specified amount of characters from the buffered data. + _getString(n) { + let ret = ""; + let p = this.head; + let c = 0; + do { + const str = p.data; + if (n > str.length) { + ret += str; + n -= str.length; + } else { + if (n === str.length) { + ret += str; + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + ret += StringPrototypeSlice(str, 0, n); + this.head = p; + p.data = StringPrototypeSlice(str, n); + } + break; + } + ++c; + } while ((p = p.next) !== null); + this.length -= c; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + _getBuffer(n) { + const ret = Buffer2.allocUnsafe(n); + const retLen = n; + let p = this.head; + let c = 0; + do { + const buf = p.data; + if (n > buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n); + n -= buf.length; + } else { + if (n === buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n); + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n), retLen - n); + this.head = p; + p.data = buf.slice(n); + } + break; + } + ++c; + } while ((p = p.next) !== null); + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + [Symbol.for("nodejs.util.inspect.custom")](_, options2) { + return inspect(this, { + ...options2, + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + }); + } + }; + return buffer_list$3; +} +var state$3; +var hasRequiredState$3; +function requireState$3() { + if (hasRequiredState$3) return state$3; + hasRequiredState$3 = 1; + const { MathFloor, NumberIsInteger } = requirePrimordials(); + const { validateInteger } = requireValidators(); + const { ERR_INVALID_ARG_VALUE } = requireErrors().codes; + let defaultHighWaterMarkBytes = 16 * 1024; + let defaultHighWaterMarkObjectMode = 16; + function highWaterMarkFrom(options2, isDuplex, duplexKey) { + return options2.highWaterMark != null ? options2.highWaterMark : isDuplex ? options2[duplexKey] : null; + } + function getDefaultHighWaterMark(objectMode) { + return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes; + } + function setDefaultHighWaterMark(objectMode, value) { + validateInteger(value, "value", 0); + if (objectMode) { + defaultHighWaterMarkObjectMode = value; + } else { + defaultHighWaterMarkBytes = value; + } + } + function getHighWaterMark(state2, options2, duplexKey, isDuplex) { + const hwm = highWaterMarkFrom(options2, isDuplex, duplexKey); + if (hwm != null) { + if (!NumberIsInteger(hwm) || hwm < 0) { + const name = isDuplex ? `options.${duplexKey}` : "options.highWaterMark"; + throw new ERR_INVALID_ARG_VALUE(name, hwm); + } + return MathFloor(hwm); + } + return getDefaultHighWaterMark(state2.objectMode); + } + state$3 = { + getHighWaterMark, + getDefaultHighWaterMark, + setDefaultHighWaterMark + }; + return state$3; +} +var string_decoder = {}; +var safeBuffer = { exports: {} }; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +var hasRequiredSafeBuffer; +function requireSafeBuffer() { + if (hasRequiredSafeBuffer) return safeBuffer.exports; + hasRequiredSafeBuffer = 1; + (function(module, exports) { + var buffer2 = requireBuffer$2(); + var Buffer2 = buffer2.Buffer; + function copyProps(src2, dst) { + for (var key2 in src2) { + dst[key2] = src2[key2]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module.exports = buffer2; + } else { + copyProps(buffer2, exports); + exports.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); + } + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size, fill, encoding2) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + if (fill !== void 0) { + if (typeof encoding2 === "string") { + buf.fill(fill, encoding2); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer2.SlowBuffer(size); + }; + })(safeBuffer, safeBuffer.exports); + return safeBuffer.exports; +} +var hasRequiredString_decoder; +function requireString_decoder() { + if (hasRequiredString_decoder) return string_decoder; + hasRequiredString_decoder = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding2) { + encoding2 = "" + encoding2; + switch (encoding2 && encoding2.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _normalizeEncoding(enc) { + if (!enc) return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) return; + enc = ("" + enc).toLowerCase(); + retried = true; + } + } + } + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); + return nenc || enc; + } + string_decoder.StringDecoder = StringDecoder; + function StringDecoder(encoding2) { + this.encoding = normalizeEncoding(encoding2); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); + } + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) return ""; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === void 0) return ""; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + function utf8CheckByte(byte) { + if (byte <= 127) return 0; + else if (byte >> 5 === 6) return 2; + else if (byte >> 4 === 14) return 3; + else if (byte >> 3 === 30) return 4; + return byte >> 6 === 2 ? -1 : -2; + } + function utf8CheckIncomplete(self2, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0; + else self2.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + function utf8CheckExtraBytes(self2, buf, p) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "�"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "�"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "�"; + } + } + } + } + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf); + if (r !== void 0) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString("utf8", i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i, end); + } + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + "�"; + return r; + } + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString("utf16le", i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 55296 && c <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i, buf.length - 1); + } + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); + } + return r; + } + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString("base64", i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i, buf.length - n); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + return string_decoder; +} +var from_1; +var hasRequiredFrom; +function requireFrom() { + if (hasRequiredFrom) return from_1; + hasRequiredFrom = 1; + const process2 = requireBrowser$j(); + const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = requirePrimordials(); + const { Buffer: Buffer2 } = requireBuffer$2(); + const { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_NULL_VALUES } = requireErrors().codes; + function from2(Readable, iterable, opts) { + let iterator; + if (typeof iterable === "string" || iterable instanceof Buffer2) { + return new Readable({ + objectMode: true, + ...opts, + read() { + this.push(iterable); + this.push(null); + } + }); + } + let isAsync; + if (iterable && iterable[SymbolAsyncIterator]) { + isAsync = true; + iterator = iterable[SymbolAsyncIterator](); + } else if (iterable && iterable[SymbolIterator]) { + isAsync = false; + iterator = iterable[SymbolIterator](); + } else { + throw new ERR_INVALID_ARG_TYPE2("iterable", ["Iterable"], iterable); + } + const readable2 = new Readable({ + objectMode: true, + highWaterMark: 1, + // TODO(ronag): What options should be allowed? + ...opts + }); + let reading = false; + readable2._read = function() { + if (!reading) { + reading = true; + next(); + } + }; + readable2._destroy = function(error2, cb) { + PromisePrototypeThen( + close2(error2), + () => process2.nextTick(cb, error2), + // nextTick is here in case cb throws + (e) => process2.nextTick(cb, e || error2) + ); + }; + async function close2(error2) { + const hadError = error2 !== void 0 && error2 !== null; + const hasThrow = typeof iterator.throw === "function"; + if (hadError && hasThrow) { + const { value, done } = await iterator.throw(error2); + await value; + if (done) { + return; + } + } + if (typeof iterator.return === "function") { + const { value } = await iterator.return(); + await value; + } + } + async function next() { + for (; ; ) { + try { + const { value, done } = isAsync ? await iterator.next() : iterator.next(); + if (done) { + readable2.push(null); + } else { + const res = value && typeof value.then === "function" ? await value : value; + if (res === null) { + reading = false; + throw new ERR_STREAM_NULL_VALUES(); + } else if (readable2.push(res)) { + continue; + } else { + reading = false; + } + } + } catch (err) { + readable2.destroy(err); + } + break; + } + } + return readable2; + } + from_1 = from2; + return from_1; +} +var readable; +var hasRequiredReadable; +function requireReadable() { + if (hasRequiredReadable) return readable; + hasRequiredReadable = 1; + const process2 = requireBrowser$j(); + const { + ArrayPrototypeIndexOf, + NumberIsInteger, + NumberIsNaN, + NumberParseInt, + ObjectDefineProperties, + ObjectKeys, + ObjectSetPrototypeOf, + Promise: Promise2, + SafeSet, + SymbolAsyncDispose, + SymbolAsyncIterator, + Symbol: Symbol2 + } = requirePrimordials(); + readable = Readable; + Readable.ReadableState = ReadableState; + const { EventEmitter: EE } = requireEvents(); + const { Stream: Stream2, prependListener } = requireLegacy$1(); + const { Buffer: Buffer2 } = requireBuffer$2(); + const { addAbortSignal: addAbortSignal2 } = requireAddAbortSignal(); + const eos = requireEndOfStream$4(); + let debug2 = requireUtil$3().debuglog("stream", (fn) => { + debug2 = fn; + }); + const BufferList = requireBuffer_list$3(); + const destroyImpl = requireDestroy$3(); + const { getHighWaterMark, getDefaultHighWaterMark } = requireState$3(); + const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OUT_OF_RANGE, + ERR_STREAM_PUSH_AFTER_EOF, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT + }, + AbortError + } = requireErrors(); + const { validateObject } = requireValidators(); + const kPaused = Symbol2("kPaused"); + const { StringDecoder } = requireString_decoder(); + const from2 = requireFrom(); + ObjectSetPrototypeOf(Readable.prototype, Stream2.prototype); + ObjectSetPrototypeOf(Readable, Stream2); + const nop = () => { + }; + const { errorOrDestroy } = destroyImpl; + const kObjectMode = 1 << 0; + const kEnded = 1 << 1; + const kEndEmitted = 1 << 2; + const kReading = 1 << 3; + const kConstructed = 1 << 4; + const kSync = 1 << 5; + const kNeedReadable = 1 << 6; + const kEmittedReadable = 1 << 7; + const kReadableListening = 1 << 8; + const kResumeScheduled = 1 << 9; + const kErrorEmitted = 1 << 10; + const kEmitClose = 1 << 11; + const kAutoDestroy = 1 << 12; + const kDestroyed = 1 << 13; + const kClosed = 1 << 14; + const kCloseEmitted = 1 << 15; + const kMultiAwaitDrain = 1 << 16; + const kReadingMore = 1 << 17; + const kDataEmitted = 1 << 18; + function makeBitMapDescriptor(bit) { + return { + enumerable: false, + get() { + return (this.state & bit) !== 0; + }, + set(value) { + if (value) this.state |= bit; + else this.state &= ~bit; + } + }; + } + ObjectDefineProperties(ReadableState.prototype, { + objectMode: makeBitMapDescriptor(kObjectMode), + ended: makeBitMapDescriptor(kEnded), + endEmitted: makeBitMapDescriptor(kEndEmitted), + reading: makeBitMapDescriptor(kReading), + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + constructed: makeBitMapDescriptor(kConstructed), + // A flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + sync: makeBitMapDescriptor(kSync), + // Whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + needReadable: makeBitMapDescriptor(kNeedReadable), + emittedReadable: makeBitMapDescriptor(kEmittedReadable), + readableListening: makeBitMapDescriptor(kReadableListening), + resumeScheduled: makeBitMapDescriptor(kResumeScheduled), + // True if the error was already emitted and should not be thrown again. + errorEmitted: makeBitMapDescriptor(kErrorEmitted), + emitClose: makeBitMapDescriptor(kEmitClose), + autoDestroy: makeBitMapDescriptor(kAutoDestroy), + // Has it been destroyed. + destroyed: makeBitMapDescriptor(kDestroyed), + // Indicates whether the stream has finished destroying. + closed: makeBitMapDescriptor(kClosed), + // True if close has been emitted or would have been emitted + // depending on emitClose. + closeEmitted: makeBitMapDescriptor(kCloseEmitted), + multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), + // If true, a maybeReadMore has been scheduled. + readingMore: makeBitMapDescriptor(kReadingMore), + dataEmitted: makeBitMapDescriptor(kDataEmitted) + }); + function ReadableState(options2, stream2, isDuplex) { + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof requireDuplex(); + this.state = kEmitClose | kAutoDestroy | kConstructed | kSync; + if (options2 && options2.objectMode) this.state |= kObjectMode; + if (isDuplex && options2 && options2.readableObjectMode) this.state |= kObjectMode; + this.highWaterMark = options2 ? getHighWaterMark(this, options2, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = []; + this.flowing = null; + this[kPaused] = null; + if (options2 && options2.emitClose === false) this.state &= -2049; + if (options2 && options2.autoDestroy === false) this.state &= -4097; + this.errored = null; + this.defaultEncoding = options2 && options2.defaultEncoding || "utf8"; + this.awaitDrainWriters = null; + this.decoder = null; + this.encoding = null; + if (options2 && options2.encoding) { + this.decoder = new StringDecoder(options2.encoding); + this.encoding = options2.encoding; + } + } + function Readable(options2) { + if (!(this instanceof Readable)) return new Readable(options2); + const isDuplex = this instanceof requireDuplex(); + this._readableState = new ReadableState(options2, this, isDuplex); + if (options2) { + if (typeof options2.read === "function") this._read = options2.read; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + if (typeof options2.construct === "function") this._construct = options2.construct; + if (options2.signal && !isDuplex) addAbortSignal2(options2.signal, this); + } + Stream2.call(this, options2); + destroyImpl.construct(this, () => { + if (this._readableState.needReadable) { + maybeReadMore(this, this._readableState); + } + }); + } + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype[EE.captureRejectionSymbol] = function(err) { + this.destroy(err); + }; + Readable.prototype[SymbolAsyncDispose] = function() { + let error2; + if (!this.destroyed) { + error2 = this.readableEnded ? null : new AbortError(); + this.destroy(error2); + } + return new Promise2((resolve, reject) => eos(this, (err) => err && err !== error2 ? reject(err) : resolve(null))); + }; + Readable.prototype.push = function(chunk, encoding2) { + return readableAddChunk(this, chunk, encoding2, false); + }; + Readable.prototype.unshift = function(chunk, encoding2) { + return readableAddChunk(this, chunk, encoding2, true); + }; + function readableAddChunk(stream2, chunk, encoding2, addToFront) { + debug2("readableAddChunk", chunk); + const state2 = stream2._readableState; + let err; + if ((state2.state & kObjectMode) === 0) { + if (typeof chunk === "string") { + encoding2 = encoding2 || state2.defaultEncoding; + if (state2.encoding !== encoding2) { + if (addToFront && state2.encoding) { + chunk = Buffer2.from(chunk, encoding2).toString(state2.encoding); + } else { + chunk = Buffer2.from(chunk, encoding2); + encoding2 = ""; + } + } + } else if (chunk instanceof Buffer2) { + encoding2 = ""; + } else if (Stream2._isUint8Array(chunk)) { + chunk = Stream2._uint8ArrayToBuffer(chunk); + encoding2 = ""; + } else if (chunk != null) { + err = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + } + if (err) { + errorOrDestroy(stream2, err); + } else if (chunk === null) { + state2.state &= -9; + onEofChunk(stream2, state2); + } else if ((state2.state & kObjectMode) !== 0 || chunk && chunk.length > 0) { + if (addToFront) { + if ((state2.state & kEndEmitted) !== 0) errorOrDestroy(stream2, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else if (state2.destroyed || state2.errored) return false; + else addChunk(stream2, state2, chunk, true); + } else if (state2.ended) { + errorOrDestroy(stream2, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state2.destroyed || state2.errored) { + return false; + } else { + state2.state &= -9; + if (state2.decoder && !encoding2) { + chunk = state2.decoder.write(chunk); + if (state2.objectMode || chunk.length !== 0) addChunk(stream2, state2, chunk, false); + else maybeReadMore(stream2, state2); + } else { + addChunk(stream2, state2, chunk, false); + } + } + } else if (!addToFront) { + state2.state &= -9; + maybeReadMore(stream2, state2); + } + return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0); + } + function addChunk(stream2, state2, chunk, addToFront) { + if (state2.flowing && state2.length === 0 && !state2.sync && stream2.listenerCount("data") > 0) { + if ((state2.state & kMultiAwaitDrain) !== 0) { + state2.awaitDrainWriters.clear(); + } else { + state2.awaitDrainWriters = null; + } + state2.dataEmitted = true; + stream2.emit("data", chunk); + } else { + state2.length += state2.objectMode ? 1 : chunk.length; + if (addToFront) state2.buffer.unshift(chunk); + else state2.buffer.push(chunk); + if ((state2.state & kNeedReadable) !== 0) emitReadable(stream2); + } + maybeReadMore(stream2, state2); + } + Readable.prototype.isPaused = function() { + const state2 = this._readableState; + return state2[kPaused] === true || state2.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + const decoder2 = new StringDecoder(enc); + this._readableState.decoder = decoder2; + this._readableState.encoding = this._readableState.decoder.encoding; + const buffer2 = this._readableState.buffer; + let content = ""; + for (const data2 of buffer2) { + content += decoder2.write(data2); + } + buffer2.clear(); + if (content !== "") buffer2.push(content); + this._readableState.length = content.length; + return this; + }; + const MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n > MAX_HWM) { + throw new ERR_OUT_OF_RANGE("size", "<= 1GiB", n); + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state2) { + if (n <= 0 || state2.length === 0 && state2.ended) return 0; + if ((state2.state & kObjectMode) !== 0) return 1; + if (NumberIsNaN(n)) { + if (state2.flowing && state2.length) return state2.buffer.first().length; + return state2.length; + } + if (n <= state2.length) return n; + return state2.ended ? state2.length : 0; + } + Readable.prototype.read = function(n) { + debug2("read", n); + if (n === void 0) { + n = NaN; + } else if (!NumberIsInteger(n)) { + n = NumberParseInt(n, 10); + } + const state2 = this._readableState; + const nOrig = n; + if (n > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n); + if (n !== 0) state2.state &= -129; + if (n === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) { + debug2("read: emitReadable", state2.length, state2.ended); + if (state2.length === 0 && state2.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state2); + if (n === 0 && state2.ended) { + if (state2.length === 0) endReadable(this); + return null; + } + let doRead = (state2.state & kNeedReadable) !== 0; + debug2("need readable", doRead); + if (state2.length === 0 || state2.length - n < state2.highWaterMark) { + doRead = true; + debug2("length less than watermark", doRead); + } + if (state2.ended || state2.reading || state2.destroyed || state2.errored || !state2.constructed) { + doRead = false; + debug2("reading, ended or constructing", doRead); + } else if (doRead) { + debug2("do read"); + state2.state |= kReading | kSync; + if (state2.length === 0) state2.state |= kNeedReadable; + try { + this._read(state2.highWaterMark); + } catch (err) { + errorOrDestroy(this, err); + } + state2.state &= -33; + if (!state2.reading) n = howMuchToRead(nOrig, state2); + } + let ret; + if (n > 0) ret = fromList(n, state2); + else ret = null; + if (ret === null) { + state2.needReadable = state2.length <= state2.highWaterMark; + n = 0; + } else { + state2.length -= n; + if (state2.multiAwaitDrain) { + state2.awaitDrainWriters.clear(); + } else { + state2.awaitDrainWriters = null; + } + } + if (state2.length === 0) { + if (!state2.ended) state2.needReadable = true; + if (nOrig !== n && state2.ended) endReadable(this); + } + if (ret !== null && !state2.errorEmitted && !state2.closeEmitted) { + state2.dataEmitted = true; + this.emit("data", ret); + } + return ret; + }; + function onEofChunk(stream2, state2) { + debug2("onEofChunk"); + if (state2.ended) return; + if (state2.decoder) { + const chunk = state2.decoder.end(); + if (chunk && chunk.length) { + state2.buffer.push(chunk); + state2.length += state2.objectMode ? 1 : chunk.length; + } + } + state2.ended = true; + if (state2.sync) { + emitReadable(stream2); + } else { + state2.needReadable = false; + state2.emittedReadable = true; + emitReadable_(stream2); + } + } + function emitReadable(stream2) { + const state2 = stream2._readableState; + debug2("emitReadable", state2.needReadable, state2.emittedReadable); + state2.needReadable = false; + if (!state2.emittedReadable) { + debug2("emitReadable", state2.flowing); + state2.emittedReadable = true; + process2.nextTick(emitReadable_, stream2); + } + } + function emitReadable_(stream2) { + const state2 = stream2._readableState; + debug2("emitReadable_", state2.destroyed, state2.length, state2.ended); + if (!state2.destroyed && !state2.errored && (state2.length || state2.ended)) { + stream2.emit("readable"); + state2.emittedReadable = false; + } + state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark; + flow(stream2); + } + function maybeReadMore(stream2, state2) { + if (!state2.readingMore && state2.constructed) { + state2.readingMore = true; + process2.nextTick(maybeReadMore_, stream2, state2); + } + } + function maybeReadMore_(stream2, state2) { + while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) { + const len = state2.length; + debug2("maybeReadMore read 0"); + stream2.read(0); + if (len === state2.length) + break; + } + state2.readingMore = false; + } + Readable.prototype._read = function(n) { + throw new ERR_METHOD_NOT_IMPLEMENTED("_read()"); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + const src2 = this; + const state2 = this._readableState; + if (state2.pipes.length === 1) { + if (!state2.multiAwaitDrain) { + state2.multiAwaitDrain = true; + state2.awaitDrainWriters = new SafeSet(state2.awaitDrainWriters ? [state2.awaitDrainWriters] : []); + } + } + state2.pipes.push(dest); + debug2("pipe count=%d opts=%j", state2.pipes.length, pipeOpts); + const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process2.stdout && dest !== process2.stderr; + const endFn = doEnd ? onend : unpipe; + if (state2.endEmitted) process2.nextTick(endFn); + else src2.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable2, unpipeInfo) { + debug2("onunpipe"); + if (readable2 === src2) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug2("onend"); + dest.end(); + } + let ondrain; + let cleanedUp = false; + function cleanup() { + debug2("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + if (ondrain) { + dest.removeListener("drain", ondrain); + } + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src2.removeListener("end", onend); + src2.removeListener("end", unpipe); + src2.removeListener("data", ondata); + cleanedUp = true; + if (ondrain && state2.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + function pause() { + if (!cleanedUp) { + if (state2.pipes.length === 1 && state2.pipes[0] === dest) { + debug2("false write response, pause", 0); + state2.awaitDrainWriters = dest; + state2.multiAwaitDrain = false; + } else if (state2.pipes.length > 1 && state2.pipes.includes(dest)) { + debug2("false write response, pause", state2.awaitDrainWriters.size); + state2.awaitDrainWriters.add(dest); + } + src2.pause(); + } + if (!ondrain) { + ondrain = pipeOnDrain(src2, dest); + dest.on("drain", ondrain); + } + } + src2.on("data", ondata); + function ondata(chunk) { + debug2("ondata"); + const ret = dest.write(chunk); + debug2("dest.write", ret); + if (ret === false) { + pause(); + } + } + function onerror(er) { + debug2("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (dest.listenerCount("error") === 0) { + const s = dest._writableState || dest._readableState; + if (s && !s.errorEmitted) { + errorOrDestroy(dest, er); + } else { + dest.emit("error", er); + } + } + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug2("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug2("unpipe"); + src2.unpipe(dest); + } + dest.emit("pipe", src2); + if (dest.writableNeedDrain === true) { + pause(); + } else if (!state2.flowing) { + debug2("pipe resume"); + src2.resume(); + } + return dest; + }; + function pipeOnDrain(src2, dest) { + return function pipeOnDrainFunctionResult() { + const state2 = src2._readableState; + if (state2.awaitDrainWriters === dest) { + debug2("pipeOnDrain", 1); + state2.awaitDrainWriters = null; + } else if (state2.multiAwaitDrain) { + debug2("pipeOnDrain", state2.awaitDrainWriters.size); + state2.awaitDrainWriters.delete(dest); + } + if ((!state2.awaitDrainWriters || state2.awaitDrainWriters.size === 0) && src2.listenerCount("data")) { + src2.resume(); + } + }; + } + Readable.prototype.unpipe = function(dest) { + const state2 = this._readableState; + const unpipeInfo = { + hasUnpiped: false + }; + if (state2.pipes.length === 0) return this; + if (!dest) { + const dests = state2.pipes; + state2.pipes = []; + this.pause(); + for (let i = 0; i < dests.length; i++) + dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + const index2 = ArrayPrototypeIndexOf(state2.pipes, dest); + if (index2 === -1) return this; + state2.pipes.splice(index2, 1); + if (state2.pipes.length === 0) this.pause(); + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + const res = Stream2.prototype.on.call(this, ev, fn); + const state2 = this._readableState; + if (ev === "data") { + state2.readableListening = this.listenerCount("readable") > 0; + if (state2.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state2.endEmitted && !state2.readableListening) { + state2.readableListening = state2.needReadable = true; + state2.flowing = false; + state2.emittedReadable = false; + debug2("on readable", state2.length, state2.reading); + if (state2.length) { + emitReadable(this); + } else if (!state2.reading) { + process2.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + const res = Stream2.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + process2.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.off = Readable.prototype.removeListener; + Readable.prototype.removeAllListeners = function(ev) { + const res = Stream2.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process2.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + const state2 = self2._readableState; + state2.readableListening = self2.listenerCount("readable") > 0; + if (state2.resumeScheduled && state2[kPaused] === false) { + state2.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } else if (!state2.readableListening) { + state2.flowing = null; + } + } + function nReadingNextTick(self2) { + debug2("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + const state2 = this._readableState; + if (!state2.flowing) { + debug2("resume"); + state2.flowing = !state2.readableListening; + resume(this, state2); + } + state2[kPaused] = false; + return this; + }; + function resume(stream2, state2) { + if (!state2.resumeScheduled) { + state2.resumeScheduled = true; + process2.nextTick(resume_, stream2, state2); + } + } + function resume_(stream2, state2) { + debug2("resume", state2.reading); + if (!state2.reading) { + stream2.read(0); + } + state2.resumeScheduled = false; + stream2.emit("resume"); + flow(stream2); + if (state2.flowing && !state2.reading) stream2.read(0); + } + Readable.prototype.pause = function() { + debug2("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug2("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState[kPaused] = true; + return this; + }; + function flow(stream2) { + const state2 = stream2._readableState; + debug2("flow", state2.flowing); + while (state2.flowing && stream2.read() !== null) ; + } + Readable.prototype.wrap = function(stream2) { + let paused = false; + stream2.on("data", (chunk) => { + if (!this.push(chunk) && stream2.pause) { + paused = true; + stream2.pause(); + } + }); + stream2.on("end", () => { + this.push(null); + }); + stream2.on("error", (err) => { + errorOrDestroy(this, err); + }); + stream2.on("close", () => { + this.destroy(); + }); + stream2.on("destroy", () => { + this.destroy(); + }); + this._read = () => { + if (paused && stream2.resume) { + paused = false; + stream2.resume(); + } + }; + const streamKeys = ObjectKeys(stream2); + for (let j = 1; j < streamKeys.length; j++) { + const i = streamKeys[j]; + if (this[i] === void 0 && typeof stream2[i] === "function") { + this[i] = stream2[i].bind(stream2); + } + } + return this; + }; + Readable.prototype[SymbolAsyncIterator] = function() { + return streamToAsyncIterator(this); + }; + Readable.prototype.iterator = function(options2) { + if (options2 !== void 0) { + validateObject(options2, "options"); + } + return streamToAsyncIterator(this, options2); + }; + function streamToAsyncIterator(stream2, options2) { + if (typeof stream2.read !== "function") { + stream2 = Readable.wrap(stream2, { + objectMode: true + }); + } + const iter = createAsyncIterator(stream2, options2); + iter.stream = stream2; + return iter; + } + async function* createAsyncIterator(stream2, options2) { + let callback = nop; + function next(resolve) { + if (this === stream2) { + callback(); + callback = nop; + } else { + callback = resolve; + } + } + stream2.on("readable", next); + let error2; + const cleanup = eos( + stream2, + { + writable: false + }, + (err) => { + error2 = err ? aggregateTwoErrors(error2, err) : null; + callback(); + callback = nop; + } + ); + try { + while (true) { + const chunk = stream2.destroyed ? null : stream2.read(); + if (chunk !== null) { + yield chunk; + } else if (error2) { + throw error2; + } else if (error2 === null) { + return; + } else { + await new Promise2(next); + } + } + } catch (err) { + error2 = aggregateTwoErrors(error2, err); + throw error2; + } finally { + if ((error2 || (options2 === null || options2 === void 0 ? void 0 : options2.destroyOnReturn) !== false) && (error2 === void 0 || stream2._readableState.autoDestroy)) { + destroyImpl.destroyer(stream2, null); + } else { + stream2.off("readable", next); + cleanup(); + } + } + } + ObjectDefineProperties(Readable.prototype, { + readable: { + __proto__: null, + get() { + const r = this._readableState; + return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted; + }, + set(val) { + if (this._readableState) { + this._readableState.readable = !!val; + } + } + }, + readableDidRead: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState.dataEmitted; + } + }, + readableAborted: { + __proto__: null, + enumerable: false, + get: function() { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } + }, + readableHighWaterMark: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState.highWaterMark; + } + }, + readableBuffer: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState && this._readableState.buffer; + } + }, + readableFlowing: { + __proto__: null, + enumerable: false, + get: function() { + return this._readableState.flowing; + }, + set: function(state2) { + if (this._readableState) { + this._readableState.flowing = state2; + } + } + }, + readableLength: { + __proto__: null, + enumerable: false, + get() { + return this._readableState.length; + } + }, + readableObjectMode: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.objectMode : false; + } + }, + readableEncoding: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.encoding : null; + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.errored : null; + } + }, + closed: { + __proto__: null, + get() { + return this._readableState ? this._readableState.closed : false; + } + }, + destroyed: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.destroyed : false; + }, + set(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }, + readableEnded: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.endEmitted : false; + } + } + }); + ObjectDefineProperties(ReadableState.prototype, { + // Legacy getter for `pipesCount`. + pipesCount: { + __proto__: null, + get() { + return this.pipes.length; + } + }, + // Legacy property for `paused`. + paused: { + __proto__: null, + get() { + return this[kPaused] !== false; + }, + set(value) { + this[kPaused] = !!value; + } + } + }); + Readable._fromList = fromList; + function fromList(n, state2) { + if (state2.length === 0) return null; + let ret; + if (state2.objectMode) ret = state2.buffer.shift(); + else if (!n || n >= state2.length) { + if (state2.decoder) ret = state2.buffer.join(""); + else if (state2.buffer.length === 1) ret = state2.buffer.first(); + else ret = state2.buffer.concat(state2.length); + state2.buffer.clear(); + } else { + ret = state2.buffer.consume(n, state2.decoder); + } + return ret; + } + function endReadable(stream2) { + const state2 = stream2._readableState; + debug2("endReadable", state2.endEmitted); + if (!state2.endEmitted) { + state2.ended = true; + process2.nextTick(endReadableNT, state2, stream2); + } + } + function endReadableNT(state2, stream2) { + debug2("endReadableNT", state2.endEmitted, state2.length); + if (!state2.errored && !state2.closeEmitted && !state2.endEmitted && state2.length === 0) { + state2.endEmitted = true; + stream2.emit("end"); + if (stream2.writable && stream2.allowHalfOpen === false) { + process2.nextTick(endWritableNT, stream2); + } else if (state2.autoDestroy) { + const wState = stream2._writableState; + const autoDestroy = !wState || wState.autoDestroy && // We don't expect the writable to ever 'finish' + // if writable is explicitly set to false. + (wState.finished || wState.writable === false); + if (autoDestroy) { + stream2.destroy(); + } + } + } + } + function endWritableNT(stream2) { + const writable2 = stream2.writable && !stream2.writableEnded && !stream2.destroyed; + if (writable2) { + stream2.end(); + } + } + Readable.from = function(iterable, opts) { + return from2(Readable, iterable, opts); + }; + let webStreamsAdapters; + function lazyWebStreams() { + if (webStreamsAdapters === void 0) webStreamsAdapters = {}; + return webStreamsAdapters; + } + Readable.fromWeb = function(readableStream, options2) { + return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options2); + }; + Readable.toWeb = function(streamReadable, options2) { + return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options2); + }; + Readable.wrap = function(src2, options2) { + var _ref, _src$readableObjectMo; + return new Readable({ + objectMode: (_ref = (_src$readableObjectMo = src2.readableObjectMode) !== null && _src$readableObjectMo !== void 0 ? _src$readableObjectMo : src2.objectMode) !== null && _ref !== void 0 ? _ref : true, + ...options2, + destroy(err, callback) { + destroyImpl.destroyer(src2, err); + callback(err); + } + }).wrap(src2); + }; + return readable; +} +var writable; +var hasRequiredWritable; +function requireWritable() { + if (hasRequiredWritable) return writable; + hasRequiredWritable = 1; + const process2 = requireBrowser$j(); + const { + ArrayPrototypeSlice, + Error: Error2, + FunctionPrototypeSymbolHasInstance, + ObjectDefineProperty, + ObjectDefineProperties, + ObjectSetPrototypeOf, + StringPrototypeToLowerCase, + Symbol: Symbol2, + SymbolHasInstance + } = requirePrimordials(); + writable = Writable; + Writable.WritableState = WritableState; + const { EventEmitter: EE } = requireEvents(); + const Stream2 = requireLegacy$1().Stream; + const { Buffer: Buffer2 } = requireBuffer$2(); + const destroyImpl = requireDestroy$3(); + const { addAbortSignal: addAbortSignal2 } = requireAddAbortSignal(); + const { getHighWaterMark, getDefaultHighWaterMark } = requireState$3(); + const { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED, + ERR_STREAM_ALREADY_FINISHED, + ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING + } = requireErrors().codes; + const { errorOrDestroy } = destroyImpl; + ObjectSetPrototypeOf(Writable.prototype, Stream2.prototype); + ObjectSetPrototypeOf(Writable, Stream2); + function nop() { + } + const kOnFinished = Symbol2("kOnFinished"); + function WritableState(options2, stream2, isDuplex) { + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof requireDuplex(); + this.objectMode = !!(options2 && options2.objectMode); + if (isDuplex) this.objectMode = this.objectMode || !!(options2 && options2.writableObjectMode); + this.highWaterMark = options2 ? getHighWaterMark(this, options2, "writableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + const noDecode = !!(options2 && options2.decodeStrings === false); + this.decodeStrings = !noDecode; + this.defaultEncoding = options2 && options2.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = onwrite.bind(void 0, stream2); + this.writecb = null; + this.writelen = 0; + this.afterWriteTickInfo = null; + resetBuffer(this); + this.pendingcb = 0; + this.constructed = true; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = !options2 || options2.emitClose !== false; + this.autoDestroy = !options2 || options2.autoDestroy !== false; + this.errored = null; + this.closed = false; + this.closeEmitted = false; + this[kOnFinished] = []; + } + function resetBuffer(state2) { + state2.buffered = []; + state2.bufferedIndex = 0; + state2.allBuffers = true; + state2.allNoop = true; + } + WritableState.prototype.getBuffer = function getBuffer() { + return ArrayPrototypeSlice(this.buffered, this.bufferedIndex); + }; + ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", { + __proto__: null, + get() { + return this.buffered.length - this.bufferedIndex; + } + }); + function Writable(options2) { + const isDuplex = this instanceof requireDuplex(); + if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options2); + this._writableState = new WritableState(options2, this, isDuplex); + if (options2) { + if (typeof options2.write === "function") this._write = options2.write; + if (typeof options2.writev === "function") this._writev = options2.writev; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + if (typeof options2.final === "function") this._final = options2.final; + if (typeof options2.construct === "function") this._construct = options2.construct; + if (options2.signal) addAbortSignal2(options2.signal, this); + } + Stream2.call(this, options2); + destroyImpl.construct(this, () => { + const state2 = this._writableState; + if (!state2.writing) { + clearBuffer(this, state2); + } + finishMaybe(this, state2); + }); + } + ObjectDefineProperty(Writable, SymbolHasInstance, { + __proto__: null, + value: function(object) { + if (FunctionPrototypeSymbolHasInstance(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function _write(stream2, chunk, encoding2, cb) { + const state2 = stream2._writableState; + if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = state2.defaultEncoding; + } else { + if (!encoding2) encoding2 = state2.defaultEncoding; + else if (encoding2 !== "buffer" && !Buffer2.isEncoding(encoding2)) throw new ERR_UNKNOWN_ENCODING(encoding2); + if (typeof cb !== "function") cb = nop; + } + if (chunk === null) { + throw new ERR_STREAM_NULL_VALUES(); + } else if (!state2.objectMode) { + if (typeof chunk === "string") { + if (state2.decodeStrings !== false) { + chunk = Buffer2.from(chunk, encoding2); + encoding2 = "buffer"; + } + } else if (chunk instanceof Buffer2) { + encoding2 = "buffer"; + } else if (Stream2._isUint8Array(chunk)) { + chunk = Stream2._uint8ArrayToBuffer(chunk); + encoding2 = "buffer"; + } else { + throw new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + } + let err; + if (state2.ending) { + err = new ERR_STREAM_WRITE_AFTER_END(); + } else if (state2.destroyed) { + err = new ERR_STREAM_DESTROYED("write"); + } + if (err) { + process2.nextTick(cb, err); + errorOrDestroy(stream2, err, true); + return err; + } + state2.pendingcb++; + return writeOrBuffer(stream2, state2, chunk, encoding2, cb); + } + Writable.prototype.write = function(chunk, encoding2, cb) { + return _write(this, chunk, encoding2, cb) === true; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + const state2 = this._writableState; + if (state2.corked) { + state2.corked--; + if (!state2.writing) clearBuffer(this, state2); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding2) { + if (typeof encoding2 === "string") encoding2 = StringPrototypeToLowerCase(encoding2); + if (!Buffer2.isEncoding(encoding2)) throw new ERR_UNKNOWN_ENCODING(encoding2); + this._writableState.defaultEncoding = encoding2; + return this; + }; + function writeOrBuffer(stream2, state2, chunk, encoding2, callback) { + const len = state2.objectMode ? 1 : chunk.length; + state2.length += len; + const ret = state2.length < state2.highWaterMark; + if (!ret) state2.needDrain = true; + if (state2.writing || state2.corked || state2.errored || !state2.constructed) { + state2.buffered.push({ + chunk, + encoding: encoding2, + callback + }); + if (state2.allBuffers && encoding2 !== "buffer") { + state2.allBuffers = false; + } + if (state2.allNoop && callback !== nop) { + state2.allNoop = false; + } + } else { + state2.writelen = len; + state2.writecb = callback; + state2.writing = true; + state2.sync = true; + stream2._write(chunk, encoding2, state2.onwrite); + state2.sync = false; + } + return ret && !state2.errored && !state2.destroyed; + } + function doWrite(stream2, state2, writev2, len, chunk, encoding2, cb) { + state2.writelen = len; + state2.writecb = cb; + state2.writing = true; + state2.sync = true; + if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev2) stream2._writev(chunk, state2.onwrite); + else stream2._write(chunk, encoding2, state2.onwrite); + state2.sync = false; + } + function onwriteError(stream2, state2, er, cb) { + --state2.pendingcb; + cb(er); + errorBuffer(state2); + errorOrDestroy(stream2, er); + } + function onwrite(stream2, er) { + const state2 = stream2._writableState; + const sync = state2.sync; + const cb = state2.writecb; + if (typeof cb !== "function") { + errorOrDestroy(stream2, new ERR_MULTIPLE_CALLBACK()); + return; + } + state2.writing = false; + state2.writecb = null; + state2.length -= state2.writelen; + state2.writelen = 0; + if (er) { + er.stack; + if (!state2.errored) { + state2.errored = er; + } + if (stream2._readableState && !stream2._readableState.errored) { + stream2._readableState.errored = er; + } + if (sync) { + process2.nextTick(onwriteError, stream2, state2, er, cb); + } else { + onwriteError(stream2, state2, er, cb); + } + } else { + if (state2.buffered.length > state2.bufferedIndex) { + clearBuffer(stream2, state2); + } + if (sync) { + if (state2.afterWriteTickInfo !== null && state2.afterWriteTickInfo.cb === cb) { + state2.afterWriteTickInfo.count++; + } else { + state2.afterWriteTickInfo = { + count: 1, + cb, + stream: stream2, + state: state2 + }; + process2.nextTick(afterWriteTick, state2.afterWriteTickInfo); + } + } else { + afterWrite(stream2, state2, 1, cb); + } + } + } + function afterWriteTick({ stream: stream2, state: state2, count, cb }) { + state2.afterWriteTickInfo = null; + return afterWrite(stream2, state2, count, cb); + } + function afterWrite(stream2, state2, count, cb) { + const needDrain = !state2.ending && !stream2.destroyed && state2.length === 0 && state2.needDrain; + if (needDrain) { + state2.needDrain = false; + stream2.emit("drain"); + } + while (count-- > 0) { + state2.pendingcb--; + cb(); + } + if (state2.destroyed) { + errorBuffer(state2); + } + finishMaybe(stream2, state2); + } + function errorBuffer(state2) { + if (state2.writing) { + return; + } + for (let n = state2.bufferedIndex; n < state2.buffered.length; ++n) { + var _state$errored; + const { chunk, callback } = state2.buffered[n]; + const len = state2.objectMode ? 1 : chunk.length; + state2.length -= len; + callback( + (_state$errored = state2.errored) !== null && _state$errored !== void 0 ? _state$errored : new ERR_STREAM_DESTROYED("write") + ); + } + const onfinishCallbacks = state2[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + var _state$errored2; + onfinishCallbacks[i]( + (_state$errored2 = state2.errored) !== null && _state$errored2 !== void 0 ? _state$errored2 : new ERR_STREAM_DESTROYED("end") + ); + } + resetBuffer(state2); + } + function clearBuffer(stream2, state2) { + if (state2.corked || state2.bufferProcessing || state2.destroyed || !state2.constructed) { + return; + } + const { buffered, bufferedIndex, objectMode } = state2; + const bufferedLength = buffered.length - bufferedIndex; + if (!bufferedLength) { + return; + } + let i = bufferedIndex; + state2.bufferProcessing = true; + if (bufferedLength > 1 && stream2._writev) { + state2.pendingcb -= bufferedLength - 1; + const callback = state2.allNoop ? nop : (err) => { + for (let n = i; n < buffered.length; ++n) { + buffered[n].callback(err); + } + }; + const chunks = state2.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i); + chunks.allBuffers = state2.allBuffers; + doWrite(stream2, state2, true, state2.length, chunks, "", callback); + resetBuffer(state2); + } else { + do { + const { chunk, encoding: encoding2, callback } = buffered[i]; + buffered[i++] = null; + const len = objectMode ? 1 : chunk.length; + doWrite(stream2, state2, false, len, chunk, encoding2, callback); + } while (i < buffered.length && !state2.writing); + if (i === buffered.length) { + resetBuffer(state2); + } else if (i > 256) { + buffered.splice(0, i); + state2.bufferedIndex = 0; + } else { + state2.bufferedIndex = i; + } + } + state2.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding2, cb) { + if (this._writev) { + this._writev( + [ + { + chunk, + encoding: encoding2 + } + ], + cb + ); + } else { + throw new ERR_METHOD_NOT_IMPLEMENTED("_write()"); + } + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding2, cb) { + const state2 = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding2 = null; + } else if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + let err; + if (chunk !== null && chunk !== void 0) { + const ret = _write(this, chunk, encoding2); + if (ret instanceof Error2) { + err = ret; + } + } + if (state2.corked) { + state2.corked = 1; + this.uncork(); + } + if (err) ; + else if (!state2.errored && !state2.ending) { + state2.ending = true; + finishMaybe(this, state2, true); + state2.ended = true; + } else if (state2.finished) { + err = new ERR_STREAM_ALREADY_FINISHED("end"); + } else if (state2.destroyed) { + err = new ERR_STREAM_DESTROYED("end"); + } + if (typeof cb === "function") { + if (err || state2.finished) { + process2.nextTick(cb, err); + } else { + state2[kOnFinished].push(cb); + } + } + return this; + }; + function needFinish(state2) { + return state2.ending && !state2.destroyed && state2.constructed && state2.length === 0 && !state2.errored && state2.buffered.length === 0 && !state2.finished && !state2.writing && !state2.errorEmitted && !state2.closeEmitted; + } + function callFinal(stream2, state2) { + let called = false; + function onFinish(err) { + if (called) { + errorOrDestroy(stream2, err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK()); + return; + } + called = true; + state2.pendingcb--; + if (err) { + const onfinishCallbacks = state2[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](err); + } + errorOrDestroy(stream2, err, state2.sync); + } else if (needFinish(state2)) { + state2.prefinished = true; + stream2.emit("prefinish"); + state2.pendingcb++; + process2.nextTick(finish, stream2, state2); + } + } + state2.sync = true; + state2.pendingcb++; + try { + stream2._final(onFinish); + } catch (err) { + onFinish(err); + } + state2.sync = false; + } + function prefinish(stream2, state2) { + if (!state2.prefinished && !state2.finalCalled) { + if (typeof stream2._final === "function" && !state2.destroyed) { + state2.finalCalled = true; + callFinal(stream2, state2); + } else { + state2.prefinished = true; + stream2.emit("prefinish"); + } + } + } + function finishMaybe(stream2, state2, sync) { + if (needFinish(state2)) { + prefinish(stream2, state2); + if (state2.pendingcb === 0) { + if (sync) { + state2.pendingcb++; + process2.nextTick( + (stream3, state3) => { + if (needFinish(state3)) { + finish(stream3, state3); + } else { + state3.pendingcb--; + } + }, + stream2, + state2 + ); + } else if (needFinish(state2)) { + state2.pendingcb++; + finish(stream2, state2); + } + } + } + } + function finish(stream2, state2) { + state2.pendingcb--; + state2.finished = true; + const onfinishCallbacks = state2[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](); + } + stream2.emit("finish"); + if (state2.autoDestroy) { + const rState = stream2._readableState; + const autoDestroy = !rState || rState.autoDestroy && // We don't expect the readable to ever 'end' + // if readable is explicitly set to false. + (rState.endEmitted || rState.readable === false); + if (autoDestroy) { + stream2.destroy(); + } + } + } + ObjectDefineProperties(Writable.prototype, { + closed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.closed : false; + } + }, + destroyed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.destroyed : false; + }, + set(value) { + if (this._writableState) { + this._writableState.destroyed = value; + } + } + }, + writable: { + __proto__: null, + get() { + const w = this._writableState; + return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended; + }, + set(val) { + if (this._writableState) { + this._writableState.writable = !!val; + } + } + }, + writableFinished: { + __proto__: null, + get() { + return this._writableState ? this._writableState.finished : false; + } + }, + writableObjectMode: { + __proto__: null, + get() { + return this._writableState ? this._writableState.objectMode : false; + } + }, + writableBuffer: { + __proto__: null, + get() { + return this._writableState && this._writableState.getBuffer(); + } + }, + writableEnded: { + __proto__: null, + get() { + return this._writableState ? this._writableState.ending : false; + } + }, + writableNeedDrain: { + __proto__: null, + get() { + const wState = this._writableState; + if (!wState) return false; + return !wState.destroyed && !wState.ending && wState.needDrain; + } + }, + writableHighWaterMark: { + __proto__: null, + get() { + return this._writableState && this._writableState.highWaterMark; + } + }, + writableCorked: { + __proto__: null, + get() { + return this._writableState ? this._writableState.corked : 0; + } + }, + writableLength: { + __proto__: null, + get() { + return this._writableState && this._writableState.length; + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._writableState ? this._writableState.errored : null; + } + }, + writableAborted: { + __proto__: null, + enumerable: false, + get: function() { + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } + } + }); + const destroy = destroyImpl.destroy; + Writable.prototype.destroy = function(err, cb) { + const state2 = this._writableState; + if (!state2.destroyed && (state2.bufferedIndex < state2.buffered.length || state2[kOnFinished].length)) { + process2.nextTick(errorBuffer, state2); + } + destroy.call(this, err, cb); + return this; + }; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + Writable.prototype[EE.captureRejectionSymbol] = function(err) { + this.destroy(err); + }; + let webStreamsAdapters; + function lazyWebStreams() { + if (webStreamsAdapters === void 0) webStreamsAdapters = {}; + return webStreamsAdapters; + } + Writable.fromWeb = function(writableStream, options2) { + return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options2); + }; + Writable.toWeb = function(streamWritable) { + return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable); + }; + return writable; +} +var duplexify; +var hasRequiredDuplexify; +function requireDuplexify() { + if (hasRequiredDuplexify) return duplexify; + hasRequiredDuplexify = 1; + const process2 = requireBrowser$j(); + const bufferModule = requireBuffer$2(); + const { + isReadable, + isWritable, + isIterable, + isNodeStream, + isReadableNodeStream, + isWritableNodeStream, + isDuplexNodeStream, + isReadableStream, + isWritableStream + } = requireUtils$6(); + const eos = requireEndOfStream$4(); + const { + AbortError, + codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_RETURN_VALUE } + } = requireErrors(); + const { destroyer } = requireDestroy$3(); + const Duplex = requireDuplex(); + const Readable = requireReadable(); + const Writable = requireWritable(); + const { createDeferredPromise } = requireUtil$3(); + const from2 = requireFrom(); + const Blob2 = globalThis.Blob || bufferModule.Blob; + const isBlob = typeof Blob2 !== "undefined" ? function isBlob2(b) { + return b instanceof Blob2; + } : function isBlob2(b) { + return false; + }; + const AbortController2 = globalThis.AbortController || requireBrowser$i().AbortController; + const { FunctionPrototypeCall } = requirePrimordials(); + class Duplexify extends Duplex { + constructor(options2) { + super(options2); + if ((options2 === null || options2 === void 0 ? void 0 : options2.readable) === false) { + this._readableState.readable = false; + this._readableState.ended = true; + this._readableState.endEmitted = true; + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.writable) === false) { + this._writableState.writable = false; + this._writableState.ending = true; + this._writableState.ended = true; + this._writableState.finished = true; + } + } + } + duplexify = function duplexify2(body, name) { + if (isDuplexNodeStream(body)) { + return body; + } + if (isReadableNodeStream(body)) { + return _duplexify({ + readable: body + }); + } + if (isWritableNodeStream(body)) { + return _duplexify({ + writable: body + }); + } + if (isNodeStream(body)) { + return _duplexify({ + writable: false, + readable: false + }); + } + if (isReadableStream(body)) { + return _duplexify({ + readable: Readable.fromWeb(body) + }); + } + if (isWritableStream(body)) { + return _duplexify({ + writable: Writable.fromWeb(body) + }); + } + if (typeof body === "function") { + const { value, write: write2, final, destroy } = fromAsyncGen(body); + if (isIterable(value)) { + return from2(Duplexify, value, { + // TODO (ronag): highWaterMark? + objectMode: true, + write: write2, + final, + destroy + }); + } + const then2 = value === null || value === void 0 ? void 0 : value.then; + if (typeof then2 === "function") { + let d; + const promise = FunctionPrototypeCall( + then2, + value, + (val) => { + if (val != null) { + throw new ERR_INVALID_RETURN_VALUE("nully", "body", val); + } + }, + (err) => { + destroyer(d, err); + } + ); + return d = new Duplexify({ + // TODO (ronag): highWaterMark? + objectMode: true, + readable: false, + write: write2, + final(cb) { + final(async () => { + try { + await promise; + process2.nextTick(cb, null); + } catch (err) { + process2.nextTick(cb, err); + } + }); + }, + destroy + }); + } + throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction", name, value); + } + if (isBlob(body)) { + return duplexify2(body.arrayBuffer()); + } + if (isIterable(body)) { + return from2(Duplexify, body, { + // TODO (ronag): highWaterMark? + objectMode: true, + writable: false + }); + } + if (isReadableStream(body === null || body === void 0 ? void 0 : body.readable) && isWritableStream(body === null || body === void 0 ? void 0 : body.writable)) { + return Duplexify.fromWeb(body); + } + if (typeof (body === null || body === void 0 ? void 0 : body.writable) === "object" || typeof (body === null || body === void 0 ? void 0 : body.readable) === "object") { + const readable2 = body !== null && body !== void 0 && body.readable ? isReadableNodeStream(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify2(body.readable) : void 0; + const writable2 = body !== null && body !== void 0 && body.writable ? isWritableNodeStream(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify2(body.writable) : void 0; + return _duplexify({ + readable: readable2, + writable: writable2 + }); + } + const then = body === null || body === void 0 ? void 0 : body.then; + if (typeof then === "function") { + let d; + FunctionPrototypeCall( + then, + body, + (val) => { + if (val != null) { + d.push(val); + } + d.push(null); + }, + (err) => { + destroyer(d, err); + } + ); + return d = new Duplexify({ + objectMode: true, + writable: false, + read() { + } + }); + } + throw new ERR_INVALID_ARG_TYPE2( + name, + [ + "Blob", + "ReadableStream", + "WritableStream", + "Stream", + "Iterable", + "AsyncIterable", + "Function", + "{ readable, writable } pair", + "Promise" + ], + body + ); + }; + function fromAsyncGen(fn) { + let { promise, resolve } = createDeferredPromise(); + const ac = new AbortController2(); + const signal = ac.signal; + const value = fn( + async function* () { + while (true) { + const _promise = promise; + promise = null; + const { chunk, done, cb } = await _promise; + process2.nextTick(cb); + if (done) return; + if (signal.aborted) + throw new AbortError(void 0, { + cause: signal.reason + }); + ({ promise, resolve } = createDeferredPromise()); + yield chunk; + } + }(), + { + signal + } + ); + return { + value, + write(chunk, encoding2, cb) { + const _resolve = resolve; + resolve = null; + _resolve({ + chunk, + done: false, + cb + }); + }, + final(cb) { + const _resolve = resolve; + resolve = null; + _resolve({ + done: true, + cb + }); + }, + destroy(err, cb) { + ac.abort(); + cb(err); + } + }; + } + function _duplexify(pair) { + const r = pair.readable && typeof pair.readable.read !== "function" ? Readable.wrap(pair.readable) : pair.readable; + const w = pair.writable; + let readable2 = !!isReadable(r); + let writable2 = !!isWritable(w); + let ondrain; + let onfinish; + let onreadable; + let onclose; + let d; + function onfinished(err) { + const cb = onclose; + onclose = null; + if (cb) { + cb(err); + } else if (err) { + d.destroy(err); + } + } + d = new Duplexify({ + // TODO (ronag): highWaterMark? + readableObjectMode: !!(r !== null && r !== void 0 && r.readableObjectMode), + writableObjectMode: !!(w !== null && w !== void 0 && w.writableObjectMode), + readable: readable2, + writable: writable2 + }); + if (writable2) { + eos(w, (err) => { + writable2 = false; + if (err) { + destroyer(r, err); + } + onfinished(err); + }); + d._write = function(chunk, encoding2, callback) { + if (w.write(chunk, encoding2)) { + callback(); + } else { + ondrain = callback; + } + }; + d._final = function(callback) { + w.end(); + onfinish = callback; + }; + w.on("drain", function() { + if (ondrain) { + const cb = ondrain; + ondrain = null; + cb(); + } + }); + w.on("finish", function() { + if (onfinish) { + const cb = onfinish; + onfinish = null; + cb(); + } + }); + } + if (readable2) { + eos(r, (err) => { + readable2 = false; + if (err) { + destroyer(r, err); + } + onfinished(err); + }); + r.on("readable", function() { + if (onreadable) { + const cb = onreadable; + onreadable = null; + cb(); + } + }); + r.on("end", function() { + d.push(null); + }); + d._read = function() { + while (true) { + const buf = r.read(); + if (buf === null) { + onreadable = d._read; + return; + } + if (!d.push(buf)) { + return; + } + } + }; + } + d._destroy = function(err, callback) { + if (!err && onclose !== null) { + err = new AbortError(); + } + onreadable = null; + ondrain = null; + onfinish = null; + if (onclose === null) { + callback(err); + } else { + onclose = callback; + destroyer(w, err); + destroyer(r, err); + } + }; + return d; + } + return duplexify; +} +var duplex; +var hasRequiredDuplex; +function requireDuplex() { + if (hasRequiredDuplex) return duplex; + hasRequiredDuplex = 1; + const { + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptor, + ObjectKeys, + ObjectSetPrototypeOf + } = requirePrimordials(); + duplex = Duplex; + const Readable = requireReadable(); + const Writable = requireWritable(); + ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype); + ObjectSetPrototypeOf(Duplex, Readable); + { + const keys = ObjectKeys(Writable.prototype); + for (let i = 0; i < keys.length; i++) { + const method = keys[i]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options2) { + if (!(this instanceof Duplex)) return new Duplex(options2); + Readable.call(this, options2); + Writable.call(this, options2); + if (options2) { + this.allowHalfOpen = options2.allowHalfOpen !== false; + if (options2.readable === false) { + this._readableState.readable = false; + this._readableState.ended = true; + this._readableState.endEmitted = true; + } + if (options2.writable === false) { + this._writableState.writable = false; + this._writableState.ending = true; + this._writableState.ended = true; + this._writableState.finished = true; + } + } else { + this.allowHalfOpen = true; + } + } + ObjectDefineProperties(Duplex.prototype, { + writable: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable") + }, + writableHighWaterMark: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableHighWaterMark") + }, + writableObjectMode: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableObjectMode") + }, + writableBuffer: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableBuffer") + }, + writableLength: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableLength") + }, + writableFinished: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableFinished") + }, + writableCorked: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableCorked") + }, + writableEnded: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableEnded") + }, + writableNeedDrain: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableNeedDrain") + }, + destroyed: { + __proto__: null, + get() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set(value) { + if (this._readableState && this._writableState) { + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + } + } + }); + let webStreamsAdapters; + function lazyWebStreams() { + if (webStreamsAdapters === void 0) webStreamsAdapters = {}; + return webStreamsAdapters; + } + Duplex.fromWeb = function(pair, options2) { + return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options2); + }; + Duplex.toWeb = function(duplex2) { + return lazyWebStreams().newReadableWritablePairFromDuplex(duplex2); + }; + let duplexify2; + Duplex.from = function(body) { + if (!duplexify2) { + duplexify2 = requireDuplexify(); + } + return duplexify2(body, "body"); + }; + return duplex; +} +var transform$1; +var hasRequiredTransform; +function requireTransform() { + if (hasRequiredTransform) return transform$1; + hasRequiredTransform = 1; + const { ObjectSetPrototypeOf, Symbol: Symbol2 } = requirePrimordials(); + transform$1 = Transform; + const { ERR_METHOD_NOT_IMPLEMENTED } = requireErrors().codes; + const Duplex = requireDuplex(); + const { getHighWaterMark } = requireState$3(); + ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype); + ObjectSetPrototypeOf(Transform, Duplex); + const kCallback = Symbol2("kCallback"); + function Transform(options2) { + if (!(this instanceof Transform)) return new Transform(options2); + const readableHighWaterMark = options2 ? getHighWaterMark(this, options2, "readableHighWaterMark", true) : null; + if (readableHighWaterMark === 0) { + options2 = { + ...options2, + highWaterMark: null, + readableHighWaterMark, + // TODO (ronag): 0 is not optimal since we have + // a "bug" where we check needDrain before calling _write and not after. + // Refs: https://github.com/nodejs/node/pull/32887 + // Refs: https://github.com/nodejs/node/pull/35941 + writableHighWaterMark: options2.writableHighWaterMark || 0 + }; + } + Duplex.call(this, options2); + this._readableState.sync = false; + this[kCallback] = null; + if (options2) { + if (typeof options2.transform === "function") this._transform = options2.transform; + if (typeof options2.flush === "function") this._flush = options2.flush; + } + this.on("prefinish", prefinish); + } + function final(cb) { + if (typeof this._flush === "function" && !this.destroyed) { + this._flush((er, data2) => { + if (er) { + if (cb) { + cb(er); + } else { + this.destroy(er); + } + return; + } + if (data2 != null) { + this.push(data2); + } + this.push(null); + if (cb) { + cb(); + } + }); + } else { + this.push(null); + if (cb) { + cb(); + } + } + } + function prefinish() { + if (this._final !== final) { + final.call(this); + } + } + Transform.prototype._final = final; + Transform.prototype._transform = function(chunk, encoding2, callback) { + throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()"); + }; + Transform.prototype._write = function(chunk, encoding2, callback) { + const rState = this._readableState; + const wState = this._writableState; + const length = rState.length; + this._transform(chunk, encoding2, (err, val) => { + if (err) { + callback(err); + return; + } + if (val != null) { + this.push(val); + } + if (wState.ended || // Backwards compat. + length === rState.length || // Backwards compat. + rState.length < rState.highWaterMark) { + callback(); + } else { + this[kCallback] = callback; + } + }); + }; + Transform.prototype._read = function() { + if (this[kCallback]) { + const callback = this[kCallback]; + this[kCallback] = null; + callback(); + } + }; + return transform$1; +} +var passthrough; +var hasRequiredPassthrough; +function requirePassthrough() { + if (hasRequiredPassthrough) return passthrough; + hasRequiredPassthrough = 1; + const { ObjectSetPrototypeOf } = requirePrimordials(); + passthrough = PassThrough; + const Transform = requireTransform(); + ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype); + ObjectSetPrototypeOf(PassThrough, Transform); + function PassThrough(options2) { + if (!(this instanceof PassThrough)) return new PassThrough(options2); + Transform.call(this, options2); + } + PassThrough.prototype._transform = function(chunk, encoding2, cb) { + cb(null, chunk); + }; + return passthrough; +} +var pipeline_1$3; +var hasRequiredPipeline$3; +function requirePipeline$3() { + if (hasRequiredPipeline$3) return pipeline_1$3; + hasRequiredPipeline$3 = 1; + const process2 = requireBrowser$j(); + const { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = requirePrimordials(); + const eos = requireEndOfStream$4(); + const { once: once2 } = requireUtil$3(); + const destroyImpl = requireDestroy$3(); + const Duplex = requireDuplex(); + const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, + ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED, + ERR_STREAM_PREMATURE_CLOSE + }, + AbortError + } = requireErrors(); + const { validateFunction, validateAbortSignal } = requireValidators(); + const { + isIterable, + isReadable, + isReadableNodeStream, + isNodeStream, + isTransformStream, + isWebStream, + isReadableStream, + isReadableFinished + } = requireUtils$6(); + const AbortController2 = globalThis.AbortController || requireBrowser$i().AbortController; + let PassThrough; + let Readable; + let addAbortListener; + function destroyer(stream2, reading, writing) { + let finished = false; + stream2.on("close", () => { + finished = true; + }); + const cleanup = eos( + stream2, + { + readable: reading, + writable: writing + }, + (err) => { + finished = !err; + } + ); + return { + destroy: (err) => { + if (finished) return; + finished = true; + destroyImpl.destroyer(stream2, err || new ERR_STREAM_DESTROYED("pipe")); + }, + cleanup + }; + } + function popCallback(streams) { + validateFunction(streams[streams.length - 1], "streams[stream.length - 1]"); + return streams.pop(); + } + function makeAsyncIterable(val) { + if (isIterable(val)) { + return val; + } else if (isReadableNodeStream(val)) { + return fromReadable(val); + } + throw new ERR_INVALID_ARG_TYPE2("val", ["Readable", "Iterable", "AsyncIterable"], val); + } + async function* fromReadable(val) { + if (!Readable) { + Readable = requireReadable(); + } + yield* Readable.prototype[SymbolAsyncIterator].call(val); + } + async function pumpToNode(iterable, writable2, finish, { end }) { + let error2; + let onresolve = null; + const resume = (err) => { + if (err) { + error2 = err; + } + if (onresolve) { + const callback = onresolve; + onresolve = null; + callback(); + } + }; + const wait = () => new Promise2((resolve, reject) => { + if (error2) { + reject(error2); + } else { + onresolve = () => { + if (error2) { + reject(error2); + } else { + resolve(); + } + }; + } + }); + writable2.on("drain", resume); + const cleanup = eos( + writable2, + { + readable: false + }, + resume + ); + try { + if (writable2.writableNeedDrain) { + await wait(); + } + for await (const chunk of iterable) { + if (!writable2.write(chunk)) { + await wait(); + } + } + if (end) { + writable2.end(); + await wait(); + } + finish(); + } catch (err) { + finish(error2 !== err ? aggregateTwoErrors(error2, err) : err); + } finally { + cleanup(); + writable2.off("drain", resume); + } + } + async function pumpToWeb(readable2, writable2, finish, { end }) { + if (isTransformStream(writable2)) { + writable2 = writable2.writable; + } + const writer = writable2.getWriter(); + try { + for await (const chunk of readable2) { + await writer.ready; + writer.write(chunk).catch(() => { + }); + } + await writer.ready; + if (end) { + await writer.close(); + } + finish(); + } catch (err) { + try { + await writer.abort(err); + finish(err); + } catch (err2) { + finish(err2); + } + } + } + function pipeline(...streams) { + return pipelineImpl(streams, once2(popCallback(streams))); + } + function pipelineImpl(streams, callback, opts) { + if (streams.length === 1 && ArrayIsArray(streams[0])) { + streams = streams[0]; + } + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + const ac = new AbortController2(); + const signal = ac.signal; + const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal; + const lastStreamCleanup = []; + validateAbortSignal(outerSignal, "options.signal"); + function abort() { + finishImpl(new AbortError()); + } + addAbortListener = addAbortListener || requireUtil$3().addAbortListener; + let disposable; + if (outerSignal) { + disposable = addAbortListener(outerSignal, abort); + } + let error2; + let value; + const destroys = []; + let finishCount = 0; + function finish(err) { + finishImpl(err, --finishCount === 0); + } + function finishImpl(err, final) { + var _disposable; + if (err && (!error2 || error2.code === "ERR_STREAM_PREMATURE_CLOSE")) { + error2 = err; + } + if (!error2 && !final) { + return; + } + while (destroys.length) { + destroys.shift()(error2); + } + (_disposable = disposable) === null || _disposable === void 0 ? void 0 : _disposable[SymbolDispose](); + ac.abort(); + if (final) { + if (!error2) { + lastStreamCleanup.forEach((fn) => fn()); + } + process2.nextTick(callback, error2, value); + } + } + let ret; + for (let i = 0; i < streams.length; i++) { + const stream2 = streams[i]; + const reading = i < streams.length - 1; + const writing = i > 0; + const end = reading || (opts === null || opts === void 0 ? void 0 : opts.end) !== false; + const isLastStream = i === streams.length - 1; + if (isNodeStream(stream2)) { + let onError = function(err) { + if (err && err.name !== "AbortError" && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + finish(err); + } + }; + if (end) { + const { destroy, cleanup } = destroyer(stream2, reading, writing); + destroys.push(destroy); + if (isReadable(stream2) && isLastStream) { + lastStreamCleanup.push(cleanup); + } + } + stream2.on("error", onError); + if (isReadable(stream2) && isLastStream) { + lastStreamCleanup.push(() => { + stream2.removeListener("error", onError); + }); + } + } + if (i === 0) { + if (typeof stream2 === "function") { + ret = stream2({ + signal + }); + if (!isIterable(ret)) { + throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret); + } + } else if (isIterable(stream2) || isReadableNodeStream(stream2) || isTransformStream(stream2)) { + ret = stream2; + } else { + ret = Duplex.from(stream2); + } + } else if (typeof stream2 === "function") { + if (isTransformStream(ret)) { + var _ret; + ret = makeAsyncIterable((_ret = ret) === null || _ret === void 0 ? void 0 : _ret.readable); + } else { + ret = makeAsyncIterable(ret); + } + ret = stream2(ret, { + signal + }); + if (reading) { + if (!isIterable(ret, true)) { + throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i - 1}]`, ret); + } + } else { + var _ret2; + if (!PassThrough) { + PassThrough = requirePassthrough(); + } + const pt = new PassThrough({ + objectMode: true + }); + const then = (_ret2 = ret) === null || _ret2 === void 0 ? void 0 : _ret2.then; + if (typeof then === "function") { + finishCount++; + then.call( + ret, + (val) => { + value = val; + if (val != null) { + pt.write(val); + } + if (end) { + pt.end(); + } + process2.nextTick(finish); + }, + (err) => { + pt.destroy(err); + process2.nextTick(finish, err); + } + ); + } else if (isIterable(ret, true)) { + finishCount++; + pumpToNode(ret, pt, finish, { + end + }); + } else if (isReadableStream(ret) || isTransformStream(ret)) { + const toRead = ret.readable || ret; + finishCount++; + pumpToNode(toRead, pt, finish, { + end + }); + } else { + throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise", "destination", ret); + } + ret = pt; + const { destroy, cleanup } = destroyer(ret, false, true); + destroys.push(destroy); + if (isLastStream) { + lastStreamCleanup.push(cleanup); + } + } + } else if (isNodeStream(stream2)) { + if (isReadableNodeStream(ret)) { + finishCount += 2; + const cleanup = pipe(ret, stream2, finish, { + end + }); + if (isReadable(stream2) && isLastStream) { + lastStreamCleanup.push(cleanup); + } + } else if (isTransformStream(ret) || isReadableStream(ret)) { + const toRead = ret.readable || ret; + finishCount++; + pumpToNode(toRead, stream2, finish, { + end + }); + } else if (isIterable(ret)) { + finishCount++; + pumpToNode(ret, stream2, finish, { + end + }); + } else { + throw new ERR_INVALID_ARG_TYPE2( + "val", + ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], + ret + ); + } + ret = stream2; + } else if (isWebStream(stream2)) { + if (isReadableNodeStream(ret)) { + finishCount++; + pumpToWeb(makeAsyncIterable(ret), stream2, finish, { + end + }); + } else if (isReadableStream(ret) || isIterable(ret)) { + finishCount++; + pumpToWeb(ret, stream2, finish, { + end + }); + } else if (isTransformStream(ret)) { + finishCount++; + pumpToWeb(ret.readable, stream2, finish, { + end + }); + } else { + throw new ERR_INVALID_ARG_TYPE2( + "val", + ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], + ret + ); + } + ret = stream2; + } else { + ret = Duplex.from(stream2); + } + } + if (signal !== null && signal !== void 0 && signal.aborted || outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted) { + process2.nextTick(abort); + } + return ret; + } + function pipe(src2, dst, finish, { end }) { + let ended = false; + dst.on("close", () => { + if (!ended) { + finish(new ERR_STREAM_PREMATURE_CLOSE()); + } + }); + src2.pipe(dst, { + end: false + }); + if (end) { + let endFn = function() { + ended = true; + dst.end(); + }; + if (isReadableFinished(src2)) { + process2.nextTick(endFn); + } else { + src2.once("end", endFn); + } + } else { + finish(); + } + eos( + src2, + { + readable: true, + writable: false + }, + (err) => { + const rState = src2._readableState; + if (err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState && rState.ended && !rState.errored && !rState.errorEmitted) { + src2.once("end", finish).once("error", finish); + } else { + finish(err); + } + } + ); + return eos( + dst, + { + readable: false, + writable: true + }, + finish + ); + } + pipeline_1$3 = { + pipelineImpl, + pipeline + }; + return pipeline_1$3; +} +var compose; +var hasRequiredCompose; +function requireCompose() { + if (hasRequiredCompose) return compose; + hasRequiredCompose = 1; + const { pipeline } = requirePipeline$3(); + const Duplex = requireDuplex(); + const { destroyer } = requireDestroy$3(); + const { + isNodeStream, + isReadable, + isWritable, + isWebStream, + isTransformStream, + isWritableStream, + isReadableStream + } = requireUtils$6(); + const { + AbortError, + codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } + } = requireErrors(); + const eos = requireEndOfStream$4(); + compose = function compose2(...streams) { + if (streams.length === 0) { + throw new ERR_MISSING_ARGS("streams"); + } + if (streams.length === 1) { + return Duplex.from(streams[0]); + } + const orgStreams = [...streams]; + if (typeof streams[0] === "function") { + streams[0] = Duplex.from(streams[0]); + } + if (typeof streams[streams.length - 1] === "function") { + const idx = streams.length - 1; + streams[idx] = Duplex.from(streams[idx]); + } + for (let n = 0; n < streams.length; ++n) { + if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { + continue; + } + if (n < streams.length - 1 && !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be readable"); + } + if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be writable"); + } + } + let ondrain; + let onfinish; + let onreadable; + let onclose; + let d; + function onfinished(err) { + const cb = onclose; + onclose = null; + if (cb) { + cb(err); + } else if (err) { + d.destroy(err); + } else if (!readable2 && !writable2) { + d.destroy(); + } + } + const head = streams[0]; + const tail = pipeline(streams, onfinished); + const writable2 = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)); + const readable2 = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)); + d = new Duplex({ + // TODO (ronag): highWaterMark? + writableObjectMode: !!(head !== null && head !== void 0 && head.writableObjectMode), + readableObjectMode: !!(tail !== null && tail !== void 0 && tail.readableObjectMode), + writable: writable2, + readable: readable2 + }); + if (writable2) { + if (isNodeStream(head)) { + d._write = function(chunk, encoding2, callback) { + if (head.write(chunk, encoding2)) { + callback(); + } else { + ondrain = callback; + } + }; + d._final = function(callback) { + head.end(); + onfinish = callback; + }; + head.on("drain", function() { + if (ondrain) { + const cb = ondrain; + ondrain = null; + cb(); + } + }); + } else if (isWebStream(head)) { + const writable3 = isTransformStream(head) ? head.writable : head; + const writer = writable3.getWriter(); + d._write = async function(chunk, encoding2, callback) { + try { + await writer.ready; + writer.write(chunk).catch(() => { + }); + callback(); + } catch (err) { + callback(err); + } + }; + d._final = async function(callback) { + try { + await writer.ready; + writer.close().catch(() => { + }); + onfinish = callback; + } catch (err) { + callback(err); + } + }; + } + const toRead = isTransformStream(tail) ? tail.readable : tail; + eos(toRead, () => { + if (onfinish) { + const cb = onfinish; + onfinish = null; + cb(); + } + }); + } + if (readable2) { + if (isNodeStream(tail)) { + tail.on("readable", function() { + if (onreadable) { + const cb = onreadable; + onreadable = null; + cb(); + } + }); + tail.on("end", function() { + d.push(null); + }); + d._read = function() { + while (true) { + const buf = tail.read(); + if (buf === null) { + onreadable = d._read; + return; + } + if (!d.push(buf)) { + return; + } + } + }; + } else if (isWebStream(tail)) { + const readable3 = isTransformStream(tail) ? tail.readable : tail; + const reader = readable3.getReader(); + d._read = async function() { + while (true) { + try { + const { value, done } = await reader.read(); + if (!d.push(value)) { + return; + } + if (done) { + d.push(null); + return; + } + } catch { + return; + } + } + }; + } + } + d._destroy = function(err, callback) { + if (!err && onclose !== null) { + err = new AbortError(); + } + onreadable = null; + ondrain = null; + onfinish = null; + if (onclose === null) { + callback(err); + } else { + onclose = callback; + if (isNodeStream(tail)) { + destroyer(tail, err); + } + } + }; + return d; + }; + return compose; +} +var hasRequiredOperators; +function requireOperators() { + if (hasRequiredOperators) return operators; + hasRequiredOperators = 1; + const AbortController2 = globalThis.AbortController || requireBrowser$i().AbortController; + const { + codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, + AbortError + } = requireErrors(); + const { validateAbortSignal, validateInteger, validateObject } = requireValidators(); + const kWeakHandler = requirePrimordials().Symbol("kWeak"); + const kResistStopPropagation = requirePrimordials().Symbol("kResistStopPropagation"); + const { finished } = requireEndOfStream$4(); + const staticCompose = requireCompose(); + const { addAbortSignalNoValidate } = requireAddAbortSignal(); + const { isWritable, isNodeStream } = requireUtils$6(); + const { deprecate } = requireUtil$3(); + const { + ArrayPrototypePush, + Boolean: Boolean2, + MathFloor, + Number: Number2, + NumberIsNaN, + Promise: Promise2, + PromiseReject, + PromiseResolve, + PromisePrototypeThen, + Symbol: Symbol2 + } = requirePrimordials(); + const kEmpty = Symbol2("kEmpty"); + const kEof = Symbol2("kEof"); + function compose2(stream2, options2) { + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + if (isNodeStream(stream2) && !isWritable(stream2)) { + throw new ERR_INVALID_ARG_VALUE("stream", stream2, "must be writable"); + } + const composedStream = staticCompose(this, stream2); + if (options2 !== null && options2 !== void 0 && options2.signal) { + addAbortSignalNoValidate(options2.signal, composedStream); + } + return composedStream; + } + function map2(fn, options2) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + } + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + let concurrency = 1; + if ((options2 === null || options2 === void 0 ? void 0 : options2.concurrency) != null) { + concurrency = MathFloor(options2.concurrency); + } + let highWaterMark = concurrency - 1; + if ((options2 === null || options2 === void 0 ? void 0 : options2.highWaterMark) != null) { + highWaterMark = MathFloor(options2.highWaterMark); + } + validateInteger(concurrency, "options.concurrency", 1); + validateInteger(highWaterMark, "options.highWaterMark", 0); + highWaterMark += concurrency; + return (async function* map3() { + const signal = requireUtil$3().AbortSignalAny( + [options2 === null || options2 === void 0 ? void 0 : options2.signal].filter(Boolean2) + ); + const stream2 = this; + const queue = []; + const signalOpt = { + signal + }; + let next; + let resume; + let done = false; + let cnt = 0; + function onCatch() { + done = true; + afterItemProcessed(); + } + function afterItemProcessed() { + cnt -= 1; + maybeResume(); + } + function maybeResume() { + if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { + resume(); + resume = null; + } + } + async function pump() { + try { + for await (let val of stream2) { + if (done) { + return; + } + if (signal.aborted) { + throw new AbortError(); + } + try { + val = fn(val, signalOpt); + if (val === kEmpty) { + continue; + } + val = PromiseResolve(val); + } catch (err) { + val = PromiseReject(err); + } + cnt += 1; + PromisePrototypeThen(val, afterItemProcessed, onCatch); + queue.push(val); + if (next) { + next(); + next = null; + } + if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { + await new Promise2((resolve) => { + resume = resolve; + }); + } + } + queue.push(kEof); + } catch (err) { + const val = PromiseReject(err); + PromisePrototypeThen(val, afterItemProcessed, onCatch); + queue.push(val); + } finally { + done = true; + if (next) { + next(); + next = null; + } + } + } + pump(); + try { + while (true) { + while (queue.length > 0) { + const val = await queue[0]; + if (val === kEof) { + return; + } + if (signal.aborted) { + throw new AbortError(); + } + if (val !== kEmpty) { + yield val; + } + queue.shift(); + maybeResume(); + } + await new Promise2((resolve) => { + next = resolve; + }); + } + } finally { + done = true; + if (resume) { + resume(); + resume = null; + } + } + }).call(this); + } + function asIndexedPairs(options2 = void 0) { + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + return (async function* asIndexedPairs2() { + let index2 = 0; + for await (const val of this) { + var _options$signal; + if (options2 !== null && options2 !== void 0 && (_options$signal = options2.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) { + throw new AbortError({ + cause: options2.signal.reason + }); + } + yield [index2++, val]; + } + }).call(this); + } + async function some(fn, options2 = void 0) { + for await (const unused of filter.call(this, fn, options2)) { + return true; + } + return false; + } + async function every(fn, options2 = void 0) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + } + return !await some.call( + this, + async (...args) => { + return !await fn(...args); + }, + options2 + ); + } + async function find(fn, options2) { + for await (const result of filter.call(this, fn, options2)) { + return result; + } + return void 0; + } + async function forEach(fn, options2) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + } + async function forEachFn(value, options3) { + await fn(value, options3); + return kEmpty; + } + for await (const unused of map2.call(this, forEachFn, options2)) ; + } + function filter(fn, options2) { + if (typeof fn !== "function") { + throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn); + } + async function filterFn(value, options3) { + if (await fn(value, options3)) { + return value; + } + return kEmpty; + } + return map2.call(this, filterFn, options2); + } + class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { + constructor() { + super("reduce"); + this.message = "Reduce of an empty stream requires an initial value"; + } + } + async function reduce(reducer, initialValue, options2) { + var _options$signal2; + if (typeof reducer !== "function") { + throw new ERR_INVALID_ARG_TYPE2("reducer", ["Function", "AsyncFunction"], reducer); + } + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + let hasInitialValue = arguments.length > 1; + if (options2 !== null && options2 !== void 0 && (_options$signal2 = options2.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) { + const err = new AbortError(void 0, { + cause: options2.signal.reason + }); + this.once("error", () => { + }); + await finished(this.destroy(err)); + throw err; + } + const ac = new AbortController2(); + const signal = ac.signal; + if (options2 !== null && options2 !== void 0 && options2.signal) { + const opts = { + once: true, + [kWeakHandler]: this, + [kResistStopPropagation]: true + }; + options2.signal.addEventListener("abort", () => ac.abort(), opts); + } + let gotAnyItemFromStream = false; + try { + for await (const value of this) { + var _options$signal3; + gotAnyItemFromStream = true; + if (options2 !== null && options2 !== void 0 && (_options$signal3 = options2.signal) !== null && _options$signal3 !== void 0 && _options$signal3.aborted) { + throw new AbortError(); + } + if (!hasInitialValue) { + initialValue = value; + hasInitialValue = true; + } else { + initialValue = await reducer(initialValue, value, { + signal + }); + } + } + if (!gotAnyItemFromStream && !hasInitialValue) { + throw new ReduceAwareErrMissingArgs(); + } + } finally { + ac.abort(); + } + return initialValue; + } + async function toArray(options2) { + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + const result = []; + for await (const val of this) { + var _options$signal4; + if (options2 !== null && options2 !== void 0 && (_options$signal4 = options2.signal) !== null && _options$signal4 !== void 0 && _options$signal4.aborted) { + throw new AbortError(void 0, { + cause: options2.signal.reason + }); + } + ArrayPrototypePush(result, val); + } + return result; + } + function flatMap(fn, options2) { + const values = map2.call(this, fn, options2); + return (async function* flatMap2() { + for await (const val of values) { + yield* val; + } + }).call(this); + } + function toIntegerOrInfinity(number) { + number = Number2(number); + if (NumberIsNaN(number)) { + return 0; + } + if (number < 0) { + throw new ERR_OUT_OF_RANGE("number", ">= 0", number); + } + return number; + } + function drop(number, options2 = void 0) { + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + number = toIntegerOrInfinity(number); + return (async function* drop2() { + var _options$signal5; + if (options2 !== null && options2 !== void 0 && (_options$signal5 = options2.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) { + throw new AbortError(); + } + for await (const val of this) { + var _options$signal6; + if (options2 !== null && options2 !== void 0 && (_options$signal6 = options2.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) { + throw new AbortError(); + } + if (number-- <= 0) { + yield val; + } + } + }).call(this); + } + function take(number, options2 = void 0) { + if (options2 != null) { + validateObject(options2, "options"); + } + if ((options2 === null || options2 === void 0 ? void 0 : options2.signal) != null) { + validateAbortSignal(options2.signal, "options.signal"); + } + number = toIntegerOrInfinity(number); + return (async function* take2() { + var _options$signal7; + if (options2 !== null && options2 !== void 0 && (_options$signal7 = options2.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) { + throw new AbortError(); + } + for await (const val of this) { + var _options$signal8; + if (options2 !== null && options2 !== void 0 && (_options$signal8 = options2.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) { + throw new AbortError(); + } + if (number-- > 0) { + yield val; + } + if (number <= 0) { + return; + } + } + }).call(this); + } + operators.streamReturningOperators = { + asIndexedPairs: deprecate(asIndexedPairs, "readable.asIndexedPairs will be removed in a future version."), + drop, + filter, + flatMap, + map: map2, + take, + compose: compose2 + }; + operators.promiseReturningOperators = { + every, + forEach, + reduce, + toArray, + some, + find + }; + return operators; +} +var promises$2; +var hasRequiredPromises; +function requirePromises() { + if (hasRequiredPromises) return promises$2; + hasRequiredPromises = 1; + const { ArrayPrototypePop, Promise: Promise2 } = requirePrimordials(); + const { isIterable, isNodeStream, isWebStream } = requireUtils$6(); + const { pipelineImpl: pl } = requirePipeline$3(); + const { finished } = requireEndOfStream$4(); + requireStream(); + function pipeline(...streams) { + return new Promise2((resolve, reject) => { + let signal; + let end; + const lastArg = streams[streams.length - 1]; + if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) { + const options2 = ArrayPrototypePop(streams); + signal = options2.signal; + end = options2.end; + } + pl( + streams, + (err, value) => { + if (err) { + reject(err); + } else { + resolve(value); + } + }, + { + signal, + end + } + ); + }); + } + promises$2 = { + finished, + pipeline + }; + return promises$2; +} +var hasRequiredStream; +function requireStream() { + if (hasRequiredStream) return stream$1.exports; + hasRequiredStream = 1; + const { Buffer: Buffer2 } = requireBuffer$2(); + const { ObjectDefineProperty, ObjectKeys, ReflectApply } = requirePrimordials(); + const { + promisify: { custom: customPromisify } + } = requireUtil$3(); + const { streamReturningOperators, promiseReturningOperators } = requireOperators(); + const { + codes: { ERR_ILLEGAL_CONSTRUCTOR } + } = requireErrors(); + const compose2 = requireCompose(); + const { setDefaultHighWaterMark, getDefaultHighWaterMark } = requireState$3(); + const { pipeline } = requirePipeline$3(); + const { destroyer } = requireDestroy$3(); + const eos = requireEndOfStream$4(); + const promises2 = requirePromises(); + const utils2 = requireUtils$6(); + const Stream2 = stream$1.exports = requireLegacy$1().Stream; + Stream2.isDestroyed = utils2.isDestroyed; + Stream2.isDisturbed = utils2.isDisturbed; + Stream2.isErrored = utils2.isErrored; + Stream2.isReadable = utils2.isReadable; + Stream2.isWritable = utils2.isWritable; + Stream2.Readable = requireReadable(); + for (const key2 of ObjectKeys(streamReturningOperators)) { + let fn = function(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR(); + } + return Stream2.Readable.from(ReflectApply(op, this, args)); + }; + const op = streamReturningOperators[key2]; + ObjectDefineProperty(fn, "name", { + __proto__: null, + value: op.name + }); + ObjectDefineProperty(fn, "length", { + __proto__: null, + value: op.length + }); + ObjectDefineProperty(Stream2.Readable.prototype, key2, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }); + } + for (const key2 of ObjectKeys(promiseReturningOperators)) { + let fn = function(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR(); + } + return ReflectApply(op, this, args); + }; + const op = promiseReturningOperators[key2]; + ObjectDefineProperty(fn, "name", { + __proto__: null, + value: op.name + }); + ObjectDefineProperty(fn, "length", { + __proto__: null, + value: op.length + }); + ObjectDefineProperty(Stream2.Readable.prototype, key2, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }); + } + Stream2.Writable = requireWritable(); + Stream2.Duplex = requireDuplex(); + Stream2.Transform = requireTransform(); + Stream2.PassThrough = requirePassthrough(); + Stream2.pipeline = pipeline; + const { addAbortSignal: addAbortSignal2 } = requireAddAbortSignal(); + Stream2.addAbortSignal = addAbortSignal2; + Stream2.finished = eos; + Stream2.destroy = destroyer; + Stream2.compose = compose2; + Stream2.setDefaultHighWaterMark = setDefaultHighWaterMark; + Stream2.getDefaultHighWaterMark = getDefaultHighWaterMark; + ObjectDefineProperty(Stream2, "promises", { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return promises2; + } + }); + ObjectDefineProperty(pipeline, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises2.pipeline; + } + }); + ObjectDefineProperty(eos, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises2.finished; + } + }); + Stream2.Stream = Stream2; + Stream2._isUint8Array = function isUint8Array(value) { + return value instanceof Uint8Array; + }; + Stream2._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + }; + return stream$1.exports; +} +var hasRequiredBrowser$h; +function requireBrowser$h() { + if (hasRequiredBrowser$h) return browser$i.exports; + hasRequiredBrowser$h = 1; + (function(module) { + const CustomStream = requireStream(); + const promises2 = requirePromises(); + const originalDestroy = CustomStream.Readable.destroy; + module.exports = CustomStream.Readable; + module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer; + module.exports._isUint8Array = CustomStream._isUint8Array; + module.exports.isDisturbed = CustomStream.isDisturbed; + module.exports.isErrored = CustomStream.isErrored; + module.exports.isReadable = CustomStream.isReadable; + module.exports.Readable = CustomStream.Readable; + module.exports.Writable = CustomStream.Writable; + module.exports.Duplex = CustomStream.Duplex; + module.exports.Transform = CustomStream.Transform; + module.exports.PassThrough = CustomStream.PassThrough; + module.exports.addAbortSignal = CustomStream.addAbortSignal; + module.exports.finished = CustomStream.finished; + module.exports.destroy = CustomStream.destroy; + module.exports.destroy = originalDestroy; + module.exports.pipeline = CustomStream.pipeline; + module.exports.compose = CustomStream.compose; + Object.defineProperty(CustomStream, "promises", { + configurable: true, + enumerable: true, + get() { + return promises2; + } + }); + module.exports.Stream = CustomStream.Stream; + module.exports.default = module.exports; + })(browser$i); + return browser$i.exports; +} +var FileHandle = {}; +var util$3 = {}; +var constants$7 = {}; +var hasRequiredConstants$6; +function requireConstants$6() { + if (hasRequiredConstants$6) return constants$7; + hasRequiredConstants$6 = 1; + Object.defineProperty(constants$7, "__esModule", { value: true }); + constants$7.FLAGS = constants$7.ERRSTR = void 0; + const constants_1 = requireConstants$7(); + constants$7.ERRSTR = { + PATH_STR: "path must be a string or Buffer", + // FD: 'file descriptor must be a unsigned 32-bit integer', + FD: "fd must be a file descriptor", + MODE_INT: "mode must be an int", + CB: "callback must be a function", + UID: "uid must be an unsigned int", + GID: "gid must be an unsigned int", + LEN: "len must be an integer", + ATIME: "atime must be an integer", + MTIME: "mtime must be an integer", + PREFIX: "filename prefix is required", + BUFFER: "buffer must be an instance of Buffer or StaticBuffer", + OFFSET: "offset must be an integer", + LENGTH: "length must be an integer", + POSITION: "position must be an integer" + }; + const { O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_SYNC } = constants_1.constants; + var FLAGS; + (function(FLAGS2) { + FLAGS2[FLAGS2["r"] = O_RDONLY] = "r"; + FLAGS2[FLAGS2["r+"] = O_RDWR] = "r+"; + FLAGS2[FLAGS2["rs"] = O_RDONLY | O_SYNC] = "rs"; + FLAGS2[FLAGS2["sr"] = FLAGS2.rs] = "sr"; + FLAGS2[FLAGS2["rs+"] = O_RDWR | O_SYNC] = "rs+"; + FLAGS2[FLAGS2["sr+"] = FLAGS2["rs+"]] = "sr+"; + FLAGS2[FLAGS2["w"] = O_WRONLY | O_CREAT | O_TRUNC] = "w"; + FLAGS2[FLAGS2["wx"] = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL] = "wx"; + FLAGS2[FLAGS2["xw"] = FLAGS2.wx] = "xw"; + FLAGS2[FLAGS2["w+"] = O_RDWR | O_CREAT | O_TRUNC] = "w+"; + FLAGS2[FLAGS2["wx+"] = O_RDWR | O_CREAT | O_TRUNC | O_EXCL] = "wx+"; + FLAGS2[FLAGS2["xw+"] = FLAGS2["wx+"]] = "xw+"; + FLAGS2[FLAGS2["a"] = O_WRONLY | O_APPEND | O_CREAT] = "a"; + FLAGS2[FLAGS2["ax"] = O_WRONLY | O_APPEND | O_CREAT | O_EXCL] = "ax"; + FLAGS2[FLAGS2["xa"] = FLAGS2.ax] = "xa"; + FLAGS2[FLAGS2["a+"] = O_RDWR | O_APPEND | O_CREAT] = "a+"; + FLAGS2[FLAGS2["ax+"] = O_RDWR | O_APPEND | O_CREAT | O_EXCL] = "ax+"; + FLAGS2[FLAGS2["xa+"] = FLAGS2["ax+"]] = "xa+"; + })(FLAGS || (constants$7.FLAGS = FLAGS = {})); + return constants$7; +} +var url$2 = {}; +var punycode$1 = { exports: {} }; +/*! https://mths.be/punycode v1.4.1 by @mathias */ +var punycode = punycode$1.exports; +var hasRequiredPunycode; +function requirePunycode() { + if (hasRequiredPunycode) return punycode$1.exports; + hasRequiredPunycode = 1; + (function(module, exports) { + (function(root) { + var freeExports = exports && !exports.nodeType && exports; + var freeModule = module && !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) { + root = freeGlobal; + } + var punycode2, maxInt = 2147483647, base2 = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, delimiter = "-", regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, errors2 = { + "overflow": "Overflow: input needs wider integers to process", + "not-basic": "Illegal input >= 0x80 (not a basic code point)", + "invalid-input": "Invalid input" + }, baseMinusTMin = base2 - tMin, floor2 = Math.floor, stringFromCharCode = String.fromCharCode, key2; + function error2(type2) { + throw new RangeError(errors2[type2]); + } + function map2(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + function mapDomain(string2, fn) { + var parts = string2.split("@"); + var result = ""; + if (parts.length > 1) { + result = parts[0] + "@"; + string2 = parts[1]; + } + string2 = string2.replace(regexSeparators, "."); + var labels = string2.split("."); + var encoded = map2(labels, fn).join("."); + return result + encoded; + } + function ucs2decode(string2) { + var output = [], counter = 0, length = string2.length, value, extra; + while (counter < length) { + value = string2.charCodeAt(counter++); + if (value >= 55296 && value <= 56319 && counter < length) { + extra = string2.charCodeAt(counter++); + if ((extra & 64512) == 56320) { + output.push(((value & 1023) << 10) + (extra & 1023) + 65536); + } else { + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + function ucs2encode(array) { + return map2(array, function(value) { + var output = ""; + if (value > 65535) { + value -= 65536; + output += stringFromCharCode(value >>> 10 & 1023 | 55296); + value = 56320 | value & 1023; + } + output += stringFromCharCode(value); + return output; + }).join(""); + } + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base2; + } + function digitToBasic(digit2, flag) { + return digit2 + 22 + 75 * (digit2 < 26) - ((flag != 0) << 5); + } + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor2(delta / damp) : delta >> 1; + delta += floor2(delta / numPoints); + for (; delta > baseMinusTMin * tMax >> 1; k += base2) { + delta = floor2(delta / baseMinusTMin); + } + return floor2(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + function decode(input) { + var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index2, oldi, w, k, digit2, t, baseMinusT; + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + for (j = 0; j < basic; ++j) { + if (input.charCodeAt(j) >= 128) { + error2("not-basic"); + } + output.push(input.charCodeAt(j)); + } + for (index2 = basic > 0 ? basic + 1 : 0; index2 < inputLength; ) { + for (oldi = i, w = 1, k = base2; ; k += base2) { + if (index2 >= inputLength) { + error2("invalid-input"); + } + digit2 = basicToDigit(input.charCodeAt(index2++)); + if (digit2 >= base2 || digit2 > floor2((maxInt - i) / w)) { + error2("overflow"); + } + i += digit2 * w; + t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (digit2 < t) { + break; + } + baseMinusT = base2 - t; + if (w > floor2(maxInt / baseMinusT)) { + error2("overflow"); + } + w *= baseMinusT; + } + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + if (floor2(i / out) > maxInt - n) { + error2("overflow"); + } + n += floor2(i / out); + i %= out; + output.splice(i++, 0, n); + } + return ucs2encode(output); + } + function encode(input) { + var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], inputLength, handledCPCountPlusOne, baseMinusT, qMinusT; + input = ucs2decode(input); + inputLength = input.length; + n = initialN; + delta = 0; + bias = initialBias; + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 128) { + output.push(stringFromCharCode(currentValue)); + } + } + handledCPCount = basicLength = output.length; + if (basicLength) { + output.push(delimiter); + } + while (handledCPCount < inputLength) { + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor2((maxInt - delta) / handledCPCountPlusOne)) { + error2("overflow"); + } + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < n && ++delta > maxInt) { + error2("overflow"); + } + if (currentValue == n) { + for (q = delta, k = base2; ; k += base2) { + t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base2 - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor2(qMinusT / baseMinusT); + } + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + ++delta; + ++n; + } + return output.join(""); + } + function toUnicode(input) { + return mapDomain(input, function(string2) { + return regexPunycode.test(string2) ? decode(string2.slice(4).toLowerCase()) : string2; + }); + } + function toASCII(input) { + return mapDomain(input, function(string2) { + return regexNonASCII.test(string2) ? "xn--" + encode(string2) : string2; + }); + } + punycode2 = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + "version": "1.4.1", + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + "ucs2": { + "decode": ucs2decode, + "encode": ucs2encode + }, + "decode": decode, + "encode": encode, + "toASCII": toASCII, + "toUnicode": toUnicode + }; + if (freeExports && freeModule) { + if (module.exports == freeExports) { + freeModule.exports = punycode2; + } else { + for (key2 in punycode2) { + punycode2.hasOwnProperty(key2) && (freeExports[key2] = punycode2[key2]); + } + } + } else { + root.punycode = punycode2; + } + })(punycode); + })(punycode$1, punycode$1.exports); + return punycode$1.exports; +} +const __viteBrowserExternal = {}; +const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: __viteBrowserExternal +}, Symbol.toStringTag, { value: "Module" })); +const require$$3 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1); +var objectInspect; +var hasRequiredObjectInspect; +function requireObjectInspect() { + if (hasRequiredObjectInspect) return objectInspect; + hasRequiredObjectInspect = 1; + var hasMap = typeof Map === "function" && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === "function" && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; + var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) { + return O.__proto__; + } : null); + function addNumericSeparator(num, str) { + if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === "number") { + var int2 = num < 0 ? -$floor(-num) : $floor(num); + if (int2 !== num) { + var intStr = String(int2); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); + } + } + return $replace.call(str, sepRegex, "$&_"); + } + var utilInspect = require$$3; + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + var quotes = { + __proto__: null, + "double": '"', + single: "'" + }; + var quoteREs = { + __proto__: null, + "double": /(["\\])/g, + single: /(['\\])/g + }; + objectInspect = function inspect_(obj, options2, depth, seen) { + var opts = options2 || {}; + if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, "customInspect") ? opts.customInspect : true; + if (typeof customInspect !== "boolean" && customInspect !== "symbol") { + throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); + } + if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + if (typeof obj === "boolean") { + return obj ? "true" : "false"; + } + if (typeof obj === "string") { + return inspectString(obj, opts); + } + if (typeof obj === "number") { + if (obj === 0) { + return Infinity / obj > 0 ? "0" : "-0"; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === "bigint") { + var bigIntStr = String(obj) + "n"; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; + if (typeof depth === "undefined") { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { + return isArray2(obj) ? "[Array]" : "[Object]"; + } + var indent = getIndent(opts, depth); + if (typeof seen === "undefined") { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return "[Circular]"; + } + function inspect(value, from2, noIndent) { + if (from2) { + seen = $arrSlice.call(seen); + seen.push(from2); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, "quoteStyle")) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === "function" && !isRegExp2(obj)) { + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : ""); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); + return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = "<" + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += " " + attrs[i].name + "=" + wrapQuotes(quote2(attrs[i].value), "double", opts); + } + s += ">"; + if (obj.childNodes && obj.childNodes.length) { + s += "..."; + } + s += ""; + return s; + } + if (isArray2(obj)) { + if (obj.length === 0) { + return "[]"; + } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return "[" + indentedJoin(xs, indent) + "]"; + } + return "[ " + $join.call(xs, ", ") + " ]"; + } + if (isError2(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { + return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; + } + if (parts.length === 0) { + return "[" + String(obj) + "]"; + } + return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; + } + if (typeof obj === "object" && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { + return obj.inspect(); + } + } + if (isMap2(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function(value, key2) { + mapParts.push(inspect(key2, obj, true) + " => " + inspect(value, obj)); + }); + } + return collectionOf("Map", mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function(value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf("Set", setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf("WeakMap"); + } + if (isWeakSet(obj)) { + return weakCollectionOf("WeakSet"); + } + if (isWeakRef(obj)) { + return weakCollectionOf("WeakRef"); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString2(obj)) { + return markBoxed(inspect(String(obj))); + } + if (typeof window !== "undefined" && obj === window) { + return "{ [object Window] }"; + } + if (typeof globalThis !== "undefined" && obj === globalThis || typeof commonjsGlobal !== "undefined" && obj === commonjsGlobal) { + return "{ [object globalThis] }"; + } + if (!isDate2(obj) && !isRegExp2(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject2 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? "" : "null prototype"; + var stringTag = !isPlainObject2 && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; + var constructorTag = isPlainObject2 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; + var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); + if (ys.length === 0) { + return tag + "{}"; + } + if (indent) { + return tag + "{" + indentedJoin(ys, indent) + "}"; + } + return tag + "{ " + $join.call(ys, ", ") + " }"; + } + return String(obj); + }; + function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; + } + function quote2(s) { + return $replace.call(String(s), /"/g, """); + } + function isArray2(obj) { + return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isDate2(obj) { + return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isRegExp2(obj) { + return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isError2(obj) { + return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isString2(obj) { + return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isNumber(obj) { + return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isBoolean(obj) { + return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === "object" && obj instanceof Symbol; + } + if (typeof obj === "symbol") { + return true; + } + if (!obj || typeof obj !== "object" || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) { + } + return false; + } + function isBigInt(obj) { + if (!obj || typeof obj !== "object" || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) { + } + return false; + } + var hasOwn2 = Object.prototype.hasOwnProperty || function(key2) { + return key2 in this; + }; + function has(obj, key2) { + return hasOwn2.call(obj, key2); + } + function toStr(obj) { + return objectToString.call(obj); + } + function nameOf(f) { + if (f.name) { + return f.name; + } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { + return m[1]; + } + return null; + } + function indexOf(xs, x) { + if (xs.indexOf) { + return xs.indexOf(x); + } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { + return i; + } + } + return -1; + } + function isMap2(x) { + if (!mapSize || !x || typeof x !== "object") { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; + } catch (e) { + } + return false; + } + function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== "object") { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; + } catch (e) { + } + return false; + } + function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== "object") { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) { + } + return false; + } + function isSet(x) { + if (!setSize || !x || typeof x !== "object") { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; + } catch (e) { + } + return false; + } + function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== "object") { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; + } catch (e) { + } + return false; + } + function isElement(x) { + if (!x || typeof x !== "object") { + return false; + } + if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === "string" && typeof x.getAttribute === "function"; + } + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || "single"]; + quoteRE.lastIndex = 0; + var s = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, "single", opts); + } + function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: "b", + 9: "t", + 10: "n", + 12: "f", + 13: "r" + }[n]; + if (x) { + return "\\" + x; + } + return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16)); + } + function markBoxed(str) { + return "Object(" + str + ")"; + } + function weakCollectionOf(type2) { + return type2 + " { ? }"; + } + function collectionOf(type2, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); + return type2 + " (" + size + ") {" + joinedEntries + "}"; + } + function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], "\n") >= 0) { + return false; + } + } + return true; + } + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === " ") { + baseIndent = " "; + } else if (typeof opts.indent === "number" && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), " "); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + function indentedJoin(xs, indent) { + if (xs.length === 0) { + return ""; + } + var lineJoiner = "\n" + indent.prev + indent.base; + return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; + } + function arrObjKeys(obj, inspect) { + var isArr = isArray2(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ""; + } + } + var syms = typeof gOPS === "function" ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap["$" + syms[k]] = syms[k]; + } + } + for (var key2 in obj) { + if (!has(obj, key2)) { + continue; + } + if (isArr && String(Number(key2)) === key2 && key2 < obj.length) { + continue; + } + if (hasShammedSymbols && symMap["$" + key2] instanceof Symbol) { + continue; + } else if ($test.call(/[^\w$]/, key2)) { + xs.push(inspect(key2, obj) + ": " + inspect(obj[key2], obj)); + } else { + xs.push(key2 + ": " + inspect(obj[key2], obj)); + } + } + if (typeof gOPS === "function") { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj)); + } + } + } + return xs; + } + return objectInspect; +} +var sideChannelList; +var hasRequiredSideChannelList; +function requireSideChannelList() { + if (hasRequiredSideChannelList) return sideChannelList; + hasRequiredSideChannelList = 1; + var inspect = /* @__PURE__ */ requireObjectInspect(); + var $TypeError = /* @__PURE__ */ requireType(); + var listGetNode = function(list, key2, isDelete) { + var prev = list; + var curr; + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key2) { + prev.next = curr.next; + if (!isDelete) { + curr.next = /** @type {NonNullable} */ + list.next; + list.next = curr; + } + return curr; + } + } + }; + var listGet = function(objects, key2) { + if (!objects) { + return void 0; + } + var node2 = listGetNode(objects, key2); + return node2 && node2.value; + }; + var listSet = function(objects, key2, value) { + var node2 = listGetNode(objects, key2); + if (node2) { + node2.value = value; + } else { + objects.next = /** @type {import('./list.d.ts').ListNode} */ + { + // eslint-disable-line no-param-reassign, no-extra-parens + key: key2, + next: objects.next, + value + }; + } + }; + var listHas = function(objects, key2) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key2); + }; + var listDelete = function(objects, key2) { + if (objects) { + return listGetNode(objects, key2, true); + } + }; + sideChannelList = function getSideChannelList() { + var $o; + var channel = { + assert: function(key2) { + if (!channel.has(key2)) { + throw new $TypeError("Side channel does not contain " + inspect(key2)); + } + }, + "delete": function(key2) { + var root = $o && $o.next; + var deletedNode = listDelete($o, key2); + if (deletedNode && root && root === deletedNode) { + $o = void 0; + } + return !!deletedNode; + }, + get: function(key2) { + return listGet($o, key2); + }, + has: function(key2) { + return listHas($o, key2); + }, + set: function(key2, value) { + if (!$o) { + $o = { + next: void 0 + }; + } + listSet( + /** @type {NonNullable} */ + $o, + key2, + value + ); + } + }; + return channel; + }; + return sideChannelList; +} +var sideChannelMap; +var hasRequiredSideChannelMap; +function requireSideChannelMap() { + if (hasRequiredSideChannelMap) return sideChannelMap; + hasRequiredSideChannelMap = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBound2 = /* @__PURE__ */ requireCallBound(); + var inspect = /* @__PURE__ */ requireObjectInspect(); + var $TypeError = /* @__PURE__ */ requireType(); + var $Map = GetIntrinsic("%Map%", true); + var $mapGet = callBound2("Map.prototype.get", true); + var $mapSet = callBound2("Map.prototype.set", true); + var $mapHas = callBound2("Map.prototype.has", true); + var $mapDelete = callBound2("Map.prototype.delete", true); + var $mapSize = callBound2("Map.prototype.size", true); + sideChannelMap = !!$Map && /** @type {Exclude} */ + function getSideChannelMap() { + var $m; + var channel = { + assert: function(key2) { + if (!channel.has(key2)) { + throw new $TypeError("Side channel does not contain " + inspect(key2)); + } + }, + "delete": function(key2) { + if ($m) { + var result = $mapDelete($m, key2); + if ($mapSize($m) === 0) { + $m = void 0; + } + return result; + } + return false; + }, + get: function(key2) { + if ($m) { + return $mapGet($m, key2); + } + }, + has: function(key2) { + if ($m) { + return $mapHas($m, key2); + } + return false; + }, + set: function(key2, value) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key2, value); + } + }; + return channel; + }; + return sideChannelMap; +} +var sideChannelWeakmap; +var hasRequiredSideChannelWeakmap; +function requireSideChannelWeakmap() { + if (hasRequiredSideChannelWeakmap) return sideChannelWeakmap; + hasRequiredSideChannelWeakmap = 1; + var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic(); + var callBound2 = /* @__PURE__ */ requireCallBound(); + var inspect = /* @__PURE__ */ requireObjectInspect(); + var getSideChannelMap = requireSideChannelMap(); + var $TypeError = /* @__PURE__ */ requireType(); + var $WeakMap = GetIntrinsic("%WeakMap%", true); + var $weakMapGet = callBound2("WeakMap.prototype.get", true); + var $weakMapSet = callBound2("WeakMap.prototype.set", true); + var $weakMapHas = callBound2("WeakMap.prototype.has", true); + var $weakMapDelete = callBound2("WeakMap.prototype.delete", true); + sideChannelWeakmap = $WeakMap ? ( + /** @type {Exclude} */ + function getSideChannelWeakMap() { + var $wm; + var $m; + var channel = { + assert: function(key2) { + if (!channel.has(key2)) { + throw new $TypeError("Side channel does not contain " + inspect(key2)); + } + }, + "delete": function(key2) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if ($wm) { + return $weakMapDelete($wm, key2); + } + } else if (getSideChannelMap) { + if ($m) { + return $m["delete"](key2); + } + } + return false; + }, + get: function(key2) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if ($wm) { + return $weakMapGet($wm, key2); + } + } + return $m && $m.get(key2); + }, + has: function(key2) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if ($wm) { + return $weakMapHas($wm, key2); + } + } + return !!$m && $m.has(key2); + }, + set: function(key2, value) { + if ($WeakMap && key2 && (typeof key2 === "object" || typeof key2 === "function")) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key2, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + $m.set(key2, value); + } + } + }; + return channel; + } + ) : getSideChannelMap; + return sideChannelWeakmap; +} +var sideChannel; +var hasRequiredSideChannel; +function requireSideChannel() { + if (hasRequiredSideChannel) return sideChannel; + hasRequiredSideChannel = 1; + var $TypeError = /* @__PURE__ */ requireType(); + var inspect = /* @__PURE__ */ requireObjectInspect(); + var getSideChannelList = requireSideChannelList(); + var getSideChannelMap = requireSideChannelMap(); + var getSideChannelWeakMap = requireSideChannelWeakmap(); + var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + sideChannel = function getSideChannel() { + var $channelData; + var channel = { + assert: function(key2) { + if (!channel.has(key2)) { + throw new $TypeError("Side channel does not contain " + inspect(key2)); + } + }, + "delete": function(key2) { + return !!$channelData && $channelData["delete"](key2); + }, + get: function(key2) { + return $channelData && $channelData.get(key2); + }, + has: function(key2) { + return !!$channelData && $channelData.has(key2); + }, + set: function(key2, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + $channelData.set(key2, value); + } + }; + return channel; + }; + return sideChannel; +} +var formats; +var hasRequiredFormats; +function requireFormats() { + if (hasRequiredFormats) return formats; + hasRequiredFormats = 1; + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + var Format = { + RFC1738: "RFC1738", + RFC3986: "RFC3986" + }; + formats = { + "default": Format.RFC3986, + formatters: { + RFC1738: function(value) { + return replace.call(value, percentTwenties, "+"); + }, + RFC3986: function(value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + return formats; +} +var utils$5; +var hasRequiredUtils$5; +function requireUtils$5() { + if (hasRequiredUtils$5) return utils$5; + hasRequiredUtils$5 = 1; + var formats2 = requireFormats(); + var has = Object.prototype.hasOwnProperty; + var isArray2 = Array.isArray; + var hexTable = function() { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; + }(); + var compactQueue = function compactQueue2(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + if (isArray2(obj)) { + var compacted = []; + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== "undefined") { + compacted.push(obj[j]); + } + } + item.obj[item.prop] = compacted; + } + } + }; + var arrayToObject = function arrayToObject2(source2, options2) { + var obj = options2 && options2.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + for (var i = 0; i < source2.length; ++i) { + if (typeof source2[i] !== "undefined") { + obj[i] = source2[i]; + } + } + return obj; + }; + var merge2 = function merge3(target, source2, options2) { + if (!source2) { + return target; + } + if (typeof source2 !== "object") { + if (isArray2(target)) { + target.push(source2); + } else if (target && typeof target === "object") { + if (options2 && (options2.plainObjects || options2.allowPrototypes) || !has.call(Object.prototype, source2)) { + target[source2] = true; + } + } else { + return [target, source2]; + } + return target; + } + if (!target || typeof target !== "object") { + return [target].concat(source2); + } + var mergeTarget = target; + if (isArray2(target) && !isArray2(source2)) { + mergeTarget = arrayToObject(target, options2); + } + if (isArray2(target) && isArray2(source2)) { + source2.forEach(function(item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { + target[i] = merge3(targetItem, item, options2); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + return Object.keys(source2).reduce(function(acc, key2) { + var value = source2[key2]; + if (has.call(acc, key2)) { + acc[key2] = merge3(acc[key2], value, options2); + } else { + acc[key2] = value; + } + return acc; + }, mergeTarget); + }; + var assign = function assignSingleSource(target, source2) { + return Object.keys(source2).reduce(function(acc, key2) { + acc[key2] = source2[key2]; + return acc; + }, target); + }; + var decode = function(str, decoder2, charset) { + var strWithoutPlus = str.replace(/\+/g, " "); + if (charset === "iso-8859-1") { + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } + }; + var encode = function encode2(str, defaultEncoder, charset, kind, format) { + if (str.length === 0) { + return str; + } + var string2 = str; + if (typeof str === "symbol") { + string2 = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string2 = String(str); + } + if (charset === "iso-8859-1") { + return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + var out = ""; + for (var i = 0; i < string2.length; ++i) { + var c = string2.charCodeAt(i); + if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === formats2.RFC1738 && (c === 40 || c === 41)) { + out += string2.charAt(i); + continue; + } + if (c < 128) { + out = out + hexTable[c]; + continue; + } + if (c < 2048) { + out = out + (hexTable[192 | c >> 6] + hexTable[128 | c & 63]); + continue; + } + if (c < 55296 || c >= 57344) { + out = out + (hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]); + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | string2.charCodeAt(i) & 1023); + out += hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63]; + } + return out; + }; + var compact = function compact2(value) { + var queue = [{ obj: { o: value }, prop: "o" }]; + var refs = []; + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key2 = keys[j]; + var val = obj[key2]; + if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj, prop: key2 }); + refs.push(val); + } + } + } + compactQueue(queue); + return value; + }; + var isRegExp2 = function isRegExp3(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; + }; + var isBuffer = function isBuffer2(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + }; + var combine = function combine2(a, b) { + return [].concat(a, b); + }; + var maybeMap = function maybeMap2(val, fn) { + if (isArray2(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); + }; + utils$5 = { + arrayToObject, + assign, + combine, + compact, + decode, + encode, + isBuffer, + isRegExp: isRegExp2, + maybeMap, + merge: merge2 + }; + return utils$5; +} +var stringify_1; +var hasRequiredStringify; +function requireStringify() { + if (hasRequiredStringify) return stringify_1; + hasRequiredStringify = 1; + var getSideChannel = requireSideChannel(); + var utils2 = requireUtils$5(); + var formats2 = requireFormats(); + var has = Object.prototype.hasOwnProperty; + var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + "[]"; + }, + comma: "comma", + indices: function indices(prefix, key2) { + return prefix + "[" + key2 + "]"; + }, + repeat: function repeat(prefix) { + return prefix; + } + }; + var isArray2 = Array.isArray; + var push = Array.prototype.push; + var pushToArray = function(arr, valueOrArray) { + push.apply(arr, isArray2(valueOrArray) ? valueOrArray : [valueOrArray]); + }; + var toISO = Date.prototype.toISOString; + var defaultFormat = formats2["default"]; + var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encoder: utils2.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats2.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false + }; + var isNonNullishPrimitive = function isNonNullishPrimitive2(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; + }; + var sentinel = {}; + var stringify2 = function stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder2, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel2) { + var obj = object; + var tmpSc = sideChannel2; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + findFlag = true; + } + } + if (typeof tmpSc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === "comma" && isArray2(obj)) { + obj = utils2.maybeMap(obj, function(value2) { + if (value2 instanceof Date) { + return serializeDate(value2); + } + return value2; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder2 && !encodeValuesOnly ? encoder2(prefix, defaults.encoder, charset, "key", format) : prefix; + } + obj = ""; + } + if (isNonNullishPrimitive(obj) || utils2.isBuffer(obj)) { + if (encoder2) { + var keyValue = encodeValuesOnly ? prefix : encoder2(prefix, defaults.encoder, charset, "key", format); + return [formatter(keyValue) + "=" + formatter(encoder2(obj, defaults.encoder, charset, "value", format))]; + } + return [formatter(prefix) + "=" + formatter(String(obj))]; + } + var values = []; + if (typeof obj === "undefined") { + return values; + } + var objKeys; + if (generateArrayPrefix === "comma" && isArray2(obj)) { + if (encodeValuesOnly && encoder2) { + obj = utils2.maybeMap(obj, encoder2); + } + objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray2(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + var adjustedPrefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? prefix + "[]" : prefix; + for (var j = 0; j < objKeys.length; ++j) { + var key2 = objKeys[j]; + var value = typeof key2 === "object" && typeof key2.value !== "undefined" ? key2.value : obj[key2]; + if (skipNulls && value === null) { + continue; + } + var keyPrefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, key2) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + key2 : "[" + key2 + "]"); + sideChannel2.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel2); + pushToArray(values, stringify3( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder2, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; + }; + var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { + if (!opts) { + return defaults; + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var format = formats2["default"]; + if (typeof opts.format !== "undefined") { + if (!has.call(formats2.formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + var formatter = formats2.formatters[format]; + var filter = defaults.filter; + if (typeof opts.filter === "function" || isArray2(opts.filter)) { + filter = opts.filter; + } + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + stringify_1 = function(object, opts) { + var obj = object; + var options2 = normalizeStringifyOptions(opts); + var objKeys; + var filter; + if (typeof options2.filter === "function") { + filter = options2.filter; + obj = filter("", obj); + } else if (isArray2(options2.filter)) { + filter = options2.filter; + objKeys = filter; + } + var keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && "indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = "indices"; + } + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && "commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + var commaRoundTrip = generateArrayPrefix === "comma" && opts && opts.commaRoundTrip; + if (!objKeys) { + objKeys = Object.keys(obj); + } + if (options2.sort) { + objKeys.sort(options2.sort); + } + var sideChannel2 = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key2 = objKeys[i]; + if (options2.skipNulls && obj[key2] === null) { + continue; + } + pushToArray(keys, stringify2( + obj[key2], + key2, + generateArrayPrefix, + commaRoundTrip, + options2.strictNullHandling, + options2.skipNulls, + options2.encode ? options2.encoder : null, + options2.filter, + options2.sort, + options2.allowDots, + options2.serializeDate, + options2.format, + options2.formatter, + options2.encodeValuesOnly, + options2.charset, + sideChannel2 + )); + } + var joined = keys.join(options2.delimiter); + var prefix = options2.addQueryPrefix === true ? "?" : ""; + if (options2.charsetSentinel) { + if (options2.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; + }; + return stringify_1; +} +var parse$3; +var hasRequiredParse; +function requireParse() { + if (hasRequiredParse) return parse$3; + hasRequiredParse = 1; + var utils2 = requireUtils$5(); + var has = Object.prototype.hasOwnProperty; + var isArray2 = Array.isArray; + var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: "utf-8", + charsetSentinel: false, + comma: false, + decoder: utils2.decode, + delimiter: "&", + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1e3, + parseArrays: true, + plainObjects: false, + strictNullHandling: false + }; + var interpretNumericEntities = function(str) { + return str.replace(/&#(\d+);/g, function($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); + }; + var parseArrayValue = function(val, options2) { + if (val && typeof val === "string" && options2.comma && val.indexOf(",") > -1) { + return val.split(","); + } + return val; + }; + var isoSentinel = "utf8=%26%2310003%3B"; + var charsetSentinel = "utf8=%E2%9C%93"; + var parseValues = function parseQueryStringValues(str, options2) { + var obj = { __proto__: null }; + var cleanStr = options2.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; + var limit = options2.parameterLimit === Infinity ? void 0 : options2.parameterLimit; + var parts = cleanStr.split(options2.delimiter, limit); + var skipIndex = -1; + var i; + var charset = options2.charset; + if (options2.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf("utf8=") === 0) { + if (parts[i] === charsetSentinel) { + charset = "utf-8"; + } else if (parts[i] === isoSentinel) { + charset = "iso-8859-1"; + } + skipIndex = i; + i = parts.length; + } + } + } + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + var bracketEqualsPos = part.indexOf("]="); + var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; + var key2, val; + if (pos === -1) { + key2 = options2.decoder(part, defaults.decoder, charset, "key"); + val = options2.strictNullHandling ? null : ""; + } else { + key2 = options2.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); + val = utils2.maybeMap( + parseArrayValue(part.slice(pos + 1), options2), + function(encodedVal) { + return options2.decoder(encodedVal, defaults.decoder, charset, "value"); + } + ); + } + if (val && options2.interpretNumericEntities && charset === "iso-8859-1") { + val = interpretNumericEntities(val); + } + if (part.indexOf("[]=") > -1) { + val = isArray2(val) ? [val] : val; + } + if (has.call(obj, key2)) { + obj[key2] = utils2.combine(obj[key2], val); + } else { + obj[key2] = val; + } + } + return obj; + }; + var parseObject = function(chain, val, options2, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options2); + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + if (root === "[]" && options2.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options2.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; + var index2 = parseInt(cleanRoot, 10); + if (!options2.parseArrays && cleanRoot === "") { + obj = { 0: leaf }; + } else if (!isNaN(index2) && root !== cleanRoot && String(index2) === cleanRoot && index2 >= 0 && (options2.parseArrays && index2 <= options2.arrayLimit)) { + obj = []; + obj[index2] = leaf; + } else if (cleanRoot !== "__proto__") { + obj[cleanRoot] = leaf; + } + } + leaf = obj; + } + return leaf; + }; + var parseKeys = function parseQueryStringKeys(givenKey, val, options2, valuesParsed) { + if (!givenKey) { + return; + } + var key2 = options2.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + var segment = options2.depth > 0 && brackets.exec(key2); + var parent = segment ? key2.slice(0, segment.index) : key2; + var keys = []; + if (parent) { + if (!options2.plainObjects && has.call(Object.prototype, parent)) { + if (!options2.allowPrototypes) { + return; + } + } + keys.push(parent); + } + var i = 0; + while (options2.depth > 0 && (segment = child.exec(key2)) !== null && i < options2.depth) { + i += 1; + if (!options2.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options2.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + if (segment) { + keys.push("[" + key2.slice(segment.index) + "]"); + } + return parseObject(keys, val, options2, valuesParsed); + }; + var normalizeParseOptions = function normalizeParseOptions2(opts) { + if (!opts) { + return defaults; + } + if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") { + throw new TypeError("Decoder has to be a function."); + } + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; + return { + allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === "string" || utils2.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + parse$3 = function(str, opts) { + var options2 = normalizeParseOptions(opts); + if (str === "" || str === null || typeof str === "undefined") { + return options2.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + } + var tempObj = typeof str === "string" ? parseValues(str, options2) : str; + var obj = options2.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key2 = keys[i]; + var newObj = parseKeys(key2, tempObj[key2], options2, typeof str === "string"); + obj = utils2.merge(obj, newObj, options2); + } + if (options2.allowSparse === true) { + return obj; + } + return utils2.compact(obj); + }; + return parse$3; +} +var lib$1; +var hasRequiredLib$2; +function requireLib$2() { + if (hasRequiredLib$2) return lib$1; + hasRequiredLib$2 = 1; + var stringify2 = requireStringify(); + var parse4 = requireParse(); + var formats2 = requireFormats(); + lib$1 = { + formats: formats2, + parse: parse4, + stringify: stringify2 + }; + return lib$1; +} +var hasRequiredUrl; +function requireUrl() { + if (hasRequiredUrl) return url$2; + hasRequiredUrl = 1; + var punycode2 = requirePunycode(); + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, delims = [ + "<", + ">", + '"', + "`", + " ", + "\r", + "\n", + " " + ], unwise = [ + "{", + "}", + "|", + "\\", + "^", + "`" + ].concat(delims), autoEscape = ["'"].concat(unwise), nonHostChars = [ + "%", + "/", + "?", + ";", + "#" + ].concat(autoEscape), hostEndingChars = [ + "/", + "?", + "#" + ], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, unsafeProtocol = { + javascript: true, + "javascript:": true + }, hostlessProtocol = { + javascript: true, + "javascript:": true + }, slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + "http:": true, + "https:": true, + "ftp:": true, + "gopher:": true, + "file:": true + }, querystring = requireLib$2(); + function urlParse(url2, parseQueryString, slashesDenoteHost) { + if (url2 && typeof url2 === "object" && url2 instanceof Url) { + return url2; + } + var u = new Url(); + u.parse(url2, parseQueryString, slashesDenoteHost); + return u; + } + Url.prototype.parse = function(url2, parseQueryString, slashesDenoteHost) { + if (typeof url2 !== "string") { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url2); + } + var queryIndex = url2.indexOf("?"), splitter = queryIndex !== -1 && queryIndex < url2.indexOf("#") ? "?" : "#", uSplit = url2.split(splitter), slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, "/"); + url2 = uSplit.join(splitter); + var rest = url2; + rest = rest.trim(); + if (!slashesDenoteHost && url2.split("#").length === 1) { + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ""; + this.query = {}; + } + return this; + } + } + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { + var slashes = rest.substr(0, 2) === "//"; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) { + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; + } + } + var auth, atSign; + if (hostEnd === -1) { + atSign = rest.lastIndexOf("@"); + } else { + atSign = rest.lastIndexOf("@", hostEnd); + } + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; + } + } + if (hostEnd === -1) { + hostEnd = rest.length; + } + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + this.parseHost(); + this.hostname = this.hostname || ""; + var ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]"; + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { + continue; + } + if (!part.match(hostnamePartPattern)) { + var newpart = ""; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + newpart += "x"; + } else { + newpart += part[j]; + } + } + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = "/" + notHost.join(".") + rest; + } + this.hostname = validParts.join("."); + break; + } + } + } + } + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ""; + } else { + this.hostname = this.hostname.toLowerCase(); + } + if (!ipv6Hostname) { + this.hostname = punycode2.toASCII(this.hostname); + } + var p = this.port ? ":" + this.port : ""; + var h = this.hostname || ""; + this.host = h + p; + this.href += this.host; + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== "/") { + rest = "/" + rest; + } + } + } + if (!unsafeProtocol[lowerProto]) { + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) { + continue; + } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + var hash2 = rest.indexOf("#"); + if (hash2 !== -1) { + this.hash = rest.substr(hash2); + rest = rest.slice(0, hash2); + } + var qm = rest.indexOf("?"); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + this.search = ""; + this.query = {}; + } + if (rest) { + this.pathname = rest; + } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = "/"; + } + if (this.pathname || this.search) { + var p = this.pathname || ""; + var s = this.search || ""; + this.path = p + s; + } + this.href = this.format(); + return this; + }; + function urlFormat(obj) { + if (typeof obj === "string") { + obj = urlParse(obj); + } + if (!(obj instanceof Url)) { + return Url.prototype.format.call(obj); + } + return obj.format(); + } + Url.prototype.format = function() { + var auth = this.auth || ""; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ":"); + auth += "@"; + } + var protocol = this.protocol || "", pathname = this.pathname || "", hash2 = this.hash || "", host = false, query = ""; + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(":") === -1 ? this.hostname : "[" + this.hostname + "]"); + if (this.port) { + host += ":" + this.port; + } + } + if (this.query && typeof this.query === "object" && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: "repeat", + addQueryPrefix: false + }); + } + var search = this.search || query && "?" + query || ""; + if (protocol && protocol.substr(-1) !== ":") { + protocol += ":"; + } + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { + host = "//" + (host || ""); + if (pathname && pathname.charAt(0) !== "/") { + pathname = "/" + pathname; + } + } else if (!host) { + host = ""; + } + if (hash2 && hash2.charAt(0) !== "#") { + hash2 = "#" + hash2; + } + if (search && search.charAt(0) !== "?") { + search = "?" + search; + } + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace("#", "%23"); + return protocol + host + pathname + search + hash2; + }; + function urlResolve(source2, relative) { + return urlParse(source2, false, true).resolve(relative); + } + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + function urlResolveObject(source2, relative) { + if (!source2) { + return relative; + } + return urlParse(source2, false, true).resolveObject(relative); + } + Url.prototype.resolveObject = function(relative) { + if (typeof relative === "string") { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + result.hash = relative.hash; + if (relative.href === "") { + result.href = result.format(); + return result; + } + if (relative.slashes && !relative.protocol) { + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== "protocol") { + result[rkey] = relative[rkey]; + } + } + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = "/"; + result.path = result.pathname; + } + result.href = result.format(); + return result; + } + if (relative.protocol && relative.protocol !== result.protocol) { + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || "").split("/"); + while (relPath.length && !(relative.host = relPath.shift())) { + } + if (!relative.host) { + relative.host = ""; + } + if (!relative.hostname) { + relative.hostname = ""; + } + if (relPath[0] !== "") { + relPath.unshift(""); + } + if (relPath.length < 2) { + relPath.unshift(""); + } + result.pathname = relPath.join("/"); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ""; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + if (result.pathname || result.search) { + var p = result.pathname || ""; + var s = result.search || ""; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + var isSourceAbs = result.pathname && result.pathname.charAt(0) === "/", isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === "/", mustEndAbs = isRelAbs || isSourceAbs || result.host && relative.pathname, removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split("/") || [], relPath = relative.pathname && relative.pathname.split("/") || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; + if (psychotic) { + result.hostname = ""; + result.port = null; + if (result.host) { + if (srcPath[0] === "") { + srcPath[0] = result.host; + } else { + srcPath.unshift(result.host); + } + } + result.host = ""; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === "") { + relPath[0] = relative.host; + } else { + relPath.unshift(relative.host); + } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); + } + if (isRelAbs) { + result.host = relative.host || relative.host === "" ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === "" ? relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + } else if (relPath.length) { + if (!srcPath) { + srcPath = []; + } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search != null) { + if (psychotic) { + result.host = srcPath.shift(); + result.hostname = result.host; + var authInHost = result.host && result.host.indexOf("@") > 0 ? result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + result.search = relative.search; + result.query = relative.query; + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : "") + (result.search ? result.search : ""); + } + result.href = result.format(); + return result; + } + if (!srcPath.length) { + result.pathname = null; + if (result.search) { + result.path = "/" + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === "." || last === "..") || last === ""; + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === ".") { + srcPath.splice(i, 1); + } else if (last === "..") { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift(".."); + } + } + if (mustEndAbs && srcPath[0] !== "" && (!srcPath[0] || srcPath[0].charAt(0) !== "/")) { + srcPath.unshift(""); + } + if (hasTrailingSlash && srcPath.join("/").substr(-1) !== "/") { + srcPath.push(""); + } + var isAbsolute = srcPath[0] === "" || srcPath[0] && srcPath[0].charAt(0) === "/"; + if (psychotic) { + result.hostname = isAbsolute ? "" : srcPath.length ? srcPath.shift() : ""; + result.host = result.hostname; + var authInHost = result.host && result.host.indexOf("@") > 0 ? result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + mustEndAbs = mustEndAbs || result.host && srcPath.length; + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } + if (srcPath.length > 0) { + result.pathname = srcPath.join("/"); + } else { + result.pathname = null; + result.path = null; + } + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : "") + (result.search ? result.search : ""); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ":") { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { + this.hostname = host; + } + }; + url$2.parse = urlParse; + url$2.resolve = urlResolve; + url$2.resolveObject = urlResolveObject; + url$2.format = urlFormat; + url$2.Url = Url; + return url$2; +} +var urlExports = requireUrl(); +const _url = /* @__PURE__ */ getDefaultExportFromCjs(urlExports); +function pathToFileURL(s) { + return s; +} +const url = { ..._url, pathToFileURL }; +const url$1 = /* @__PURE__ */ _mergeNamespaces({ + __proto__: null, + default: url, + pathToFileURL +}, [urlExports]); +const require$$1$5 = /* @__PURE__ */ getAugmentedNamespace(url$1); +var hasRequiredUtil$2; +function requireUtil$2() { + if (hasRequiredUtil$2) return util$3; + hasRequiredUtil$2 = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.unixify = exports.bufferToEncoding = exports.getWriteSyncArgs = exports.getWriteArgs = exports.bufToUint8 = exports.dataToBuffer = exports.validateFd = exports.isFd = exports.flagsToNumber = exports.genRndStr6 = exports.createError = exports.pathToFilename = exports.nullCheck = exports.modeToNumber = exports.validateCallback = exports.promisify = exports.isWin = void 0; + const constants_1 = requireConstants$6(); + const errors2 = requireErrors$1(); + const buffer_1 = requireBuffer$1(); + const encoding_1 = requireEncoding(); + const buffer_2 = requireBuffer$1(); + const queueMicrotask_1 = requireQueueMicrotask(); + exports.isWin = process.platform === "win32"; + function promisify2(fs2, fn, getResult = (input) => input) { + return (...args) => new Promise((resolve, reject) => { + fs2[fn].bind(fs2)(...args, (error2, result) => { + if (error2) + return reject(error2); + return resolve(getResult(result)); + }); + }); + } + exports.promisify = promisify2; + function validateCallback(callback) { + if (typeof callback !== "function") + throw TypeError(constants_1.ERRSTR.CB); + return callback; + } + exports.validateCallback = validateCallback; + function _modeToNumber(mode, def) { + if (typeof mode === "number") + return mode; + if (typeof mode === "string") + return parseInt(mode, 8); + if (def) + return modeToNumber(def); + return void 0; + } + function modeToNumber(mode, def) { + const result = _modeToNumber(mode, def); + if (typeof result !== "number" || isNaN(result)) + throw new TypeError(constants_1.ERRSTR.MODE_INT); + return result; + } + exports.modeToNumber = modeToNumber; + function nullCheck(path2, callback) { + if (("" + path2).indexOf("\0") !== -1) { + const er = new Error("Path must be a string without null bytes"); + er.code = "ENOENT"; + if (typeof callback !== "function") + throw er; + (0, queueMicrotask_1.default)(() => { + callback(er); + }); + return false; + } + return true; + } + exports.nullCheck = nullCheck; + function getPathFromURLPosix(url2) { + if (url2.hostname !== "") { + throw new errors2.TypeError("ERR_INVALID_FILE_URL_HOST", process.platform); + } + const pathname = url2.pathname; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === "%") { + const third = pathname.codePointAt(n + 2) | 32; + if (pathname[n + 1] === "2" && third === 102) { + throw new errors2.TypeError("ERR_INVALID_FILE_URL_PATH", "must not include encoded / characters"); + } + } + } + return decodeURIComponent(pathname); + } + function pathToFilename(path2) { + if (typeof path2 !== "string" && !buffer_1.Buffer.isBuffer(path2)) { + try { + if (!(path2 instanceof require$$1$5.URL)) + throw new TypeError(constants_1.ERRSTR.PATH_STR); + } catch (err) { + throw new TypeError(constants_1.ERRSTR.PATH_STR); + } + path2 = getPathFromURLPosix(path2); + } + const pathString = String(path2); + nullCheck(pathString); + return pathString; + } + exports.pathToFilename = pathToFilename; + const ENOENT = "ENOENT"; + const EBADF = "EBADF"; + const EINVAL = "EINVAL"; + const EPERM = "EPERM"; + const EPROTO = "EPROTO"; + const EEXIST = "EEXIST"; + const ENOTDIR = "ENOTDIR"; + const EMFILE = "EMFILE"; + const EACCES = "EACCES"; + const EISDIR = "EISDIR"; + const ENOTEMPTY = "ENOTEMPTY"; + const ENOSYS = "ENOSYS"; + const ERR_FS_EISDIR = "ERR_FS_EISDIR"; + const ERR_OUT_OF_RANGE = "ERR_OUT_OF_RANGE"; + function formatError(errorCode, func = "", path2 = "", path22 = "") { + let pathFormatted = ""; + if (path2) + pathFormatted = ` '${path2}'`; + if (path22) + pathFormatted += ` -> '${path22}'`; + switch (errorCode) { + case ENOENT: + return `ENOENT: no such file or directory, ${func}${pathFormatted}`; + case EBADF: + return `EBADF: bad file descriptor, ${func}${pathFormatted}`; + case EINVAL: + return `EINVAL: invalid argument, ${func}${pathFormatted}`; + case EPERM: + return `EPERM: operation not permitted, ${func}${pathFormatted}`; + case EPROTO: + return `EPROTO: protocol error, ${func}${pathFormatted}`; + case EEXIST: + return `EEXIST: file already exists, ${func}${pathFormatted}`; + case ENOTDIR: + return `ENOTDIR: not a directory, ${func}${pathFormatted}`; + case EISDIR: + return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`; + case EACCES: + return `EACCES: permission denied, ${func}${pathFormatted}`; + case ENOTEMPTY: + return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`; + case EMFILE: + return `EMFILE: too many open files, ${func}${pathFormatted}`; + case ENOSYS: + return `ENOSYS: function not implemented, ${func}${pathFormatted}`; + case ERR_FS_EISDIR: + return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path2}`; + case ERR_OUT_OF_RANGE: + return `[ERR_OUT_OF_RANGE]: value out of range, ${func}${pathFormatted}`; + default: + return `${errorCode}: error occurred, ${func}${pathFormatted}`; + } + } + function createError(errorCode, func = "", path2 = "", path22 = "", Constructor = Error) { + const error2 = new Constructor(formatError(errorCode, func, path2, path22)); + error2.code = errorCode; + if (path2) { + error2.path = path2; + } + return error2; + } + exports.createError = createError; + function genRndStr6() { + const str = (Math.random() + 1).toString(36).substring(2, 8); + if (str.length === 6) + return str; + else + return genRndStr6(); + } + exports.genRndStr6 = genRndStr6; + function flagsToNumber(flags) { + if (typeof flags === "number") + return flags; + if (typeof flags === "string") { + const flagsNum = constants_1.FLAGS[flags]; + if (typeof flagsNum !== "undefined") + return flagsNum; + } + throw new errors2.TypeError("ERR_INVALID_OPT_VALUE", "flags", flags); + } + exports.flagsToNumber = flagsToNumber; + function isFd(path2) { + return path2 >>> 0 === path2; + } + exports.isFd = isFd; + function validateFd(fd) { + if (!isFd(fd)) + throw TypeError(constants_1.ERRSTR.FD); + } + exports.validateFd = validateFd; + function dataToBuffer(data2, encoding2 = encoding_1.ENCODING_UTF8) { + if (buffer_1.Buffer.isBuffer(data2)) + return data2; + else if (data2 instanceof Uint8Array) + return (0, buffer_2.bufferFrom)(data2); + else + return (0, buffer_2.bufferFrom)(String(data2), encoding2); + } + exports.dataToBuffer = dataToBuffer; + const bufToUint8 = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + exports.bufToUint8 = bufToUint8; + const getWriteArgs = (fd, a, b, c, d, e) => { + validateFd(fd); + let offset2 = 0; + let length; + let position = null; + let encoding2; + let callback; + const tipa = typeof a; + const tipb = typeof b; + const tipc = typeof c; + const tipd = typeof d; + if (tipa !== "string") { + if (tipb === "function") { + callback = b; + } else if (tipc === "function") { + offset2 = b | 0; + callback = c; + } else if (tipd === "function") { + offset2 = b | 0; + length = c; + callback = d; + } else { + offset2 = b | 0; + length = c; + position = d; + callback = e; + } + } else { + if (tipb === "function") { + callback = b; + } else if (tipc === "function") { + position = b; + callback = c; + } else if (tipd === "function") { + position = b; + encoding2 = c; + callback = d; + } + } + const buf = dataToBuffer(a, encoding2); + if (tipa !== "string") { + if (typeof length === "undefined") + length = buf.length; + } else { + offset2 = 0; + length = buf.length; + } + const cb = validateCallback(callback); + return [fd, tipa === "string", buf, offset2, length, position, cb]; + }; + exports.getWriteArgs = getWriteArgs; + const getWriteSyncArgs = (fd, a, b, c, d) => { + validateFd(fd); + let encoding2; + let offset2; + let length; + let position; + const isBuffer = typeof a !== "string"; + if (isBuffer) { + offset2 = (b || 0) | 0; + length = c; + position = d; + } else { + position = b; + encoding2 = c; + } + const buf = dataToBuffer(a, encoding2); + if (isBuffer) { + if (typeof length === "undefined") { + length = buf.length; + } + } else { + offset2 = 0; + length = buf.length; + } + return [fd, buf, offset2 || 0, length, position]; + }; + exports.getWriteSyncArgs = getWriteSyncArgs; + function bufferToEncoding(buffer2, encoding2) { + if (!encoding2 || encoding2 === "buffer") + return buffer2; + else + return buffer2.toString(encoding2); + } + exports.bufferToEncoding = bufferToEncoding; + const isSeparator = (str, i) => { + let char = str[i]; + return i > 0 && (char === "/" || exports.isWin && char === "\\"); + }; + const removeTrailingSeparator = (str) => { + let i = str.length - 1; + if (i < 2) + return str; + while (isSeparator(str, i)) + i--; + return str.substr(0, i + 1); + }; + const normalizePath = (str, stripTrailing) => { + if (typeof str !== "string") + throw new TypeError("expected a string"); + str = str.replace(/[\\\/]+/g, "/"); + if (stripTrailing !== false) + str = removeTrailingSeparator(str); + return str; + }; + const unixify = (filepath, stripTrailing = true) => { + if (exports.isWin) { + filepath = normalizePath(filepath, stripTrailing); + return filepath.replace(/^([a-zA-Z]+:|\.\/)/, ""); + } + return filepath; + }; + exports.unixify = unixify; + })(util$3); + return util$3; +} +var hasRequiredFileHandle; +function requireFileHandle() { + if (hasRequiredFileHandle) return FileHandle; + hasRequiredFileHandle = 1; + Object.defineProperty(FileHandle, "__esModule", { value: true }); + FileHandle.FileHandle = void 0; + const util_1 = requireUtil$2(); + let FileHandle$1 = class FileHandle { + constructor(fs2, fd) { + this.fs = fs2; + this.fd = fd; + } + appendFile(data2, options2) { + return (0, util_1.promisify)(this.fs, "appendFile")(this.fd, data2, options2); + } + chmod(mode) { + return (0, util_1.promisify)(this.fs, "fchmod")(this.fd, mode); + } + chown(uid, gid) { + return (0, util_1.promisify)(this.fs, "fchown")(this.fd, uid, gid); + } + close() { + return (0, util_1.promisify)(this.fs, "close")(this.fd); + } + datasync() { + return (0, util_1.promisify)(this.fs, "fdatasync")(this.fd); + } + read(buffer2, offset2, length, position) { + return (0, util_1.promisify)(this.fs, "read", (bytesRead) => ({ bytesRead, buffer: buffer2 }))(this.fd, buffer2, offset2, length, position); + } + readv(buffers, position) { + return (0, util_1.promisify)(this.fs, "readv", (bytesRead) => ({ bytesRead, buffers }))(this.fd, buffers, position); + } + readFile(options2) { + return (0, util_1.promisify)(this.fs, "readFile")(this.fd, options2); + } + stat(options2) { + return (0, util_1.promisify)(this.fs, "fstat")(this.fd, options2); + } + sync() { + return (0, util_1.promisify)(this.fs, "fsync")(this.fd); + } + truncate(len) { + return (0, util_1.promisify)(this.fs, "ftruncate")(this.fd, len); + } + utimes(atime, mtime) { + return (0, util_1.promisify)(this.fs, "futimes")(this.fd, atime, mtime); + } + write(buffer2, offset2, length, position) { + return (0, util_1.promisify)(this.fs, "write", (bytesWritten) => ({ bytesWritten, buffer: buffer2 }))(this.fd, buffer2, offset2, length, position); + } + writev(buffers, position) { + return (0, util_1.promisify)(this.fs, "writev", (bytesWritten) => ({ bytesWritten, buffers }))(this.fd, buffers, position); + } + writeFile(data2, options2) { + return (0, util_1.promisify)(this.fs, "writeFile")(this.fd, data2, options2); + } + }; + FileHandle.FileHandle = FileHandle$1; + return FileHandle; +} +var FsPromises = {}; +var hasRequiredFsPromises; +function requireFsPromises() { + if (hasRequiredFsPromises) return FsPromises; + hasRequiredFsPromises = 1; + Object.defineProperty(FsPromises, "__esModule", { value: true }); + FsPromises.FsPromises = void 0; + const util_1 = requireUtil$2(); + const constants_1 = requireConstants$7(); + let FsPromises$1 = class FsPromises { + constructor(fs2, FileHandle2) { + this.fs = fs2; + this.FileHandle = FileHandle2; + this.constants = constants_1.constants; + this.cp = (0, util_1.promisify)(this.fs, "cp"); + this.opendir = (0, util_1.promisify)(this.fs, "opendir"); + this.statfs = (0, util_1.promisify)(this.fs, "statfs"); + this.lutimes = (0, util_1.promisify)(this.fs, "lutimes"); + this.access = (0, util_1.promisify)(this.fs, "access"); + this.chmod = (0, util_1.promisify)(this.fs, "chmod"); + this.chown = (0, util_1.promisify)(this.fs, "chown"); + this.copyFile = (0, util_1.promisify)(this.fs, "copyFile"); + this.lchmod = (0, util_1.promisify)(this.fs, "lchmod"); + this.lchown = (0, util_1.promisify)(this.fs, "lchown"); + this.link = (0, util_1.promisify)(this.fs, "link"); + this.lstat = (0, util_1.promisify)(this.fs, "lstat"); + this.mkdir = (0, util_1.promisify)(this.fs, "mkdir"); + this.mkdtemp = (0, util_1.promisify)(this.fs, "mkdtemp"); + this.readdir = (0, util_1.promisify)(this.fs, "readdir"); + this.readlink = (0, util_1.promisify)(this.fs, "readlink"); + this.realpath = (0, util_1.promisify)(this.fs, "realpath"); + this.rename = (0, util_1.promisify)(this.fs, "rename"); + this.rmdir = (0, util_1.promisify)(this.fs, "rmdir"); + this.rm = (0, util_1.promisify)(this.fs, "rm"); + this.stat = (0, util_1.promisify)(this.fs, "stat"); + this.symlink = (0, util_1.promisify)(this.fs, "symlink"); + this.truncate = (0, util_1.promisify)(this.fs, "truncate"); + this.unlink = (0, util_1.promisify)(this.fs, "unlink"); + this.utimes = (0, util_1.promisify)(this.fs, "utimes"); + this.readFile = (id, options2) => { + return (0, util_1.promisify)(this.fs, "readFile")(id instanceof this.FileHandle ? id.fd : id, options2); + }; + this.appendFile = (path2, data2, options2) => { + return (0, util_1.promisify)(this.fs, "appendFile")(path2 instanceof this.FileHandle ? path2.fd : path2, data2, options2); + }; + this.open = (path2, flags = "r", mode) => { + return (0, util_1.promisify)(this.fs, "open", (fd) => new this.FileHandle(this.fs, fd))(path2, flags, mode); + }; + this.writeFile = (id, data2, options2) => { + return (0, util_1.promisify)(this.fs, "writeFile")(id instanceof this.FileHandle ? id.fd : id, data2, options2); + }; + this.watch = () => { + throw new Error("Not implemented"); + }; + } + }; + FsPromises.FsPromises = FsPromises$1; + return FsPromises; +} +var print = {}; +var printTree = {}; +var hasRequiredPrintTree; +function requirePrintTree() { + if (hasRequiredPrintTree) return printTree; + hasRequiredPrintTree = 1; + Object.defineProperty(printTree, "__esModule", { value: true }); + printTree.printTree = void 0; + const printTree$1 = (tab = "", children) => { + children = children.filter(Boolean); + let str = ""; + for (let i = 0; i < children.length; i++) { + const isLast = i >= children.length - 1; + const fn = children[i]; + if (!fn) + continue; + const child = fn(tab + `${isLast ? " " : "│"} `); + const branch = child ? isLast ? "└─" : "├─" : "│ "; + str += ` +${tab}${branch} ${child}`; + } + return str; + }; + printTree.printTree = printTree$1; + return printTree; +} +var util$2 = {}; +var hasRequiredUtil$1; +function requireUtil$1() { + if (hasRequiredUtil$1) return util$2; + hasRequiredUtil$1 = 1; + Object.defineProperty(util$2, "__esModule", { value: true }); + util$2.newNotAllowedError = util$2.newTypeMismatchError = util$2.newNotFoundError = util$2.assertCanWrite = util$2.assertName = util$2.basename = util$2.ctx = void 0; + const ctx = (partial = {}) => { + return Object.assign({ separator: "/", syncHandleAllowed: false, mode: "read" }, partial); + }; + util$2.ctx = ctx; + const basename = (path2, separator) => { + if (path2[path2.length - 1] === separator) + path2 = path2.slice(0, -1); + const lastSlashIndex = path2.lastIndexOf(separator); + return lastSlashIndex === -1 ? path2 : path2.slice(lastSlashIndex + 1); + }; + util$2.basename = basename; + const nameRegex = /^(\.{1,2})$|^(.*([\/\\]).*)$/; + const assertName = (name, method, klass) => { + const isInvalid = !name || nameRegex.test(name); + if (isInvalid) + throw new TypeError(`Failed to execute '${method}' on '${klass}': Name is not allowed.`); + }; + util$2.assertName = assertName; + const assertCanWrite = (mode) => { + if (mode !== "readwrite") + throw new DOMException("The request is not allowed by the user agent or the platform in the current context.", "NotAllowedError"); + }; + util$2.assertCanWrite = assertCanWrite; + const newNotFoundError = () => new DOMException("A requested file or directory could not be found at the time an operation was processed.", "NotFoundError"); + util$2.newNotFoundError = newNotFoundError; + const newTypeMismatchError = () => new DOMException("The path supplied exists, but was not an entry of requested type.", "TypeMismatchError"); + util$2.newTypeMismatchError = newTypeMismatchError; + const newNotAllowedError = () => new DOMException("Permission not granted.", "NotAllowedError"); + util$2.newNotAllowedError = newNotAllowedError; + return util$2; +} +var hasRequiredPrint; +function requirePrint() { + if (hasRequiredPrint) return print; + hasRequiredPrint = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toTreeSync = void 0; + const printTree_1 = requirePrintTree(); + const util_1 = requireUtil$1(); + const toTreeSync = (fs2, opts = {}) => { + var _a2; + const separator = opts.separator || "/"; + let dir = opts.dir || separator; + if (dir[dir.length - 1] !== separator) + dir += separator; + const tab = opts.tab || ""; + const depth = (_a2 = opts.depth) !== null && _a2 !== void 0 ? _a2 : 10; + let subtree = " (...)"; + if (depth > 0) { + const list = fs2.readdirSync(dir, { withFileTypes: true }); + subtree = (0, printTree_1.printTree)(tab, list.map((entry) => (tab2) => { + if (entry.isDirectory()) { + return (0, exports.toTreeSync)(fs2, { dir: dir + entry.name, depth: depth - 1, tab: tab2 }); + } else if (entry.isSymbolicLink()) { + return "" + entry.name + " → " + fs2.readlinkSync(dir + entry.name); + } else { + return "" + entry.name; + } + })); + } + const base2 = (0, util_1.basename)(dir, separator) + separator; + return base2 + subtree; + }; + exports.toTreeSync = toTreeSync; + })(print); + return print; +} +var options$1 = {}; +var hasRequiredOptions; +function requireOptions() { + if (hasRequiredOptions) return options$1; + hasRequiredOptions = 1; + (function(exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getWriteFileOptions = exports.writeFileDefaults = exports.getRealpathOptsAndCb = exports.getRealpathOptions = exports.getStatOptsAndCb = exports.getStatOptions = exports.getAppendFileOptsAndCb = exports.getAppendFileOpts = exports.getReaddirOptsAndCb = exports.getReaddirOptions = exports.getReadFileOptions = exports.getRmOptsAndCb = exports.getRmdirOptions = exports.getDefaultOptsAndCb = exports.getDefaultOpts = exports.optsDefaults = exports.optsAndCbGenerator = exports.optsGenerator = exports.getOptions = exports.getMkdirOptions = void 0; + const constants_1 = requireConstants$6(); + const encoding_1 = requireEncoding(); + const util_1 = requireUtil$2(); + const mkdirDefaults = { + mode: 511, + recursive: false + }; + const getMkdirOptions = (options2) => { + if (typeof options2 === "number") + return Object.assign({}, mkdirDefaults, { mode: options2 }); + return Object.assign({}, mkdirDefaults, options2); + }; + exports.getMkdirOptions = getMkdirOptions; + const ERRSTR_OPTS = (tipeof) => `Expected options to be either an object or a string, but got ${tipeof} instead`; + function getOptions2(defaults, options2) { + let opts; + if (!options2) + return defaults; + else { + const tipeof = typeof options2; + switch (tipeof) { + case "string": + opts = Object.assign({}, defaults, { encoding: options2 }); + break; + case "object": + opts = Object.assign({}, defaults, options2); + break; + default: + throw TypeError(ERRSTR_OPTS(tipeof)); + } + } + if (opts.encoding !== "buffer") + (0, encoding_1.assertEncoding)(opts.encoding); + return opts; + } + exports.getOptions = getOptions2; + function optsGenerator(defaults) { + return (options2) => getOptions2(defaults, options2); + } + exports.optsGenerator = optsGenerator; + function optsAndCbGenerator(getOpts) { + return (options2, callback) => typeof options2 === "function" ? [getOpts(), options2] : [getOpts(options2), (0, util_1.validateCallback)(callback)]; + } + exports.optsAndCbGenerator = optsAndCbGenerator; + exports.optsDefaults = { + encoding: "utf8" + }; + exports.getDefaultOpts = optsGenerator(exports.optsDefaults); + exports.getDefaultOptsAndCb = optsAndCbGenerator(exports.getDefaultOpts); + const rmdirDefaults = { + recursive: false + }; + const getRmdirOptions = (options2) => { + return Object.assign({}, rmdirDefaults, options2); + }; + exports.getRmdirOptions = getRmdirOptions; + const getRmOpts = optsGenerator(exports.optsDefaults); + exports.getRmOptsAndCb = optsAndCbGenerator(getRmOpts); + const readFileOptsDefaults = { + flag: "r" + }; + exports.getReadFileOptions = optsGenerator(readFileOptsDefaults); + const readdirDefaults = { + encoding: "utf8", + recursive: false, + withFileTypes: false + }; + exports.getReaddirOptions = optsGenerator(readdirDefaults); + exports.getReaddirOptsAndCb = optsAndCbGenerator(exports.getReaddirOptions); + const appendFileDefaults = { + encoding: "utf8", + mode: 438, + flag: constants_1.FLAGS[constants_1.FLAGS.a] + }; + exports.getAppendFileOpts = optsGenerator(appendFileDefaults); + exports.getAppendFileOptsAndCb = optsAndCbGenerator(exports.getAppendFileOpts); + const statDefaults = { + bigint: false + }; + const getStatOptions = (options2 = {}) => Object.assign({}, statDefaults, options2); + exports.getStatOptions = getStatOptions; + const getStatOptsAndCb = (options2, callback) => typeof options2 === "function" ? [(0, exports.getStatOptions)(), options2] : [(0, exports.getStatOptions)(options2), (0, util_1.validateCallback)(callback)]; + exports.getStatOptsAndCb = getStatOptsAndCb; + const realpathDefaults = exports.optsDefaults; + exports.getRealpathOptions = optsGenerator(realpathDefaults); + exports.getRealpathOptsAndCb = optsAndCbGenerator(exports.getRealpathOptions); + exports.writeFileDefaults = { + encoding: "utf8", + mode: 438, + flag: constants_1.FLAGS[constants_1.FLAGS.w] + }; + exports.getWriteFileOptions = optsGenerator(exports.writeFileDefaults); + })(options$1); + return options$1; +} +var hasRequiredVolume; +function requireVolume() { + if (hasRequiredVolume) return volume; + hasRequiredVolume = 1; + Object.defineProperty(volume, "__esModule", { value: true }); + volume.FSWatcher = volume.StatWatcher = volume.Volume = volume.toUnixTimestamp = volume.dataToStr = volume.pathToSteps = volume.filenameToSteps = void 0; + const pathModule = requirePath(); + const node_1 = requireNode$1(); + const Stats_1 = requireStats(); + const Dirent_1 = requireDirent(); + const buffer_1 = requireBuffer$1(); + const setImmediate_1 = requireSetImmediate(); + const queueMicrotask_1 = requireQueueMicrotask(); + const process_1 = requireProcess(); + const setTimeoutUnref_1 = requireSetTimeoutUnref(); + const stream_1 = requireBrowser$h(); + const constants_1 = requireConstants$7(); + const events_1 = requireEvents(); + const encoding_1 = requireEncoding(); + const FileHandle_1 = requireFileHandle(); + const util2 = requireUtil$5(); + const FsPromises_1 = requireFsPromises(); + const print_1 = requirePrint(); + const constants_2 = requireConstants$6(); + const options_1 = requireOptions(); + const util_1 = requireUtil$2(); + const resolveCrossPlatform = pathModule.resolve; + const { O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_DIRECTORY, O_SYMLINK, F_OK, COPYFILE_EXCL, COPYFILE_FICLONE_FORCE } = constants_1.constants; + const { sep, relative, join: join2, dirname } = pathModule.posix ? pathModule.posix : pathModule; + const kMinPoolSpace = 128; + const EPERM = "EPERM"; + const ENOENT = "ENOENT"; + const EBADF = "EBADF"; + const EINVAL = "EINVAL"; + const EEXIST = "EEXIST"; + const ENOTDIR = "ENOTDIR"; + const EMFILE = "EMFILE"; + const EACCES = "EACCES"; + const EISDIR = "EISDIR"; + const ENOTEMPTY = "ENOTEMPTY"; + const ENOSYS = "ENOSYS"; + const ERR_FS_EISDIR = "ERR_FS_EISDIR"; + const ERR_OUT_OF_RANGE = "ERR_OUT_OF_RANGE"; + let resolve = (filename, base2 = process_1.default.cwd()) => resolveCrossPlatform(base2, filename); + if (util_1.isWin) { + const _resolve = resolve; + resolve = (filename, base2) => (0, util_1.unixify)(_resolve(filename, base2)); + } + function filenameToSteps(filename, base2) { + const fullPath = resolve(filename, base2); + const fullPathSansSlash = fullPath.substring(1); + if (!fullPathSansSlash) + return []; + return fullPathSansSlash.split(sep); + } + volume.filenameToSteps = filenameToSteps; + function pathToSteps(path2) { + return filenameToSteps((0, util_1.pathToFilename)(path2)); + } + volume.pathToSteps = pathToSteps; + function dataToStr(data2, encoding2 = encoding_1.ENCODING_UTF8) { + if (buffer_1.Buffer.isBuffer(data2)) + return data2.toString(encoding2); + else if (data2 instanceof Uint8Array) + return (0, buffer_1.bufferFrom)(data2).toString(encoding2); + else + return String(data2); + } + volume.dataToStr = dataToStr; + function toUnixTimestamp(time) { + if (typeof time === "string" && +time == time) { + return +time; + } + if (time instanceof Date) { + return time.getTime() / 1e3; + } + if (isFinite(time)) { + if (time < 0) { + return Date.now() / 1e3; + } + return time; + } + throw new Error("Cannot parse time: " + time); + } + volume.toUnixTimestamp = toUnixTimestamp; + function validateUid(uid) { + if (typeof uid !== "number") + throw TypeError(constants_2.ERRSTR.UID); + } + function validateGid(gid) { + if (typeof gid !== "number") + throw TypeError(constants_2.ERRSTR.GID); + } + function flattenJSON(nestedJSON) { + const flatJSON = {}; + function flatten(pathPrefix, node2) { + for (const path2 in node2) { + const contentOrNode = node2[path2]; + const joinedPath = join2(pathPrefix, path2); + if (typeof contentOrNode === "string" || contentOrNode instanceof buffer_1.Buffer) { + flatJSON[joinedPath] = contentOrNode; + } else if (typeof contentOrNode === "object" && contentOrNode !== null && Object.keys(contentOrNode).length > 0) { + flatten(joinedPath, contentOrNode); + } else { + flatJSON[joinedPath] = null; + } + } + } + flatten("", nestedJSON); + return flatJSON; + } + const notImplemented = () => { + throw new Error("Not implemented"); + }; + class Volume { + static fromJSON(json, cwd) { + const vol = new Volume(); + vol.fromJSON(json, cwd); + return vol; + } + static fromNestedJSON(json, cwd) { + const vol = new Volume(); + vol.fromNestedJSON(json, cwd); + return vol; + } + get promises() { + if (this.promisesApi === null) + throw new Error("Promise is not supported in this environment."); + return this.promisesApi; + } + constructor(props = {}) { + this.ino = 0; + this.inodes = {}; + this.releasedInos = []; + this.fds = {}; + this.releasedFds = []; + this.maxFiles = 1e4; + this.openFiles = 0; + this.promisesApi = new FsPromises_1.FsPromises(this, FileHandle_1.FileHandle); + this.statWatchers = {}; + this.cpSync = notImplemented; + this.lutimesSync = notImplemented; + this.statfsSync = notImplemented; + this.opendirSync = notImplemented; + this.cp = notImplemented; + this.lutimes = notImplemented; + this.statfs = notImplemented; + this.openAsBlob = notImplemented; + this.opendir = notImplemented; + this.props = Object.assign({ Node: node_1.Node, Link: node_1.Link, File: node_1.File }, props); + const root = this.createLink(); + root.setNode(this.createNode(true)); + const self2 = this; + this.StatWatcher = class extends StatWatcher { + constructor() { + super(self2); + } + }; + const _ReadStream = FsReadStream; + this.ReadStream = class extends _ReadStream { + constructor(...args) { + super(self2, ...args); + } + }; + const _WriteStream = FsWriteStream; + this.WriteStream = class extends _WriteStream { + constructor(...args) { + super(self2, ...args); + } + }; + this.FSWatcher = class extends FSWatcher { + constructor() { + super(self2); + } + }; + root.setChild(".", root); + root.getNode().nlink++; + root.setChild("..", root); + root.getNode().nlink++; + this.root = root; + } + createLink(parent, name, isDirectory = false, perm) { + if (!parent) { + return new this.props.Link(this, null, ""); + } + if (!name) { + throw new Error("createLink: name cannot be empty"); + } + return parent.createChild(name, this.createNode(isDirectory, perm)); + } + deleteLink(link2) { + const parent = link2.parent; + if (parent) { + parent.deleteChild(link2); + return true; + } + return false; + } + newInoNumber() { + const releasedFd = this.releasedInos.pop(); + if (releasedFd) + return releasedFd; + else { + this.ino = (this.ino + 1) % 4294967295; + return this.ino; + } + } + newFdNumber() { + const releasedFd = this.releasedFds.pop(); + return typeof releasedFd === "number" ? releasedFd : Volume.fd--; + } + createNode(isDirectory = false, perm) { + const node2 = new this.props.Node(this.newInoNumber(), perm); + if (isDirectory) + node2.setIsDirectory(); + this.inodes[node2.ino] = node2; + return node2; + } + deleteNode(node2) { + node2.del(); + delete this.inodes[node2.ino]; + this.releasedInos.push(node2.ino); + } + // Returns a `Link` (hard link) referenced by path "split" into steps. + getLink(steps) { + return this.root.walk(steps); + } + // Just link `getLink`, but throws a correct user error, if link to found. + getLinkOrThrow(filename, funcName) { + const steps = filenameToSteps(filename); + const link2 = this.getLink(steps); + if (!link2) + throw (0, util_1.createError)(ENOENT, funcName, filename); + return link2; + } + // Just like `getLink`, but also dereference/resolves symbolic links. + getResolvedLink(filenameOrSteps) { + let steps = typeof filenameOrSteps === "string" ? filenameToSteps(filenameOrSteps) : filenameOrSteps; + let link2 = this.root; + let i = 0; + while (i < steps.length) { + const step = steps[i]; + link2 = link2.getChild(step); + if (!link2) + return null; + const node2 = link2.getNode(); + if (node2.isSymlink()) { + steps = node2.symlink.concat(steps.slice(i + 1)); + link2 = this.root; + i = 0; + continue; + } + i++; + } + return link2; + } + // Just like `getLinkOrThrow`, but also dereference/resolves symbolic links. + getResolvedLinkOrThrow(filename, funcName) { + const link2 = this.getResolvedLink(filename); + if (!link2) + throw (0, util_1.createError)(ENOENT, funcName, filename); + return link2; + } + resolveSymlinks(link2) { + return this.getResolvedLink(link2.steps.slice(1)); + } + // Just like `getLinkOrThrow`, but also verifies that the link is a directory. + getLinkAsDirOrThrow(filename, funcName) { + const link2 = this.getLinkOrThrow(filename, funcName); + if (!link2.getNode().isDirectory()) + throw (0, util_1.createError)(ENOTDIR, funcName, filename); + return link2; + } + // Get the immediate parent directory of the link. + getLinkParent(steps) { + return this.root.walk(steps, steps.length - 1); + } + getLinkParentAsDirOrThrow(filenameOrSteps, funcName) { + const steps = filenameOrSteps instanceof Array ? filenameOrSteps : filenameToSteps(filenameOrSteps); + const link2 = this.getLinkParent(steps); + if (!link2) + throw (0, util_1.createError)(ENOENT, funcName, sep + steps.join(sep)); + if (!link2.getNode().isDirectory()) + throw (0, util_1.createError)(ENOTDIR, funcName, sep + steps.join(sep)); + return link2; + } + getFileByFd(fd) { + return this.fds[String(fd)]; + } + getFileByFdOrThrow(fd, funcName) { + if (!(0, util_1.isFd)(fd)) + throw TypeError(constants_2.ERRSTR.FD); + const file = this.getFileByFd(fd); + if (!file) + throw (0, util_1.createError)(EBADF, funcName); + return file; + } + /** + * @todo This is not used anymore. Remove. + */ + /* + private getNodeByIdOrCreate(id: TFileId, flags: number, perm: number): Node { + if (typeof id === 'number') { + const file = this.getFileByFd(id); + if (!file) throw Error('File nto found'); + return file.node; + } else { + const steps = pathToSteps(id as PathLike); + let link = this.getLink(steps); + if (link) return link.getNode(); + + // Try creating a node if not found. + if (flags & O_CREAT) { + const dirLink = this.getLinkParent(steps); + if (dirLink) { + const name = steps[steps.length - 1]; + link = this.createLink(dirLink, name, false, perm); + return link.getNode(); + } + } + + throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id)); + } + } + */ + wrapAsync(method, args, callback) { + (0, util_1.validateCallback)(callback); + (0, setImmediate_1.default)(() => { + let result; + try { + result = method.apply(this, args); + } catch (err) { + callback(err); + return; + } + callback(null, result); + }); + } + _toJSON(link2 = this.root, json = {}, path2, asBuffer) { + let isEmpty2 = true; + let children = link2.children; + if (link2.getNode().isFile()) { + children = /* @__PURE__ */ new Map([[link2.getName(), link2.parent.getChild(link2.getName())]]); + link2 = link2.parent; + } + for (const name of children.keys()) { + if (name === "." || name === "..") { + continue; + } + isEmpty2 = false; + const child = link2.getChild(name); + if (!child) { + throw new Error("_toJSON: unexpected undefined"); + } + const node2 = child.getNode(); + if (node2.isFile()) { + let filename = child.getPath(); + if (path2) + filename = relative(path2, filename); + json[filename] = asBuffer ? node2.getBuffer() : node2.getString(); + } else if (node2.isDirectory()) { + this._toJSON(child, json, path2); + } + } + let dirPath = link2.getPath(); + if (path2) + dirPath = relative(path2, dirPath); + if (dirPath && isEmpty2) { + json[dirPath] = null; + } + return json; + } + toJSON(paths, json = {}, isRelative = false, asBuffer = false) { + const links = []; + if (paths) { + if (!Array.isArray(paths)) + paths = [paths]; + for (const path2 of paths) { + const filename = (0, util_1.pathToFilename)(path2); + const link2 = this.getResolvedLink(filename); + if (!link2) + continue; + links.push(link2); + } + } else { + links.push(this.root); + } + if (!links.length) + return json; + for (const link2 of links) + this._toJSON(link2, json, isRelative ? link2.getPath() : "", asBuffer); + return json; + } + // TODO: `cwd` should probably not invoke `process.cwd()`. + fromJSON(json, cwd = process_1.default.cwd()) { + for (let filename in json) { + const data2 = json[filename]; + filename = resolve(filename, cwd); + if (typeof data2 === "string" || data2 instanceof buffer_1.Buffer) { + const dir = dirname(filename); + this.mkdirpBase( + dir, + 511 + /* MODE.DIR */ + ); + this.writeFileSync(filename, data2); + } else { + this.mkdirpBase( + filename, + 511 + /* MODE.DIR */ + ); + } + } + } + fromNestedJSON(json, cwd) { + this.fromJSON(flattenJSON(json), cwd); + } + toTree(opts = { separator: sep }) { + return (0, print_1.toTreeSync)(this, opts); + } + reset() { + this.ino = 0; + this.inodes = {}; + this.releasedInos = []; + this.fds = {}; + this.releasedFds = []; + this.openFiles = 0; + this.root = this.createLink(); + this.root.setNode(this.createNode(true)); + } + // Legacy interface + mountSync(mountpoint, json) { + this.fromJSON(json, mountpoint); + } + openLink(link2, flagsNum, resolveSymlinks = true) { + if (this.openFiles >= this.maxFiles) { + throw (0, util_1.createError)(EMFILE, "open", link2.getPath()); + } + let realLink = link2; + if (resolveSymlinks) + realLink = this.resolveSymlinks(link2); + if (!realLink) + throw (0, util_1.createError)(ENOENT, "open", link2.getPath()); + const node2 = realLink.getNode(); + if (node2.isDirectory()) { + if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY) + throw (0, util_1.createError)(EISDIR, "open", link2.getPath()); + } else { + if (flagsNum & O_DIRECTORY) + throw (0, util_1.createError)(ENOTDIR, "open", link2.getPath()); + } + if (!(flagsNum & O_WRONLY)) { + if (!node2.canRead()) { + throw (0, util_1.createError)(EACCES, "open", link2.getPath()); + } + } + const file = new this.props.File(link2, node2, flagsNum, this.newFdNumber()); + this.fds[file.fd] = file; + this.openFiles++; + if (flagsNum & O_TRUNC) + file.truncate(); + return file; + } + openFile(filename, flagsNum, modeNum, resolveSymlinks = true) { + const steps = filenameToSteps(filename); + let link2 = resolveSymlinks ? this.getResolvedLink(steps) : this.getLink(steps); + if (link2 && flagsNum & O_EXCL) + throw (0, util_1.createError)(EEXIST, "open", filename); + if (!link2 && flagsNum & O_CREAT) { + const dirLink = this.getResolvedLink(steps.slice(0, steps.length - 1)); + if (!dirLink) + throw (0, util_1.createError)(ENOENT, "open", sep + steps.join(sep)); + if (flagsNum & O_CREAT && typeof modeNum === "number") { + link2 = this.createLink(dirLink, steps[steps.length - 1], false, modeNum); + } + } + if (link2) + return this.openLink(link2, flagsNum, resolveSymlinks); + throw (0, util_1.createError)(ENOENT, "open", filename); + } + openBase(filename, flagsNum, modeNum, resolveSymlinks = true) { + const file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks); + if (!file) + throw (0, util_1.createError)(ENOENT, "open", filename); + return file.fd; + } + openSync(path2, flags, mode = 438) { + const modeNum = (0, util_1.modeToNumber)(mode); + const fileName = (0, util_1.pathToFilename)(path2); + const flagsNum = (0, util_1.flagsToNumber)(flags); + return this.openBase(fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)); + } + open(path2, flags, a, b) { + let mode = a; + let callback = b; + if (typeof a === "function") { + mode = 438; + callback = a; + } + mode = mode || 438; + const modeNum = (0, util_1.modeToNumber)(mode); + const fileName = (0, util_1.pathToFilename)(path2); + const flagsNum = (0, util_1.flagsToNumber)(flags); + this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)], callback); + } + closeFile(file) { + if (!this.fds[file.fd]) + return; + this.openFiles--; + delete this.fds[file.fd]; + this.releasedFds.push(file.fd); + } + closeSync(fd) { + (0, util_1.validateFd)(fd); + const file = this.getFileByFdOrThrow(fd, "close"); + this.closeFile(file); + } + close(fd, callback) { + (0, util_1.validateFd)(fd); + this.wrapAsync(this.closeSync, [fd], callback); + } + openFileOrGetById(id, flagsNum, modeNum) { + if (typeof id === "number") { + const file = this.fds[id]; + if (!file) + throw (0, util_1.createError)(ENOENT); + return file; + } else { + return this.openFile((0, util_1.pathToFilename)(id), flagsNum, modeNum); + } + } + readBase(fd, buffer2, offset2, length, position) { + if (buffer2.byteLength < length) { + throw (0, util_1.createError)(ERR_OUT_OF_RANGE, "read", void 0, void 0, RangeError); + } + const file = this.getFileByFdOrThrow(fd); + if (file.node.isSymlink()) { + throw (0, util_1.createError)(EPERM, "read", file.link.getPath()); + } + return file.read(buffer2, Number(offset2), Number(length), position === -1 || typeof position !== "number" ? void 0 : position); + } + readSync(fd, buffer2, offset2, length, position) { + (0, util_1.validateFd)(fd); + return this.readBase(fd, buffer2, offset2, length, position); + } + read(fd, buffer2, offset2, length, position, callback) { + (0, util_1.validateCallback)(callback); + if (length === 0) { + return (0, queueMicrotask_1.default)(() => { + if (callback) + callback(null, 0, buffer2); + }); + } + (0, setImmediate_1.default)(() => { + try { + const bytes = this.readBase(fd, buffer2, offset2, length, position); + callback(null, bytes, buffer2); + } catch (err) { + callback(err); + } + }); + } + readvBase(fd, buffers, position) { + const file = this.getFileByFdOrThrow(fd); + let p = position !== null && position !== void 0 ? position : void 0; + if (p === -1) { + p = void 0; + } + let bytesRead = 0; + for (const buffer2 of buffers) { + const bytes = file.read(buffer2, 0, buffer2.byteLength, p); + p = void 0; + bytesRead += bytes; + if (bytes < buffer2.byteLength) + break; + } + return bytesRead; + } + readv(fd, buffers, a, b) { + let position = a; + let callback = b; + if (typeof a === "function") { + position = null; + callback = a; + } + (0, util_1.validateCallback)(callback); + (0, setImmediate_1.default)(() => { + try { + const bytes = this.readvBase(fd, buffers, position); + callback(null, bytes, buffers); + } catch (err) { + callback(err); + } + }); + } + readvSync(fd, buffers, position) { + (0, util_1.validateFd)(fd); + return this.readvBase(fd, buffers, position); + } + readFileBase(id, flagsNum, encoding2) { + let result; + const isUserFd = typeof id === "number"; + const userOwnsFd = isUserFd && (0, util_1.isFd)(id); + let fd; + if (userOwnsFd) + fd = id; + else { + const filename = (0, util_1.pathToFilename)(id); + const steps = filenameToSteps(filename); + const link2 = this.getResolvedLink(steps); + if (link2) { + const node2 = link2.getNode(); + if (node2.isDirectory()) + throw (0, util_1.createError)(EISDIR, "open", link2.getPath()); + } + fd = this.openSync(id, flagsNum); + } + try { + result = (0, util_1.bufferToEncoding)(this.getFileByFdOrThrow(fd).getBuffer(), encoding2); + } finally { + if (!userOwnsFd) { + this.closeSync(fd); + } + } + return result; + } + readFileSync(file, options2) { + const opts = (0, options_1.getReadFileOptions)(options2); + const flagsNum = (0, util_1.flagsToNumber)(opts.flag); + return this.readFileBase(file, flagsNum, opts.encoding); + } + readFile(id, a, b) { + const [opts, callback] = (0, options_1.optsAndCbGenerator)(options_1.getReadFileOptions)(a, b); + const flagsNum = (0, util_1.flagsToNumber)(opts.flag); + this.wrapAsync(this.readFileBase, [id, flagsNum, opts.encoding], callback); + } + writeBase(fd, buf, offset2, length, position) { + const file = this.getFileByFdOrThrow(fd, "write"); + if (file.node.isSymlink()) { + throw (0, util_1.createError)(EBADF, "write", file.link.getPath()); + } + return file.write(buf, offset2, length, position === -1 || typeof position !== "number" ? void 0 : position); + } + writeSync(fd, a, b, c, d) { + const [, buf, offset2, length, position] = (0, util_1.getWriteSyncArgs)(fd, a, b, c, d); + return this.writeBase(fd, buf, offset2, length, position); + } + write(fd, a, b, c, d, e) { + const [, asStr, buf, offset2, length, position, cb] = (0, util_1.getWriteArgs)(fd, a, b, c, d, e); + (0, setImmediate_1.default)(() => { + try { + const bytes = this.writeBase(fd, buf, offset2, length, position); + if (!asStr) { + cb(null, bytes, buf); + } else { + cb(null, bytes, a); + } + } catch (err) { + cb(err); + } + }); + } + writevBase(fd, buffers, position) { + const file = this.getFileByFdOrThrow(fd); + let p = position !== null && position !== void 0 ? position : void 0; + if (p === -1) { + p = void 0; + } + let bytesWritten = 0; + for (const buffer2 of buffers) { + const nodeBuf = buffer_1.Buffer.from(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength); + const bytes = file.write(nodeBuf, 0, nodeBuf.byteLength, p); + p = void 0; + bytesWritten += bytes; + if (bytes < nodeBuf.byteLength) + break; + } + return bytesWritten; + } + writev(fd, buffers, a, b) { + let position = a; + let callback = b; + if (typeof a === "function") { + position = null; + callback = a; + } + (0, util_1.validateCallback)(callback); + (0, setImmediate_1.default)(() => { + try { + const bytes = this.writevBase(fd, buffers, position); + callback(null, bytes, buffers); + } catch (err) { + callback(err); + } + }); + } + writevSync(fd, buffers, position) { + (0, util_1.validateFd)(fd); + return this.writevBase(fd, buffers, position); + } + writeFileBase(id, buf, flagsNum, modeNum) { + const isUserFd = typeof id === "number"; + let fd; + if (isUserFd) + fd = id; + else { + fd = this.openBase((0, util_1.pathToFilename)(id), flagsNum, modeNum); + } + let offset2 = 0; + let length = buf.length; + let position = flagsNum & O_APPEND ? void 0 : 0; + try { + while (length > 0) { + const written = this.writeSync(fd, buf, offset2, length, position); + offset2 += written; + length -= written; + if (position !== void 0) + position += written; + } + } finally { + if (!isUserFd) + this.closeSync(fd); + } + } + writeFileSync(id, data2, options2) { + const opts = (0, options_1.getWriteFileOptions)(options2); + const flagsNum = (0, util_1.flagsToNumber)(opts.flag); + const modeNum = (0, util_1.modeToNumber)(opts.mode); + const buf = (0, util_1.dataToBuffer)(data2, opts.encoding); + this.writeFileBase(id, buf, flagsNum, modeNum); + } + writeFile(id, data2, a, b) { + let options2 = a; + let callback = b; + if (typeof a === "function") { + options2 = options_1.writeFileDefaults; + callback = a; + } + const cb = (0, util_1.validateCallback)(callback); + const opts = (0, options_1.getWriteFileOptions)(options2); + const flagsNum = (0, util_1.flagsToNumber)(opts.flag); + const modeNum = (0, util_1.modeToNumber)(opts.mode); + const buf = (0, util_1.dataToBuffer)(data2, opts.encoding); + this.wrapAsync(this.writeFileBase, [id, buf, flagsNum, modeNum], cb); + } + linkBase(filename1, filename2) { + const steps1 = filenameToSteps(filename1); + const link1 = this.getLink(steps1); + if (!link1) + throw (0, util_1.createError)(ENOENT, "link", filename1, filename2); + const steps2 = filenameToSteps(filename2); + const dir2 = this.getLinkParent(steps2); + if (!dir2) + throw (0, util_1.createError)(ENOENT, "link", filename1, filename2); + const name = steps2[steps2.length - 1]; + if (dir2.getChild(name)) + throw (0, util_1.createError)(EEXIST, "link", filename1, filename2); + const node2 = link1.getNode(); + node2.nlink++; + dir2.createChild(name, node2); + } + copyFileBase(src2, dest, flags) { + const buf = this.readFileSync(src2); + if (flags & COPYFILE_EXCL) { + if (this.existsSync(dest)) { + throw (0, util_1.createError)(EEXIST, "copyFile", src2, dest); + } + } + if (flags & COPYFILE_FICLONE_FORCE) { + throw (0, util_1.createError)(ENOSYS, "copyFile", src2, dest); + } + this.writeFileBase( + dest, + buf, + constants_2.FLAGS.w, + 438 + /* MODE.DEFAULT */ + ); + } + copyFileSync(src2, dest, flags) { + const srcFilename = (0, util_1.pathToFilename)(src2); + const destFilename = (0, util_1.pathToFilename)(dest); + return this.copyFileBase(srcFilename, destFilename, (flags || 0) | 0); + } + copyFile(src2, dest, a, b) { + const srcFilename = (0, util_1.pathToFilename)(src2); + const destFilename = (0, util_1.pathToFilename)(dest); + let flags; + let callback; + if (typeof a === "function") { + flags = 0; + callback = a; + } else { + flags = a; + callback = b; + } + (0, util_1.validateCallback)(callback); + this.wrapAsync(this.copyFileBase, [srcFilename, destFilename, flags], callback); + } + linkSync(existingPath, newPath) { + const existingPathFilename = (0, util_1.pathToFilename)(existingPath); + const newPathFilename = (0, util_1.pathToFilename)(newPath); + this.linkBase(existingPathFilename, newPathFilename); + } + link(existingPath, newPath, callback) { + const existingPathFilename = (0, util_1.pathToFilename)(existingPath); + const newPathFilename = (0, util_1.pathToFilename)(newPath); + this.wrapAsync(this.linkBase, [existingPathFilename, newPathFilename], callback); + } + unlinkBase(filename) { + const steps = filenameToSteps(filename); + const link2 = this.getLink(steps); + if (!link2) + throw (0, util_1.createError)(ENOENT, "unlink", filename); + if (link2.length) + throw Error("Dir not empty..."); + this.deleteLink(link2); + const node2 = link2.getNode(); + node2.nlink--; + if (node2.nlink <= 0) { + this.deleteNode(node2); + } + } + unlinkSync(path2) { + const filename = (0, util_1.pathToFilename)(path2); + this.unlinkBase(filename); + } + unlink(path2, callback) { + const filename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.unlinkBase, [filename], callback); + } + symlinkBase(targetFilename, pathFilename) { + const pathSteps = filenameToSteps(pathFilename); + const dirLink = this.getLinkParent(pathSteps); + if (!dirLink) + throw (0, util_1.createError)(ENOENT, "symlink", targetFilename, pathFilename); + const name = pathSteps[pathSteps.length - 1]; + if (dirLink.getChild(name)) + throw (0, util_1.createError)(EEXIST, "symlink", targetFilename, pathFilename); + const symlink2 = dirLink.createChild(name); + symlink2.getNode().makeSymlink(filenameToSteps(targetFilename)); + return symlink2; + } + // `type` argument works only on Windows. + symlinkSync(target, path2, type2) { + const targetFilename = (0, util_1.pathToFilename)(target); + const pathFilename = (0, util_1.pathToFilename)(path2); + this.symlinkBase(targetFilename, pathFilename); + } + symlink(target, path2, a, b) { + const callback = (0, util_1.validateCallback)(typeof a === "function" ? a : b); + const targetFilename = (0, util_1.pathToFilename)(target); + const pathFilename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.symlinkBase, [targetFilename, pathFilename], callback); + } + realpathBase(filename, encoding2) { + const steps = filenameToSteps(filename); + const realLink = this.getResolvedLink(steps); + if (!realLink) + throw (0, util_1.createError)(ENOENT, "realpath", filename); + return (0, encoding_1.strToEncoding)(realLink.getPath() || "/", encoding2); + } + realpathSync(path2, options2) { + return this.realpathBase((0, util_1.pathToFilename)(path2), (0, options_1.getRealpathOptions)(options2).encoding); + } + realpath(path2, a, b) { + const [opts, callback] = (0, options_1.getRealpathOptsAndCb)(a, b); + const pathFilename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.realpathBase, [pathFilename, opts.encoding], callback); + } + lstatBase(filename, bigint = false, throwIfNoEntry = false) { + const link2 = this.getLink(filenameToSteps(filename)); + if (link2) { + return Stats_1.default.build(link2.getNode(), bigint); + } else if (!throwIfNoEntry) { + return void 0; + } else { + throw (0, util_1.createError)(ENOENT, "lstat", filename); + } + } + lstatSync(path2, options2) { + const { throwIfNoEntry = true, bigint = false } = (0, options_1.getStatOptions)(options2); + return this.lstatBase((0, util_1.pathToFilename)(path2), bigint, throwIfNoEntry); + } + lstat(path2, a, b) { + const [{ throwIfNoEntry = true, bigint = false }, callback] = (0, options_1.getStatOptsAndCb)(a, b); + this.wrapAsync(this.lstatBase, [(0, util_1.pathToFilename)(path2), bigint, throwIfNoEntry], callback); + } + statBase(filename, bigint = false, throwIfNoEntry = true) { + const link2 = this.getResolvedLink(filenameToSteps(filename)); + if (link2) { + return Stats_1.default.build(link2.getNode(), bigint); + } else if (!throwIfNoEntry) { + return void 0; + } else { + throw (0, util_1.createError)(ENOENT, "stat", filename); + } + } + statSync(path2, options2) { + const { bigint = true, throwIfNoEntry = true } = (0, options_1.getStatOptions)(options2); + return this.statBase((0, util_1.pathToFilename)(path2), bigint, throwIfNoEntry); + } + stat(path2, a, b) { + const [{ bigint = false, throwIfNoEntry = true }, callback] = (0, options_1.getStatOptsAndCb)(a, b); + this.wrapAsync(this.statBase, [(0, util_1.pathToFilename)(path2), bigint, throwIfNoEntry], callback); + } + fstatBase(fd, bigint = false) { + const file = this.getFileByFd(fd); + if (!file) + throw (0, util_1.createError)(EBADF, "fstat"); + return Stats_1.default.build(file.node, bigint); + } + fstatSync(fd, options2) { + return this.fstatBase(fd, (0, options_1.getStatOptions)(options2).bigint); + } + fstat(fd, a, b) { + const [opts, callback] = (0, options_1.getStatOptsAndCb)(a, b); + this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback); + } + renameBase(oldPathFilename, newPathFilename) { + const link2 = this.getLink(filenameToSteps(oldPathFilename)); + if (!link2) + throw (0, util_1.createError)(ENOENT, "rename", oldPathFilename, newPathFilename); + const newPathSteps = filenameToSteps(newPathFilename); + const newPathDirLink = this.getLinkParent(newPathSteps); + if (!newPathDirLink) + throw (0, util_1.createError)(ENOENT, "rename", oldPathFilename, newPathFilename); + const oldLinkParent = link2.parent; + if (oldLinkParent) { + oldLinkParent.deleteChild(link2); + } + const name = newPathSteps[newPathSteps.length - 1]; + link2.name = name; + link2.steps = [...newPathDirLink.steps, name]; + newPathDirLink.setChild(link2.getName(), link2); + } + renameSync(oldPath, newPath) { + const oldPathFilename = (0, util_1.pathToFilename)(oldPath); + const newPathFilename = (0, util_1.pathToFilename)(newPath); + this.renameBase(oldPathFilename, newPathFilename); + } + rename(oldPath, newPath, callback) { + const oldPathFilename = (0, util_1.pathToFilename)(oldPath); + const newPathFilename = (0, util_1.pathToFilename)(newPath); + this.wrapAsync(this.renameBase, [oldPathFilename, newPathFilename], callback); + } + existsBase(filename) { + return !!this.statBase(filename); + } + existsSync(path2) { + try { + return this.existsBase((0, util_1.pathToFilename)(path2)); + } catch (err) { + return false; + } + } + exists(path2, callback) { + const filename = (0, util_1.pathToFilename)(path2); + if (typeof callback !== "function") + throw Error(constants_2.ERRSTR.CB); + (0, setImmediate_1.default)(() => { + try { + callback(this.existsBase(filename)); + } catch (err) { + callback(false); + } + }); + } + accessBase(filename, mode) { + this.getLinkOrThrow(filename, "access"); + } + accessSync(path2, mode = F_OK) { + const filename = (0, util_1.pathToFilename)(path2); + mode = mode | 0; + this.accessBase(filename, mode); + } + access(path2, a, b) { + let mode = F_OK; + let callback; + if (typeof a !== "function") { + mode = a | 0; + callback = (0, util_1.validateCallback)(b); + } else { + callback = a; + } + const filename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.accessBase, [filename, mode], callback); + } + appendFileSync(id, data2, options2) { + const opts = (0, options_1.getAppendFileOpts)(options2); + if (!opts.flag || (0, util_1.isFd)(id)) + opts.flag = "a"; + this.writeFileSync(id, data2, opts); + } + appendFile(id, data2, a, b) { + const [opts, callback] = (0, options_1.getAppendFileOptsAndCb)(a, b); + if (!opts.flag || (0, util_1.isFd)(id)) + opts.flag = "a"; + this.writeFile(id, data2, opts, callback); + } + readdirBase(filename, options2) { + const steps = filenameToSteps(filename); + const link2 = this.getResolvedLink(steps); + if (!link2) + throw (0, util_1.createError)(ENOENT, "readdir", filename); + const node2 = link2.getNode(); + if (!node2.isDirectory()) + throw (0, util_1.createError)(ENOTDIR, "scandir", filename); + const list = []; + for (const name of link2.children.keys()) { + const child = link2.getChild(name); + if (!child || name === "." || name === "..") + continue; + list.push(Dirent_1.default.build(child, options2.encoding)); + if (options2.recursive && child.children.size) { + const recurseOptions = Object.assign(Object.assign({}, options2), { recursive: true, withFileTypes: true }); + const childList = this.readdirBase(child.getPath(), recurseOptions); + list.push(...childList); + } + } + if (!util_1.isWin && options2.encoding !== "buffer") + list.sort((a, b) => { + if (a.name < b.name) + return -1; + if (a.name > b.name) + return 1; + return 0; + }); + if (options2.withFileTypes) + return list; + let filename2 = filename; + if (util_1.isWin) { + filename2 = filename2.replace(/\\/g, "/"); + } + return list.map((dirent) => { + if (options2.recursive) { + return dirent.path.replace(filename2 + pathModule.posix.sep, ""); + } + return dirent.name; + }); + } + readdirSync(path2, options2) { + const opts = (0, options_1.getReaddirOptions)(options2); + const filename = (0, util_1.pathToFilename)(path2); + return this.readdirBase(filename, opts); + } + readdir(path2, a, b) { + const [options2, callback] = (0, options_1.getReaddirOptsAndCb)(a, b); + const filename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.readdirBase, [filename, options2], callback); + } + readlinkBase(filename, encoding2) { + const link2 = this.getLinkOrThrow(filename, "readlink"); + const node2 = link2.getNode(); + if (!node2.isSymlink()) + throw (0, util_1.createError)(EINVAL, "readlink", filename); + const str = sep + node2.symlink.join(sep); + return (0, encoding_1.strToEncoding)(str, encoding2); + } + readlinkSync(path2, options2) { + const opts = (0, options_1.getDefaultOpts)(options2); + const filename = (0, util_1.pathToFilename)(path2); + return this.readlinkBase(filename, opts.encoding); + } + readlink(path2, a, b) { + const [opts, callback] = (0, options_1.getDefaultOptsAndCb)(a, b); + const filename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.readlinkBase, [filename, opts.encoding], callback); + } + fsyncBase(fd) { + this.getFileByFdOrThrow(fd, "fsync"); + } + fsyncSync(fd) { + this.fsyncBase(fd); + } + fsync(fd, callback) { + this.wrapAsync(this.fsyncBase, [fd], callback); + } + fdatasyncBase(fd) { + this.getFileByFdOrThrow(fd, "fdatasync"); + } + fdatasyncSync(fd) { + this.fdatasyncBase(fd); + } + fdatasync(fd, callback) { + this.wrapAsync(this.fdatasyncBase, [fd], callback); + } + ftruncateBase(fd, len) { + const file = this.getFileByFdOrThrow(fd, "ftruncate"); + file.truncate(len); + } + ftruncateSync(fd, len) { + this.ftruncateBase(fd, len); + } + ftruncate(fd, a, b) { + const len = typeof a === "number" ? a : 0; + const callback = (0, util_1.validateCallback)(typeof a === "number" ? b : a); + this.wrapAsync(this.ftruncateBase, [fd, len], callback); + } + truncateBase(path2, len) { + const fd = this.openSync(path2, "r+"); + try { + this.ftruncateSync(fd, len); + } finally { + this.closeSync(fd); + } + } + /** + * `id` should be a file descriptor or a path. `id` as file descriptor will + * not be supported soon. + */ + truncateSync(id, len) { + if ((0, util_1.isFd)(id)) + return this.ftruncateSync(id, len); + this.truncateBase(id, len); + } + truncate(id, a, b) { + const len = typeof a === "number" ? a : 0; + const callback = (0, util_1.validateCallback)(typeof a === "number" ? b : a); + if ((0, util_1.isFd)(id)) + return this.ftruncate(id, len, callback); + this.wrapAsync(this.truncateBase, [id, len], callback); + } + futimesBase(fd, atime, mtime) { + const file = this.getFileByFdOrThrow(fd, "futimes"); + const node2 = file.node; + node2.atime = new Date(atime * 1e3); + node2.mtime = new Date(mtime * 1e3); + } + futimesSync(fd, atime, mtime) { + this.futimesBase(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)); + } + futimes(fd, atime, mtime, callback) { + this.wrapAsync(this.futimesBase, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback); + } + utimesBase(filename, atime, mtime) { + const fd = this.openSync(filename, "r"); + try { + this.futimesBase(fd, atime, mtime); + } finally { + this.closeSync(fd); + } + } + utimesSync(path2, atime, mtime) { + this.utimesBase((0, util_1.pathToFilename)(path2), toUnixTimestamp(atime), toUnixTimestamp(mtime)); + } + utimes(path2, atime, mtime, callback) { + this.wrapAsync(this.utimesBase, [(0, util_1.pathToFilename)(path2), toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback); + } + mkdirBase(filename, modeNum) { + const steps = filenameToSteps(filename); + if (!steps.length) { + throw (0, util_1.createError)(EEXIST, "mkdir", filename); + } + const dir = this.getLinkParentAsDirOrThrow(filename, "mkdir"); + const name = steps[steps.length - 1]; + if (dir.getChild(name)) + throw (0, util_1.createError)(EEXIST, "mkdir", filename); + dir.createChild(name, this.createNode(true, modeNum)); + } + /** + * Creates directory tree recursively. + * @param filename + * @param modeNum + */ + mkdirpBase(filename, modeNum) { + const fullPath = resolve(filename); + const fullPathSansSlash = fullPath.substring(1); + const steps = !fullPathSansSlash ? [] : fullPathSansSlash.split(sep); + let link2 = this.root; + let created = false; + for (let i = 0; i < steps.length; i++) { + const step = steps[i]; + if (!link2.getNode().isDirectory()) + throw (0, util_1.createError)(ENOTDIR, "mkdir", link2.getPath()); + const child = link2.getChild(step); + if (child) { + if (child.getNode().isDirectory()) + link2 = child; + else + throw (0, util_1.createError)(ENOTDIR, "mkdir", child.getPath()); + } else { + link2 = link2.createChild(step, this.createNode(true, modeNum)); + created = true; + } + } + return created ? fullPath : void 0; + } + mkdirSync(path2, options2) { + const opts = (0, options_1.getMkdirOptions)(options2); + const modeNum = (0, util_1.modeToNumber)(opts.mode, 511); + const filename = (0, util_1.pathToFilename)(path2); + if (opts.recursive) + return this.mkdirpBase(filename, modeNum); + this.mkdirBase(filename, modeNum); + } + mkdir(path2, a, b) { + const opts = (0, options_1.getMkdirOptions)(a); + const callback = (0, util_1.validateCallback)(typeof a === "function" ? a : b); + const modeNum = (0, util_1.modeToNumber)(opts.mode, 511); + const filename = (0, util_1.pathToFilename)(path2); + if (opts.recursive) + this.wrapAsync(this.mkdirpBase, [filename, modeNum], callback); + else + this.wrapAsync(this.mkdirBase, [filename, modeNum], callback); + } + mkdtempBase(prefix, encoding2, retry2 = 5) { + const filename = prefix + (0, util_1.genRndStr6)(); + try { + this.mkdirBase( + filename, + 511 + /* MODE.DIR */ + ); + return (0, encoding_1.strToEncoding)(filename, encoding2); + } catch (err) { + if (err.code === EEXIST) { + if (retry2 > 1) + return this.mkdtempBase(prefix, encoding2, retry2 - 1); + else + throw Error("Could not create temp dir."); + } else + throw err; + } + } + mkdtempSync(prefix, options2) { + const { encoding: encoding2 } = (0, options_1.getDefaultOpts)(options2); + if (!prefix || typeof prefix !== "string") + throw new TypeError("filename prefix is required"); + (0, util_1.nullCheck)(prefix); + return this.mkdtempBase(prefix, encoding2); + } + mkdtemp(prefix, a, b) { + const [{ encoding: encoding2 }, callback] = (0, options_1.getDefaultOptsAndCb)(a, b); + if (!prefix || typeof prefix !== "string") + throw new TypeError("filename prefix is required"); + if (!(0, util_1.nullCheck)(prefix)) + return; + this.wrapAsync(this.mkdtempBase, [prefix, encoding2], callback); + } + rmdirBase(filename, options2) { + const opts = (0, options_1.getRmdirOptions)(options2); + const link2 = this.getLinkAsDirOrThrow(filename, "rmdir"); + if (link2.length && !opts.recursive) + throw (0, util_1.createError)(ENOTEMPTY, "rmdir", filename); + this.deleteLink(link2); + } + rmdirSync(path2, options2) { + this.rmdirBase((0, util_1.pathToFilename)(path2), options2); + } + rmdir(path2, a, b) { + const opts = (0, options_1.getRmdirOptions)(a); + const callback = (0, util_1.validateCallback)(typeof a === "function" ? a : b); + this.wrapAsync(this.rmdirBase, [(0, util_1.pathToFilename)(path2), opts], callback); + } + rmBase(filename, options2 = {}) { + const link2 = this.getResolvedLink(filename); + if (!link2) { + if (!options2.force) + throw (0, util_1.createError)(ENOENT, "stat", filename); + return; + } + if (link2.getNode().isDirectory()) { + if (!options2.recursive) { + throw (0, util_1.createError)(ERR_FS_EISDIR, "rm", filename); + } + } + this.deleteLink(link2); + } + rmSync(path2, options2) { + this.rmBase((0, util_1.pathToFilename)(path2), options2); + } + rm(path2, a, b) { + const [opts, callback] = (0, options_1.getRmOptsAndCb)(a, b); + this.wrapAsync(this.rmBase, [(0, util_1.pathToFilename)(path2), opts], callback); + } + fchmodBase(fd, modeNum) { + const file = this.getFileByFdOrThrow(fd, "fchmod"); + file.chmod(modeNum); + } + fchmodSync(fd, mode) { + this.fchmodBase(fd, (0, util_1.modeToNumber)(mode)); + } + fchmod(fd, mode, callback) { + this.wrapAsync(this.fchmodBase, [fd, (0, util_1.modeToNumber)(mode)], callback); + } + chmodBase(filename, modeNum) { + const fd = this.openSync(filename, "r"); + try { + this.fchmodBase(fd, modeNum); + } finally { + this.closeSync(fd); + } + } + chmodSync(path2, mode) { + const modeNum = (0, util_1.modeToNumber)(mode); + const filename = (0, util_1.pathToFilename)(path2); + this.chmodBase(filename, modeNum); + } + chmod(path2, mode, callback) { + const modeNum = (0, util_1.modeToNumber)(mode); + const filename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.chmodBase, [filename, modeNum], callback); + } + lchmodBase(filename, modeNum) { + const fd = this.openBase(filename, O_RDWR, 0, false); + try { + this.fchmodBase(fd, modeNum); + } finally { + this.closeSync(fd); + } + } + lchmodSync(path2, mode) { + const modeNum = (0, util_1.modeToNumber)(mode); + const filename = (0, util_1.pathToFilename)(path2); + this.lchmodBase(filename, modeNum); + } + lchmod(path2, mode, callback) { + const modeNum = (0, util_1.modeToNumber)(mode); + const filename = (0, util_1.pathToFilename)(path2); + this.wrapAsync(this.lchmodBase, [filename, modeNum], callback); + } + fchownBase(fd, uid, gid) { + this.getFileByFdOrThrow(fd, "fchown").chown(uid, gid); + } + fchownSync(fd, uid, gid) { + validateUid(uid); + validateGid(gid); + this.fchownBase(fd, uid, gid); + } + fchown(fd, uid, gid, callback) { + validateUid(uid); + validateGid(gid); + this.wrapAsync(this.fchownBase, [fd, uid, gid], callback); + } + chownBase(filename, uid, gid) { + const link2 = this.getResolvedLinkOrThrow(filename, "chown"); + const node2 = link2.getNode(); + node2.chown(uid, gid); + } + chownSync(path2, uid, gid) { + validateUid(uid); + validateGid(gid); + this.chownBase((0, util_1.pathToFilename)(path2), uid, gid); + } + chown(path2, uid, gid, callback) { + validateUid(uid); + validateGid(gid); + this.wrapAsync(this.chownBase, [(0, util_1.pathToFilename)(path2), uid, gid], callback); + } + lchownBase(filename, uid, gid) { + this.getLinkOrThrow(filename, "lchown").getNode().chown(uid, gid); + } + lchownSync(path2, uid, gid) { + validateUid(uid); + validateGid(gid); + this.lchownBase((0, util_1.pathToFilename)(path2), uid, gid); + } + lchown(path2, uid, gid, callback) { + validateUid(uid); + validateGid(gid); + this.wrapAsync(this.lchownBase, [(0, util_1.pathToFilename)(path2), uid, gid], callback); + } + watchFile(path2, a, b) { + const filename = (0, util_1.pathToFilename)(path2); + let options2 = a; + let listener = b; + if (typeof options2 === "function") { + listener = a; + options2 = null; + } + if (typeof listener !== "function") { + throw Error('"watchFile()" requires a listener function'); + } + let interval = 5007; + let persistent = true; + if (options2 && typeof options2 === "object") { + if (typeof options2.interval === "number") + interval = options2.interval; + if (typeof options2.persistent === "boolean") + persistent = options2.persistent; + } + let watcher = this.statWatchers[filename]; + if (!watcher) { + watcher = new this.StatWatcher(); + watcher.start(filename, persistent, interval); + this.statWatchers[filename] = watcher; + } + watcher.addListener("change", listener); + return watcher; + } + unwatchFile(path2, listener) { + const filename = (0, util_1.pathToFilename)(path2); + const watcher = this.statWatchers[filename]; + if (!watcher) + return; + if (typeof listener === "function") { + watcher.removeListener("change", listener); + } else { + watcher.removeAllListeners("change"); + } + if (watcher.listenerCount("change") === 0) { + watcher.stop(); + delete this.statWatchers[filename]; + } + } + createReadStream(path2, options2) { + return new this.ReadStream(path2, options2); + } + createWriteStream(path2, options2) { + return new this.WriteStream(path2, options2); + } + // watch(path: PathLike): FSWatcher; + // watch(path: PathLike, options?: IWatchOptions | string): FSWatcher; + watch(path2, options2, listener) { + const filename = (0, util_1.pathToFilename)(path2); + let givenOptions = options2; + if (typeof options2 === "function") { + listener = options2; + givenOptions = null; + } + let { persistent, recursive, encoding: encoding2 } = (0, options_1.getDefaultOpts)(givenOptions); + if (persistent === void 0) + persistent = true; + if (recursive === void 0) + recursive = false; + const watcher = new this.FSWatcher(); + watcher.start(filename, persistent, recursive, encoding2); + if (listener) { + watcher.addListener("change", listener); + } + return watcher; + } + } + volume.Volume = Volume; + Volume.fd = 2147483647; + function emitStop(self2) { + self2.emit("stop"); + } + class StatWatcher extends events_1.EventEmitter { + constructor(vol) { + super(); + this.onInterval = () => { + try { + const stats = this.vol.statSync(this.filename); + if (this.hasChanged(stats)) { + this.emit("change", stats, this.prev); + this.prev = stats; + } + } finally { + this.loop(); + } + }; + this.vol = vol; + } + loop() { + this.timeoutRef = this.setTimeout(this.onInterval, this.interval); + } + hasChanged(stats) { + if (stats.mtimeMs > this.prev.mtimeMs) + return true; + if (stats.nlink !== this.prev.nlink) + return true; + return false; + } + start(path2, persistent = true, interval = 5007) { + this.filename = (0, util_1.pathToFilename)(path2); + this.setTimeout = persistent ? setTimeout.bind(typeof globalThis !== "undefined" ? globalThis : commonjsGlobal) : setTimeoutUnref_1.default; + this.interval = interval; + this.prev = this.vol.statSync(this.filename); + this.loop(); + } + stop() { + clearTimeout(this.timeoutRef); + (0, queueMicrotask_1.default)(() => { + emitStop.call(this, this); + }); + } + } + volume.StatWatcher = StatWatcher; + var pool; + function allocNewPool(poolSize) { + pool = (0, buffer_1.bufferAllocUnsafe)(poolSize); + pool.used = 0; + } + util2.inherits(FsReadStream, stream_1.Readable); + volume.ReadStream = FsReadStream; + function FsReadStream(vol, path2, options2) { + if (!(this instanceof FsReadStream)) + return new FsReadStream(vol, path2, options2); + this._vol = vol; + options2 = Object.assign({}, (0, options_1.getOptions)(options2, {})); + if (options2.highWaterMark === void 0) + options2.highWaterMark = 64 * 1024; + stream_1.Readable.call(this, options2); + this.path = (0, util_1.pathToFilename)(path2); + this.fd = options2.fd === void 0 ? null : options2.fd; + this.flags = options2.flags === void 0 ? "r" : options2.flags; + this.mode = options2.mode === void 0 ? 438 : options2.mode; + this.start = options2.start; + this.end = options2.end; + this.autoClose = options2.autoClose === void 0 ? true : options2.autoClose; + this.pos = void 0; + this.bytesRead = 0; + if (this.start !== void 0) { + if (typeof this.start !== "number") { + throw new TypeError('"start" option must be a Number'); + } + if (this.end === void 0) { + this.end = Infinity; + } else if (typeof this.end !== "number") { + throw new TypeError('"end" option must be a Number'); + } + if (this.start > this.end) { + throw new Error('"start" option must be <= "end" option'); + } + this.pos = this.start; + } + if (typeof this.fd !== "number") + this.open(); + this.on("end", function() { + if (this.autoClose) { + if (this.destroy) + this.destroy(); + } + }); + } + FsReadStream.prototype.open = function() { + var self2 = this; + this._vol.open(this.path, this.flags, this.mode, (er, fd) => { + if (er) { + if (self2.autoClose) { + if (self2.destroy) + self2.destroy(); + } + self2.emit("error", er); + return; + } + self2.fd = fd; + self2.emit("open", fd); + self2.read(); + }); + }; + FsReadStream.prototype._read = function(n) { + if (typeof this.fd !== "number") { + return this.once("open", function() { + this._read(n); + }); + } + if (this.destroyed) + return; + if (!pool || pool.length - pool.used < kMinPoolSpace) { + allocNewPool(this._readableState.highWaterMark); + } + var thisPool = pool; + var toRead = Math.min(pool.length - pool.used, n); + var start = pool.used; + if (this.pos !== void 0) + toRead = Math.min(this.end - this.pos + 1, toRead); + if (toRead <= 0) + return this.push(null); + var self2 = this; + this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread); + if (this.pos !== void 0) + this.pos += toRead; + pool.used += toRead; + function onread(er, bytesRead) { + if (er) { + if (self2.autoClose && self2.destroy) { + self2.destroy(); + } + self2.emit("error", er); + } else { + var b = null; + if (bytesRead > 0) { + self2.bytesRead += bytesRead; + b = thisPool.slice(start, start + bytesRead); + } + self2.push(b); + } + } + }; + FsReadStream.prototype._destroy = function(err, cb) { + this.close((err2) => { + cb(err || err2); + }); + }; + FsReadStream.prototype.close = function(cb) { + var _a2; + if (cb) + this.once("close", cb); + if (this.closed || typeof this.fd !== "number") { + if (typeof this.fd !== "number") { + this.once("open", closeOnOpen); + return; + } + return (0, queueMicrotask_1.default)(() => this.emit("close")); + } + if (typeof ((_a2 = this._readableState) === null || _a2 === void 0 ? void 0 : _a2.closed) === "boolean") { + this._readableState.closed = true; + } else { + this.closed = true; + } + this._vol.close(this.fd, (er) => { + if (er) + this.emit("error", er); + else + this.emit("close"); + }); + this.fd = null; + }; + function closeOnOpen(fd) { + this.close(); + } + util2.inherits(FsWriteStream, stream_1.Writable); + volume.WriteStream = FsWriteStream; + function FsWriteStream(vol, path2, options2) { + if (!(this instanceof FsWriteStream)) + return new FsWriteStream(vol, path2, options2); + this._vol = vol; + options2 = Object.assign({}, (0, options_1.getOptions)(options2, {})); + stream_1.Writable.call(this, options2); + this.path = (0, util_1.pathToFilename)(path2); + this.fd = options2.fd === void 0 ? null : options2.fd; + this.flags = options2.flags === void 0 ? "w" : options2.flags; + this.mode = options2.mode === void 0 ? 438 : options2.mode; + this.start = options2.start; + this.autoClose = options2.autoClose === void 0 ? true : !!options2.autoClose; + this.pos = void 0; + this.bytesWritten = 0; + this.pending = true; + if (this.start !== void 0) { + if (typeof this.start !== "number") { + throw new TypeError('"start" option must be a Number'); + } + if (this.start < 0) { + throw new Error('"start" must be >= zero'); + } + this.pos = this.start; + } + if (options2.encoding) + this.setDefaultEncoding(options2.encoding); + if (typeof this.fd !== "number") + this.open(); + this.once("finish", function() { + if (this.autoClose) { + this.close(); + } + }); + } + FsWriteStream.prototype.open = function() { + this._vol.open(this.path, this.flags, this.mode, (function(er, fd) { + if (er) { + if (this.autoClose && this.destroy) { + this.destroy(); + } + this.emit("error", er); + return; + } + this.fd = fd; + this.pending = false; + this.emit("open", fd); + }).bind(this)); + }; + FsWriteStream.prototype._write = function(data2, encoding2, cb) { + if (!(data2 instanceof buffer_1.Buffer || data2 instanceof Uint8Array)) + return this.emit("error", new Error("Invalid data")); + if (typeof this.fd !== "number") { + return this.once("open", function() { + this._write(data2, encoding2, cb); + }); + } + var self2 = this; + this._vol.write(this.fd, data2, 0, data2.length, this.pos, (er, bytes) => { + if (er) { + if (self2.autoClose && self2.destroy) { + self2.destroy(); + } + return cb(er); + } + self2.bytesWritten += bytes; + cb(); + }); + if (this.pos !== void 0) + this.pos += data2.length; + }; + FsWriteStream.prototype._writev = function(data2, cb) { + if (typeof this.fd !== "number") { + return this.once("open", function() { + this._writev(data2, cb); + }); + } + const self2 = this; + const len = data2.length; + const chunks = new Array(len); + var size = 0; + for (var i = 0; i < len; i++) { + var chunk = data2[i].chunk; + chunks[i] = chunk; + size += chunk.length; + } + const buf = buffer_1.Buffer.concat(chunks); + this._vol.write(this.fd, buf, 0, buf.length, this.pos, (er, bytes) => { + if (er) { + if (self2.destroy) + self2.destroy(); + return cb(er); + } + self2.bytesWritten += bytes; + cb(); + }); + if (this.pos !== void 0) + this.pos += size; + }; + FsWriteStream.prototype.close = function(cb) { + var _a2; + if (cb) + this.once("close", cb); + if (this.closed || typeof this.fd !== "number") { + if (typeof this.fd !== "number") { + this.once("open", closeOnOpen); + return; + } + return (0, queueMicrotask_1.default)(() => this.emit("close")); + } + if (typeof ((_a2 = this._writableState) === null || _a2 === void 0 ? void 0 : _a2.closed) === "boolean") { + this._writableState.closed = true; + } else { + this.closed = true; + } + this._vol.close(this.fd, (er) => { + if (er) + this.emit("error", er); + else + this.emit("close"); + }); + this.fd = null; + }; + FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy; + FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end; + class FSWatcher extends events_1.EventEmitter { + constructor(vol) { + super(); + this._filename = ""; + this._filenameEncoded = ""; + this._recursive = false; + this._encoding = encoding_1.ENCODING_UTF8; + this._listenerRemovers = /* @__PURE__ */ new Map(); + this._onParentChild = (link2) => { + if (link2.getName() === this._getName()) { + this._emit("rename"); + } + }; + this._emit = (type2) => { + this.emit("change", type2, this._filenameEncoded); + }; + this._persist = () => { + this._timer = setTimeout(this._persist, 1e6); + }; + this._vol = vol; + } + _getName() { + return this._steps[this._steps.length - 1]; + } + start(path2, persistent = true, recursive = false, encoding2 = encoding_1.ENCODING_UTF8) { + this._filename = (0, util_1.pathToFilename)(path2); + this._steps = filenameToSteps(this._filename); + this._filenameEncoded = (0, encoding_1.strToEncoding)(this._filename); + this._recursive = recursive; + this._encoding = encoding2; + try { + this._link = this._vol.getLinkOrThrow(this._filename, "FSWatcher"); + } catch (err) { + const error2 = new Error(`watch ${this._filename} ${err.code}`); + error2.code = err.code; + error2.errno = err.code; + throw error2; + } + const watchLinkNodeChanged = (link2) => { + var _a2; + const filepath = link2.getPath(); + const node2 = link2.getNode(); + const onNodeChange = () => { + let filename = relative(this._filename, filepath); + if (!filename) { + filename = this._getName(); + } + return this.emit("change", "change", filename); + }; + node2.on("change", onNodeChange); + const removers = (_a2 = this._listenerRemovers.get(node2.ino)) !== null && _a2 !== void 0 ? _a2 : []; + removers.push(() => node2.removeListener("change", onNodeChange)); + this._listenerRemovers.set(node2.ino, removers); + }; + const watchLinkChildrenChanged = (link2) => { + var _a2; + const node2 = link2.getNode(); + const onLinkChildAdd = (l) => { + this.emit("change", "rename", relative(this._filename, l.getPath())); + setTimeout(() => { + watchLinkNodeChanged(l); + watchLinkChildrenChanged(l); + }); + }; + const onLinkChildDelete = (l) => { + const removeLinkNodeListeners = (curLink) => { + const ino = curLink.getNode().ino; + const removers2 = this._listenerRemovers.get(ino); + if (removers2) { + removers2.forEach((r) => r()); + this._listenerRemovers.delete(ino); + } + for (const [name, childLink] of curLink.children.entries()) { + if (childLink && name !== "." && name !== "..") { + removeLinkNodeListeners(childLink); + } + } + }; + removeLinkNodeListeners(l); + this.emit("change", "rename", relative(this._filename, l.getPath())); + }; + for (const [name, childLink] of link2.children.entries()) { + if (childLink && name !== "." && name !== "..") { + watchLinkNodeChanged(childLink); + } + } + link2.on("child:add", onLinkChildAdd); + link2.on("child:delete", onLinkChildDelete); + const removers = (_a2 = this._listenerRemovers.get(node2.ino)) !== null && _a2 !== void 0 ? _a2 : []; + removers.push(() => { + link2.removeListener("child:add", onLinkChildAdd); + link2.removeListener("child:delete", onLinkChildDelete); + }); + if (recursive) { + for (const [name, childLink] of link2.children.entries()) { + if (childLink && name !== "." && name !== "..") { + watchLinkChildrenChanged(childLink); + } + } + } + }; + watchLinkNodeChanged(this._link); + watchLinkChildrenChanged(this._link); + const parent = this._link.parent; + if (parent) { + parent.setMaxListeners(parent.getMaxListeners() + 1); + parent.on("child:delete", this._onParentChild); + } + if (persistent) + this._persist(); + } + close() { + clearTimeout(this._timer); + this._listenerRemovers.forEach((removers) => { + removers.forEach((r) => r()); + }); + this._listenerRemovers.clear(); + const parent = this._link.parent; + if (parent) { + parent.removeListener("child:delete", this._onParentChild); + } + } + } + volume.FSWatcher = FSWatcher; + return volume; +} +var fsSynchronousApiList = {}; +var hasRequiredFsSynchronousApiList; +function requireFsSynchronousApiList() { + if (hasRequiredFsSynchronousApiList) return fsSynchronousApiList; + hasRequiredFsSynchronousApiList = 1; + Object.defineProperty(fsSynchronousApiList, "__esModule", { value: true }); + fsSynchronousApiList.fsSynchronousApiList = void 0; + fsSynchronousApiList.fsSynchronousApiList = [ + "accessSync", + "appendFileSync", + "chmodSync", + "chownSync", + "closeSync", + "copyFileSync", + "existsSync", + "fchmodSync", + "fchownSync", + "fdatasyncSync", + "fstatSync", + "fsyncSync", + "ftruncateSync", + "futimesSync", + "lchmodSync", + "lchownSync", + "linkSync", + "lstatSync", + "mkdirSync", + "mkdtempSync", + "openSync", + "readdirSync", + "readFileSync", + "readlinkSync", + "readSync", + "readvSync", + "realpathSync", + "renameSync", + "rmdirSync", + "rmSync", + "statSync", + "symlinkSync", + "truncateSync", + "unlinkSync", + "utimesSync", + "writeFileSync", + "writeSync", + "writevSync" + // 'cpSync', + // 'lutimesSync', + // 'statfsSync', + ]; + return fsSynchronousApiList; +} +var fsCallbackApiList = {}; +var hasRequiredFsCallbackApiList; +function requireFsCallbackApiList() { + if (hasRequiredFsCallbackApiList) return fsCallbackApiList; + hasRequiredFsCallbackApiList = 1; + Object.defineProperty(fsCallbackApiList, "__esModule", { value: true }); + fsCallbackApiList.fsCallbackApiList = void 0; + fsCallbackApiList.fsCallbackApiList = [ + "access", + "appendFile", + "chmod", + "chown", + "close", + "copyFile", + "createReadStream", + "createWriteStream", + "exists", + "fchmod", + "fchown", + "fdatasync", + "fstat", + "fsync", + "ftruncate", + "futimes", + "lchmod", + "lchown", + "link", + "lstat", + "mkdir", + "mkdtemp", + "open", + "read", + "readv", + "readdir", + "readFile", + "readlink", + "realpath", + "rename", + "rm", + "rmdir", + "stat", + "symlink", + "truncate", + "unlink", + "unwatchFile", + "utimes", + "watch", + "watchFile", + "write", + "writev", + "writeFile" + ]; + return fsCallbackApiList; +} +var hasRequiredLib$1; +function requireLib$1() { + if (hasRequiredLib$1) return lib$2.exports; + hasRequiredLib$1 = 1; + (function(module, exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memfs = exports.fs = exports.createFsFromVolume = exports.vol = exports.Volume = void 0; + const Stats_1 = requireStats(); + const Dirent_1 = requireDirent(); + const volume_1 = requireVolume(); + const constants_1 = requireConstants$7(); + const fsSynchronousApiList_1 = requireFsSynchronousApiList(); + const fsCallbackApiList_1 = requireFsCallbackApiList(); + const { F_OK, R_OK, W_OK, X_OK } = constants_1.constants; + exports.Volume = volume_1.Volume; + exports.vol = new volume_1.Volume(); + function createFsFromVolume(vol) { + const fs2 = { F_OK, R_OK, W_OK, X_OK, constants: constants_1.constants, Stats: Stats_1.default, Dirent: Dirent_1.default }; + for (const method of fsSynchronousApiList_1.fsSynchronousApiList) + if (typeof vol[method] === "function") + fs2[method] = vol[method].bind(vol); + for (const method of fsCallbackApiList_1.fsCallbackApiList) + if (typeof vol[method] === "function") + fs2[method] = vol[method].bind(vol); + fs2.StatWatcher = vol.StatWatcher; + fs2.FSWatcher = vol.FSWatcher; + fs2.WriteStream = vol.WriteStream; + fs2.ReadStream = vol.ReadStream; + fs2.promises = vol.promises; + fs2._toUnixTimestamp = volume_1.toUnixTimestamp; + fs2.__vol = vol; + return fs2; + } + exports.createFsFromVolume = createFsFromVolume; + exports.fs = createFsFromVolume(exports.vol); + const memfs = (json = {}, cwd = "/") => { + const vol = exports.Volume.fromNestedJSON(json, cwd); + const fs2 = createFsFromVolume(vol); + return { fs: fs2, vol }; + }; + exports.memfs = memfs; + module.exports = Object.assign(Object.assign({}, module.exports), exports.fs); + module.exports.semantic = true; + })(lib$2, lib$2.exports); + return lib$2.exports; +} +var libExports$1 = requireLib$1(); +const { fs } = libExports$1.memfs({ "/tmp": null }); +const { + appendFile, + appendFileSync, + access, + accessSync, + chown, + chownSync, + chmod, + chmodSync, + close, + closeSync, + copyFile, + copyFileSync, + cp, + cpSync, + createReadStream, + createWriteStream, + exists, + existsSync, + fchown, + fchownSync, + fchmod, + fchmodSync, + fdatasync, + fdatasyncSync, + fstat, + fstatSync, + fsync, + fsyncSync, + ftruncate, + ftruncateSync, + futimes, + futimesSync, + lchown, + lchownSync, + lchmod, + lchmodSync, + link, + linkSync, + lstat, + lstatSync, + lutimes, + lutimesSync, + mkdir, + mkdirSync, + mkdtemp, + mkdtempSync, + open: open$2, + openSync, + opendir, + opendirSync, + readdir, + readdirSync, + read, + readSync, + readv, + readvSync, + readFile, + readFileSync, + readlink, + readlinkSync, + realpath, + realpathSync, + rename, + renameSync, + rm, + rmSync, + rmdir, + rmdirSync, + stat, + statfs, + statSync, + statfsSync, + symlink, + symlinkSync, + truncate, + truncateSync, + unwatchFile, + unlink, + unlinkSync, + utimes, + utimesSync, + watch, + watchFile, + writeFile, + writeFileSync, + write, + writeSync, + writev, + writevSync, + Dirent, + Stats, + ReadStream, + WriteStream, + constants: constants$6, + promises: promises$1 +} = fs; +const fs$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Dirent, + ReadStream, + Stats, + WriteStream, + access, + accessSync, + appendFile, + appendFileSync, + chmod, + chmodSync, + chown, + chownSync, + close, + closeSync, + constants: constants$6, + copyFile, + copyFileSync, + cp, + cpSync, + createReadStream, + createWriteStream, + default: fs, + exists, + existsSync, + fchmod, + fchmodSync, + fchown, + fchownSync, + fdatasync, + fdatasyncSync, + fstat, + fstatSync, + fsync, + fsyncSync, + ftruncate, + ftruncateSync, + futimes, + futimesSync, + lchmod, + lchmodSync, + lchown, + lchownSync, + link, + linkSync, + lstat, + lstatSync, + lutimes, + lutimesSync, + mkdir, + mkdirSync, + mkdtemp, + mkdtempSync, + open: open$2, + openSync, + opendir, + opendirSync, + promises: promises$1, + read, + readFile, + readFileSync, + readSync, + readdir, + readdirSync, + readlink, + readlinkSync, + readv, + readvSync, + realpath, + realpathSync, + rename, + renameSync, + rm, + rmSync, + rmdir, + rmdirSync, + stat, + statSync, + statfs, + statfsSync, + symlink, + symlinkSync, + truncate, + truncateSync, + unlink, + unlinkSync, + unwatchFile, + utimes, + utimesSync, + watch, + watchFile, + write, + writeFile, + writeFileSync, + writeSync, + writev, + writevSync +}, Symbol.toStringTag, { value: "Module" })); +self.global = self; +self.__dirname = "/"; +class ValidationError extends Error { +} +const scheme = {}; +function findValidator(type2, method, kind) { + const validator = maybeFindValidator(type2, method, kind); + if (!validator) + throw new ValidationError(`Unknown scheme for ${kind}: ${type2}.${method}`); + return validator; +} +function maybeFindValidator(type2, method, kind) { + const schemeName = type2 + (kind === "Initializer" ? "" : method[0].toUpperCase() + method.substring(1)) + kind; + return scheme[schemeName]; +} +function createMetadataValidator() { + return tOptional(scheme["Metadata"]); +} +const tNumber = (arg, path2, context) => { + if (arg instanceof Number) + return arg.valueOf(); + if (typeof arg === "number") + return arg; + throw new ValidationError(`${path2}: expected number, got ${typeof arg}`); +}; +const tBoolean = (arg, path2, context) => { + if (arg instanceof Boolean) + return arg.valueOf(); + if (typeof arg === "boolean") + return arg; + throw new ValidationError(`${path2}: expected boolean, got ${typeof arg}`); +}; +const tString = (arg, path2, context) => { + if (arg instanceof String) + return arg.valueOf(); + if (typeof arg === "string") + return arg; + throw new ValidationError(`${path2}: expected string, got ${typeof arg}`); +}; +const tBinary = (arg, path2, context) => { + if (context.binary === "fromBase64") { + if (arg instanceof String) + return Buffer.from(arg.valueOf(), "base64"); + if (typeof arg === "string") + return Buffer.from(arg, "base64"); + throw new ValidationError(`${path2}: expected base64-encoded buffer, got ${typeof arg}`); + } + if (context.binary === "toBase64") { + if (!(arg instanceof Buffer)) + throw new ValidationError(`${path2}: expected Buffer, got ${typeof arg}`); + return arg.toString("base64"); + } + if (context.binary === "buffer") { + if (!(arg instanceof Buffer)) + throw new ValidationError(`${path2}: expected Buffer, got ${typeof arg}`); + return arg; + } + throw new ValidationError(`Unsupported binary behavior "${context.binary}"`); +}; +const tAny = (arg, path2, context) => { + return arg; +}; +const tOptional = (v) => { + return (arg, path2, context) => { + if (Object.is(arg, void 0)) + return arg; + return v(arg, path2, context); + }; +}; +const tArray = (v) => { + return (arg, path2, context) => { + if (!Array.isArray(arg)) + throw new ValidationError(`${path2}: expected array, got ${typeof arg}`); + return arg.map((x, index2) => v(x, path2 + "[" + index2 + "]", context)); + }; +}; +const tObject = (s) => { + return (arg, path2, context) => { + if (Object.is(arg, null)) + throw new ValidationError(`${path2}: expected object, got null`); + if (typeof arg !== "object") + throw new ValidationError(`${path2}: expected object, got ${typeof arg}`); + const result = {}; + for (const [key2, v] of Object.entries(s)) { + const value = v(arg[key2], path2 ? path2 + "." + key2 : key2, context); + if (!Object.is(value, void 0)) + result[key2] = value; + } + if (context.isUnderTest()) { + for (const [key2, value] of Object.entries(arg)) { + if (key2.startsWith("__testHook")) + result[key2] = value; + } + } + return result; + }; +}; +const tEnum = (e) => { + return (arg, path2, context) => { + if (!e.includes(arg)) + throw new ValidationError(`${path2}: expected one of (${e.join("|")})`); + return arg; + }; +}; +const tChannel = (names) => { + return (arg, path2, context) => { + return context.tChannelImpl(names, arg, path2, context); + }; +}; +const tType = (name) => { + return (arg, path2, context) => { + const v = scheme[name]; + if (!v) + throw new ValidationError(path2 + ': unknown type "' + name + '"'); + return v(arg, path2, context); + }; +}; +scheme.StackFrame = tObject({ + file: tString, + line: tNumber, + column: tNumber, + function: tOptional(tString) +}); +scheme.Metadata = tObject({ + location: tOptional(tObject({ + file: tString, + line: tOptional(tNumber), + column: tOptional(tNumber) + })), + title: tOptional(tString), + internal: tOptional(tBoolean), + stepId: tOptional(tString) +}); +scheme.ClientSideCallMetadata = tObject({ + id: tNumber, + stack: tOptional(tArray(tType("StackFrame"))) +}); +scheme.Point = tObject({ + x: tNumber, + y: tNumber +}); +scheme.Rect = tObject({ + x: tNumber, + y: tNumber, + width: tNumber, + height: tNumber +}); +scheme.SerializedValue = tObject({ + n: tOptional(tNumber), + b: tOptional(tBoolean), + s: tOptional(tString), + v: tOptional(tEnum(["null", "undefined", "NaN", "Infinity", "-Infinity", "-0"])), + d: tOptional(tString), + u: tOptional(tString), + bi: tOptional(tString), + ta: tOptional(tObject({ + b: tBinary, + k: tEnum(["i8", "ui8", "ui8c", "i16", "ui16", "i32", "ui32", "f32", "f64", "bi64", "bui64"]) + })), + e: tOptional(tObject({ + m: tString, + n: tString, + s: tString + })), + r: tOptional(tObject({ + p: tString, + f: tString + })), + a: tOptional(tArray(tType("SerializedValue"))), + o: tOptional(tArray(tObject({ + k: tString, + v: tType("SerializedValue") + }))), + h: tOptional(tNumber), + id: tOptional(tNumber), + ref: tOptional(tNumber) +}); +scheme.SerializedArgument = tObject({ + value: tType("SerializedValue"), + handles: tArray(tChannel("*")) +}); +scheme.ExpectedTextValue = tObject({ + string: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + matchSubstring: tOptional(tBoolean), + ignoreCase: tOptional(tBoolean), + normalizeWhiteSpace: tOptional(tBoolean) +}); +scheme.SelectorEngine = tObject({ + name: tString, + source: tString, + contentScript: tOptional(tBoolean) +}); +scheme.AXNode = tObject({ + role: tString, + name: tString, + valueString: tOptional(tString), + valueNumber: tOptional(tNumber), + description: tOptional(tString), + keyshortcuts: tOptional(tString), + roledescription: tOptional(tString), + valuetext: tOptional(tString), + disabled: tOptional(tBoolean), + expanded: tOptional(tBoolean), + focused: tOptional(tBoolean), + modal: tOptional(tBoolean), + multiline: tOptional(tBoolean), + multiselectable: tOptional(tBoolean), + readonly: tOptional(tBoolean), + required: tOptional(tBoolean), + selected: tOptional(tBoolean), + checked: tOptional(tEnum(["checked", "unchecked", "mixed"])), + pressed: tOptional(tEnum(["pressed", "released", "mixed"])), + level: tOptional(tNumber), + valuemin: tOptional(tNumber), + valuemax: tOptional(tNumber), + autocomplete: tOptional(tString), + haspopup: tOptional(tString), + invalid: tOptional(tString), + orientation: tOptional(tString), + children: tOptional(tArray(tType("AXNode"))) +}); +scheme.SetNetworkCookie = tObject({ + name: tString, + value: tString, + url: tOptional(tString), + domain: tOptional(tString), + path: tOptional(tString), + expires: tOptional(tNumber), + httpOnly: tOptional(tBoolean), + secure: tOptional(tBoolean), + sameSite: tOptional(tEnum(["Strict", "Lax", "None"])) +}); +scheme.NetworkCookie = tObject({ + name: tString, + value: tString, + domain: tString, + path: tString, + expires: tNumber, + httpOnly: tBoolean, + secure: tBoolean, + sameSite: tEnum(["Strict", "Lax", "None"]) +}); +scheme.NameValue = tObject({ + name: tString, + value: tString +}); +scheme.IndexedDBDatabase = tObject({ + name: tString, + version: tNumber, + stores: tArray(tObject({ + name: tString, + autoIncrement: tBoolean, + keyPath: tOptional(tString), + keyPathArray: tOptional(tArray(tString)), + records: tArray(tObject({ + key: tOptional(tAny), + keyEncoded: tOptional(tAny), + value: tOptional(tAny), + valueEncoded: tOptional(tAny) + })), + indexes: tArray(tObject({ + name: tString, + keyPath: tOptional(tString), + keyPathArray: tOptional(tArray(tString)), + multiEntry: tBoolean, + unique: tBoolean + })) + })) +}); +scheme.SetOriginStorage = tObject({ + origin: tString, + localStorage: tArray(tType("NameValue")), + indexedDB: tOptional(tArray(tType("IndexedDBDatabase"))) +}); +scheme.OriginStorage = tObject({ + origin: tString, + localStorage: tArray(tType("NameValue")), + indexedDB: tOptional(tArray(tType("IndexedDBDatabase"))) +}); +scheme.SerializedError = tObject({ + error: tOptional(tObject({ + message: tString, + name: tString, + stack: tOptional(tString) + })), + value: tOptional(tType("SerializedValue")) +}); +scheme.RecordHarOptions = tObject({ + zip: tOptional(tBoolean), + content: tOptional(tEnum(["embed", "attach", "omit"])), + mode: tOptional(tEnum(["full", "minimal"])), + urlGlob: tOptional(tString), + urlRegexSource: tOptional(tString), + urlRegexFlags: tOptional(tString) +}); +scheme.FormField = tObject({ + name: tString, + value: tOptional(tString), + file: tOptional(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + })) +}); +scheme.APIRequestContextInitializer = tObject({ + tracing: tChannel(["Tracing"]) +}); +scheme.APIRequestContextFetchParams = tObject({ + url: tString, + encodedParams: tOptional(tString), + params: tOptional(tArray(tType("NameValue"))), + method: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + postData: tOptional(tBinary), + jsonData: tOptional(tString), + formData: tOptional(tArray(tType("NameValue"))), + multipartData: tOptional(tArray(tType("FormField"))), + timeout: tNumber, + failOnStatusCode: tOptional(tBoolean), + ignoreHTTPSErrors: tOptional(tBoolean), + maxRedirects: tOptional(tNumber), + maxRetries: tOptional(tNumber) +}); +scheme.APIRequestContextFetchResult = tObject({ + response: tType("APIResponse") +}); +scheme.APIRequestContextFetchResponseBodyParams = tObject({ + fetchUid: tString +}); +scheme.APIRequestContextFetchResponseBodyResult = tObject({ + binary: tOptional(tBinary) +}); +scheme.APIRequestContextFetchLogParams = tObject({ + fetchUid: tString +}); +scheme.APIRequestContextFetchLogResult = tObject({ + log: tArray(tString) +}); +scheme.APIRequestContextStorageStateParams = tObject({ + indexedDB: tOptional(tBoolean) +}); +scheme.APIRequestContextStorageStateResult = tObject({ + cookies: tArray(tType("NetworkCookie")), + origins: tArray(tType("OriginStorage")) +}); +scheme.APIRequestContextDisposeAPIResponseParams = tObject({ + fetchUid: tString +}); +scheme.APIRequestContextDisposeAPIResponseResult = tOptional(tObject({})); +scheme.APIRequestContextDisposeParams = tObject({ + reason: tOptional(tString) +}); +scheme.APIRequestContextDisposeResult = tOptional(tObject({})); +scheme.APIResponse = tObject({ + fetchUid: tString, + url: tString, + status: tNumber, + statusText: tString, + headers: tArray(tType("NameValue")) +}); +scheme.LifecycleEvent = tEnum(["load", "domcontentloaded", "networkidle", "commit"]); +scheme.LocalUtilsInitializer = tObject({ + deviceDescriptors: tArray(tObject({ + name: tString, + descriptor: tObject({ + userAgent: tString, + viewport: tObject({ + width: tNumber, + height: tNumber + }), + screen: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + deviceScaleFactor: tNumber, + isMobile: tBoolean, + hasTouch: tBoolean, + defaultBrowserType: tEnum(["chromium", "firefox", "webkit"]) + }) + })) +}); +scheme.LocalUtilsZipParams = tObject({ + zipFile: tString, + entries: tArray(tType("NameValue")), + stacksId: tOptional(tString), + mode: tEnum(["write", "append"]), + includeSources: tBoolean +}); +scheme.LocalUtilsZipResult = tOptional(tObject({})); +scheme.LocalUtilsHarOpenParams = tObject({ + file: tString +}); +scheme.LocalUtilsHarOpenResult = tObject({ + harId: tOptional(tString), + error: tOptional(tString) +}); +scheme.LocalUtilsHarLookupParams = tObject({ + harId: tString, + url: tString, + method: tString, + headers: tArray(tType("NameValue")), + postData: tOptional(tBinary), + isNavigationRequest: tBoolean +}); +scheme.LocalUtilsHarLookupResult = tObject({ + action: tEnum(["error", "redirect", "fulfill", "noentry"]), + message: tOptional(tString), + redirectURL: tOptional(tString), + status: tOptional(tNumber), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tBinary) +}); +scheme.LocalUtilsHarCloseParams = tObject({ + harId: tString +}); +scheme.LocalUtilsHarCloseResult = tOptional(tObject({})); +scheme.LocalUtilsHarUnzipParams = tObject({ + zipFile: tString, + harFile: tString +}); +scheme.LocalUtilsHarUnzipResult = tOptional(tObject({})); +scheme.LocalUtilsConnectParams = tObject({ + wsEndpoint: tString, + headers: tOptional(tAny), + exposeNetwork: tOptional(tString), + slowMo: tOptional(tNumber), + timeout: tNumber, + socksProxyRedirectPortForTest: tOptional(tNumber) +}); +scheme.LocalUtilsConnectResult = tObject({ + pipe: tChannel(["JsonPipe"]), + headers: tArray(tType("NameValue")) +}); +scheme.LocalUtilsTracingStartedParams = tObject({ + tracesDir: tOptional(tString), + traceName: tString +}); +scheme.LocalUtilsTracingStartedResult = tObject({ + stacksId: tString +}); +scheme.LocalUtilsAddStackToTracingNoReplyParams = tObject({ + callData: tType("ClientSideCallMetadata") +}); +scheme.LocalUtilsAddStackToTracingNoReplyResult = tOptional(tObject({})); +scheme.LocalUtilsTraceDiscardedParams = tObject({ + stacksId: tString +}); +scheme.LocalUtilsTraceDiscardedResult = tOptional(tObject({})); +scheme.LocalUtilsGlobToRegexParams = tObject({ + glob: tString, + baseURL: tOptional(tString), + webSocketUrl: tOptional(tBoolean) +}); +scheme.LocalUtilsGlobToRegexResult = tObject({ + regex: tString +}); +scheme.RootInitializer = tOptional(tObject({})); +scheme.RootInitializeParams = tObject({ + sdkLanguage: tEnum(["javascript", "python", "java", "csharp"]) +}); +scheme.RootInitializeResult = tObject({ + playwright: tChannel(["Playwright"]) +}); +scheme.PlaywrightInitializer = tObject({ + chromium: tChannel(["BrowserType"]), + firefox: tChannel(["BrowserType"]), + webkit: tChannel(["BrowserType"]), + bidiChromium: tChannel(["BrowserType"]), + bidiFirefox: tChannel(["BrowserType"]), + android: tChannel(["Android"]), + electron: tChannel(["Electron"]), + utils: tOptional(tChannel(["LocalUtils"])), + preLaunchedBrowser: tOptional(tChannel(["Browser"])), + preConnectedAndroidDevice: tOptional(tChannel(["AndroidDevice"])), + socksSupport: tOptional(tChannel(["SocksSupport"])) +}); +scheme.PlaywrightNewRequestParams = tObject({ + baseURL: tOptional(tString), + userAgent: tOptional(tString), + ignoreHTTPSErrors: tOptional(tBoolean), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + failOnStatusCode: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + maxRedirects: tOptional(tNumber), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + })), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("NetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))) + })), + tracesDir: tOptional(tString) +}); +scheme.PlaywrightNewRequestResult = tObject({ + request: tChannel(["APIRequestContext"]) +}); +scheme.RecorderSource = tObject({ + isRecorded: tBoolean, + id: tString, + label: tString, + text: tString, + language: tString, + highlight: tArray(tObject({ + line: tNumber, + type: tString + })), + revealLine: tOptional(tNumber), + group: tOptional(tString) +}); +scheme.DebugControllerInitializer = tOptional(tObject({})); +scheme.DebugControllerInspectRequestedEvent = tObject({ + selector: tString, + locator: tString, + ariaSnapshot: tString +}); +scheme.DebugControllerSetModeRequestedEvent = tObject({ + mode: tString +}); +scheme.DebugControllerStateChangedEvent = tObject({ + pageCount: tNumber +}); +scheme.DebugControllerSourceChangedEvent = tObject({ + text: tString, + header: tOptional(tString), + footer: tOptional(tString), + actions: tOptional(tArray(tString)) +}); +scheme.DebugControllerPausedEvent = tObject({ + paused: tBoolean +}); +scheme.DebugControllerInitializeParams = tObject({ + codegenId: tString, + sdkLanguage: tEnum(["javascript", "python", "java", "csharp"]) +}); +scheme.DebugControllerInitializeResult = tOptional(tObject({})); +scheme.DebugControllerSetReportStateChangedParams = tObject({ + enabled: tBoolean +}); +scheme.DebugControllerSetReportStateChangedResult = tOptional(tObject({})); +scheme.DebugControllerResetForReuseParams = tOptional(tObject({})); +scheme.DebugControllerResetForReuseResult = tOptional(tObject({})); +scheme.DebugControllerNavigateParams = tObject({ + url: tString +}); +scheme.DebugControllerNavigateResult = tOptional(tObject({})); +scheme.DebugControllerSetRecorderModeParams = tObject({ + mode: tEnum(["inspecting", "recording", "none"]), + testIdAttributeName: tOptional(tString) +}); +scheme.DebugControllerSetRecorderModeResult = tOptional(tObject({})); +scheme.DebugControllerHighlightParams = tObject({ + selector: tOptional(tString), + ariaTemplate: tOptional(tString) +}); +scheme.DebugControllerHighlightResult = tOptional(tObject({})); +scheme.DebugControllerHideHighlightParams = tOptional(tObject({})); +scheme.DebugControllerHideHighlightResult = tOptional(tObject({})); +scheme.DebugControllerResumeParams = tOptional(tObject({})); +scheme.DebugControllerResumeResult = tOptional(tObject({})); +scheme.DebugControllerKillParams = tOptional(tObject({})); +scheme.DebugControllerKillResult = tOptional(tObject({})); +scheme.DebugControllerCloseAllBrowsersParams = tOptional(tObject({})); +scheme.DebugControllerCloseAllBrowsersResult = tOptional(tObject({})); +scheme.SocksSupportInitializer = tOptional(tObject({})); +scheme.SocksSupportSocksRequestedEvent = tObject({ + uid: tString, + host: tString, + port: tNumber +}); +scheme.SocksSupportSocksDataEvent = tObject({ + uid: tString, + data: tBinary +}); +scheme.SocksSupportSocksClosedEvent = tObject({ + uid: tString +}); +scheme.SocksSupportSocksConnectedParams = tObject({ + uid: tString, + host: tString, + port: tNumber +}); +scheme.SocksSupportSocksConnectedResult = tOptional(tObject({})); +scheme.SocksSupportSocksFailedParams = tObject({ + uid: tString, + errorCode: tString +}); +scheme.SocksSupportSocksFailedResult = tOptional(tObject({})); +scheme.SocksSupportSocksDataParams = tObject({ + uid: tString, + data: tBinary +}); +scheme.SocksSupportSocksDataResult = tOptional(tObject({})); +scheme.SocksSupportSocksErrorParams = tObject({ + uid: tString, + error: tString +}); +scheme.SocksSupportSocksErrorResult = tOptional(tObject({})); +scheme.SocksSupportSocksEndParams = tObject({ + uid: tString +}); +scheme.SocksSupportSocksEndResult = tOptional(tObject({})); +scheme.BrowserTypeInitializer = tObject({ + executablePath: tString, + name: tString +}); +scheme.BrowserTypeLaunchParams = tObject({ + channel: tOptional(tString), + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + ignoreAllDefaultArgs: tOptional(tBoolean), + ignoreDefaultArgs: tOptional(tArray(tString)), + assistantMode: tOptional(tBoolean), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + timeout: tNumber, + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + devtools: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tNumber), + slowMo: tOptional(tNumber) +}); +scheme.BrowserTypeLaunchResult = tObject({ + browser: tChannel(["Browser"]) +}); +scheme.BrowserTypeLaunchPersistentContextParams = tObject({ + channel: tOptional(tString), + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + ignoreAllDefaultArgs: tOptional(tBoolean), + ignoreDefaultArgs: tOptional(tArray(tString)), + assistantMode: tOptional(tBoolean), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + timeout: tNumber, + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + devtools: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tNumber), + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + screen: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + })), + deviceScaleFactor: tOptional(tNumber), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tString, + size: tOptional(tObject({ + width: tNumber, + height: tNumber + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + userDataDir: tString, + slowMo: tOptional(tNumber) +}); +scheme.BrowserTypeLaunchPersistentContextResult = tObject({ + browser: tChannel(["Browser"]), + context: tChannel(["BrowserContext"]) +}); +scheme.BrowserTypeConnectOverCDPParams = tObject({ + endpointURL: tString, + headers: tOptional(tArray(tType("NameValue"))), + slowMo: tOptional(tNumber), + timeout: tNumber +}); +scheme.BrowserTypeConnectOverCDPResult = tObject({ + browser: tChannel(["Browser"]), + defaultContext: tOptional(tChannel(["BrowserContext"])) +}); +scheme.BrowserInitializer = tObject({ + version: tString, + name: tString +}); +scheme.BrowserContextEvent = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.BrowserCloseEvent = tOptional(tObject({})); +scheme.BrowserCloseParams = tObject({ + reason: tOptional(tString) +}); +scheme.BrowserCloseResult = tOptional(tObject({})); +scheme.BrowserKillForTestsParams = tOptional(tObject({})); +scheme.BrowserKillForTestsResult = tOptional(tObject({})); +scheme.BrowserDefaultUserAgentForTestParams = tOptional(tObject({})); +scheme.BrowserDefaultUserAgentForTestResult = tObject({ + userAgent: tString +}); +scheme.BrowserNewContextParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + screen: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + })), + deviceScaleFactor: tOptional(tNumber), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tString, + size: tOptional(tObject({ + width: tNumber, + height: tNumber + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))) + })) +}); +scheme.BrowserNewContextResult = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.BrowserNewContextForReuseParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + screen: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + })), + deviceScaleFactor: tOptional(tNumber), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tString, + size: tOptional(tObject({ + width: tNumber, + height: tNumber + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))) + })) +}); +scheme.BrowserNewContextForReuseResult = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.BrowserStopPendingOperationsParams = tObject({ + reason: tString +}); +scheme.BrowserStopPendingOperationsResult = tOptional(tObject({})); +scheme.BrowserNewBrowserCDPSessionParams = tOptional(tObject({})); +scheme.BrowserNewBrowserCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) +}); +scheme.BrowserStartTracingParams = tObject({ + page: tOptional(tChannel(["Page"])), + screenshots: tOptional(tBoolean), + categories: tOptional(tArray(tString)) +}); +scheme.BrowserStartTracingResult = tOptional(tObject({})); +scheme.BrowserStopTracingParams = tOptional(tObject({})); +scheme.BrowserStopTracingResult = tObject({ + artifact: tChannel(["Artifact"]) +}); +scheme.EventTargetInitializer = tOptional(tObject({})); +scheme.EventTargetWaitForEventInfoParams = tObject({ + info: tObject({ + waitId: tString, + phase: tEnum(["before", "after", "log"]), + event: tOptional(tString), + message: tOptional(tString), + error: tOptional(tString) + }) +}); +scheme.BrowserContextWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); +scheme.PageWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); +scheme.WebSocketWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); +scheme.ElectronApplicationWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); +scheme.AndroidDeviceWaitForEventInfoParams = tType("EventTargetWaitForEventInfoParams"); +scheme.EventTargetWaitForEventInfoResult = tOptional(tObject({})); +scheme.BrowserContextWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); +scheme.PageWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); +scheme.WebSocketWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); +scheme.ElectronApplicationWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); +scheme.AndroidDeviceWaitForEventInfoResult = tType("EventTargetWaitForEventInfoResult"); +scheme.BrowserContextInitializer = tObject({ + isChromium: tBoolean, + requestContext: tChannel(["APIRequestContext"]), + tracing: tChannel(["Tracing"]), + options: tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + screen: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + })), + deviceScaleFactor: tOptional(tNumber), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tString, + size: tOptional(tObject({ + width: tNumber, + height: tNumber + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString) + }) +}); +scheme.BrowserContextBindingCallEvent = tObject({ + binding: tChannel(["BindingCall"]) +}); +scheme.BrowserContextConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tNumber, + columnNumber: tNumber + }), + page: tChannel(["Page"]) +}); +scheme.BrowserContextCloseEvent = tOptional(tObject({})); +scheme.BrowserContextDialogEvent = tObject({ + dialog: tChannel(["Dialog"]) +}); +scheme.BrowserContextPageEvent = tObject({ + page: tChannel(["Page"]) +}); +scheme.BrowserContextPageErrorEvent = tObject({ + error: tType("SerializedError"), + page: tChannel(["Page"]) +}); +scheme.BrowserContextRouteEvent = tObject({ + route: tChannel(["Route"]) +}); +scheme.BrowserContextWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) +}); +scheme.BrowserContextVideoEvent = tObject({ + artifact: tChannel(["Artifact"]) +}); +scheme.BrowserContextBackgroundPageEvent = tObject({ + page: tChannel(["Page"]) +}); +scheme.BrowserContextServiceWorkerEvent = tObject({ + worker: tChannel(["Worker"]) +}); +scheme.BrowserContextRequestEvent = tObject({ + request: tChannel(["Request"]), + page: tOptional(tChannel(["Page"])) +}); +scheme.BrowserContextRequestFailedEvent = tObject({ + request: tChannel(["Request"]), + failureText: tOptional(tString), + responseEndTiming: tNumber, + page: tOptional(tChannel(["Page"])) +}); +scheme.BrowserContextRequestFinishedEvent = tObject({ + request: tChannel(["Request"]), + response: tOptional(tChannel(["Response"])), + responseEndTiming: tNumber, + page: tOptional(tChannel(["Page"])) +}); +scheme.BrowserContextResponseEvent = tObject({ + response: tChannel(["Response"]), + page: tOptional(tChannel(["Page"])) +}); +scheme.BrowserContextAddCookiesParams = tObject({ + cookies: tArray(tType("SetNetworkCookie")) +}); +scheme.BrowserContextAddCookiesResult = tOptional(tObject({})); +scheme.BrowserContextAddInitScriptParams = tObject({ + source: tString +}); +scheme.BrowserContextAddInitScriptResult = tOptional(tObject({})); +scheme.BrowserContextClearCookiesParams = tObject({ + name: tOptional(tString), + nameRegexSource: tOptional(tString), + nameRegexFlags: tOptional(tString), + domain: tOptional(tString), + domainRegexSource: tOptional(tString), + domainRegexFlags: tOptional(tString), + path: tOptional(tString), + pathRegexSource: tOptional(tString), + pathRegexFlags: tOptional(tString) +}); +scheme.BrowserContextClearCookiesResult = tOptional(tObject({})); +scheme.BrowserContextClearPermissionsParams = tOptional(tObject({})); +scheme.BrowserContextClearPermissionsResult = tOptional(tObject({})); +scheme.BrowserContextCloseParams = tObject({ + reason: tOptional(tString) +}); +scheme.BrowserContextCloseResult = tOptional(tObject({})); +scheme.BrowserContextCookiesParams = tObject({ + urls: tArray(tString) +}); +scheme.BrowserContextCookiesResult = tObject({ + cookies: tArray(tType("NetworkCookie")) +}); +scheme.BrowserContextExposeBindingParams = tObject({ + name: tString, + needsHandle: tOptional(tBoolean) +}); +scheme.BrowserContextExposeBindingResult = tOptional(tObject({})); +scheme.BrowserContextGrantPermissionsParams = tObject({ + permissions: tArray(tString), + origin: tOptional(tString) +}); +scheme.BrowserContextGrantPermissionsResult = tOptional(tObject({})); +scheme.BrowserContextNewPageParams = tOptional(tObject({})); +scheme.BrowserContextNewPageResult = tObject({ + page: tChannel(["Page"]) +}); +scheme.BrowserContextRegisterSelectorEngineParams = tObject({ + selectorEngine: tType("SelectorEngine") +}); +scheme.BrowserContextRegisterSelectorEngineResult = tOptional(tObject({})); +scheme.BrowserContextSetTestIdAttributeNameParams = tObject({ + testIdAttributeName: tString +}); +scheme.BrowserContextSetTestIdAttributeNameResult = tOptional(tObject({})); +scheme.BrowserContextSetExtraHTTPHeadersParams = tObject({ + headers: tArray(tType("NameValue")) +}); +scheme.BrowserContextSetExtraHTTPHeadersResult = tOptional(tObject({})); +scheme.BrowserContextSetGeolocationParams = tObject({ + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })) +}); +scheme.BrowserContextSetGeolocationResult = tOptional(tObject({})); +scheme.BrowserContextSetHTTPCredentialsParams = tObject({ + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString) + })) +}); +scheme.BrowserContextSetHTTPCredentialsResult = tOptional(tObject({})); +scheme.BrowserContextSetNetworkInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString) + })) +}); +scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({})); +scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString) + })) +}); +scheme.BrowserContextSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); +scheme.BrowserContextSetOfflineParams = tObject({ + offline: tBoolean +}); +scheme.BrowserContextSetOfflineResult = tOptional(tObject({})); +scheme.BrowserContextStorageStateParams = tObject({ + indexedDB: tOptional(tBoolean) +}); +scheme.BrowserContextStorageStateResult = tObject({ + cookies: tArray(tType("NetworkCookie")), + origins: tArray(tType("OriginStorage")) +}); +scheme.BrowserContextPauseParams = tOptional(tObject({})); +scheme.BrowserContextPauseResult = tOptional(tObject({})); +scheme.BrowserContextEnableRecorderParams = tObject({ + language: tOptional(tString), + mode: tOptional(tEnum(["inspecting", "recording"])), + pauseOnNextStatement: tOptional(tBoolean), + testIdAttributeName: tOptional(tString), + launchOptions: tOptional(tAny), + contextOptions: tOptional(tAny), + device: tOptional(tString), + saveStorage: tOptional(tString), + outputFile: tOptional(tString), + handleSIGINT: tOptional(tBoolean), + omitCallTracking: tOptional(tBoolean) +}); +scheme.BrowserContextEnableRecorderResult = tOptional(tObject({})); +scheme.BrowserContextNewCDPSessionParams = tObject({ + page: tOptional(tChannel(["Page"])), + frame: tOptional(tChannel(["Frame"])) +}); +scheme.BrowserContextNewCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) +}); +scheme.BrowserContextHarStartParams = tObject({ + page: tOptional(tChannel(["Page"])), + options: tType("RecordHarOptions") +}); +scheme.BrowserContextHarStartResult = tObject({ + harId: tString +}); +scheme.BrowserContextHarExportParams = tObject({ + harId: tOptional(tString) +}); +scheme.BrowserContextHarExportResult = tObject({ + artifact: tChannel(["Artifact"]) +}); +scheme.BrowserContextCreateTempFilesParams = tObject({ + rootDirName: tOptional(tString), + items: tArray(tObject({ + name: tString, + lastModifiedMs: tOptional(tNumber) + })) +}); +scheme.BrowserContextCreateTempFilesResult = tObject({ + rootDir: tOptional(tChannel(["WritableStream"])), + writableStreams: tArray(tChannel(["WritableStream"])) +}); +scheme.BrowserContextUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean +}); +scheme.BrowserContextUpdateSubscriptionResult = tOptional(tObject({})); +scheme.BrowserContextClockFastForwardParams = tObject({ + ticksNumber: tOptional(tNumber), + ticksString: tOptional(tString) +}); +scheme.BrowserContextClockFastForwardResult = tOptional(tObject({})); +scheme.BrowserContextClockInstallParams = tObject({ + timeNumber: tOptional(tNumber), + timeString: tOptional(tString) +}); +scheme.BrowserContextClockInstallResult = tOptional(tObject({})); +scheme.BrowserContextClockPauseAtParams = tObject({ + timeNumber: tOptional(tNumber), + timeString: tOptional(tString) +}); +scheme.BrowserContextClockPauseAtResult = tOptional(tObject({})); +scheme.BrowserContextClockResumeParams = tOptional(tObject({})); +scheme.BrowserContextClockResumeResult = tOptional(tObject({})); +scheme.BrowserContextClockRunForParams = tObject({ + ticksNumber: tOptional(tNumber), + ticksString: tOptional(tString) +}); +scheme.BrowserContextClockRunForResult = tOptional(tObject({})); +scheme.BrowserContextClockSetFixedTimeParams = tObject({ + timeNumber: tOptional(tNumber), + timeString: tOptional(tString) +}); +scheme.BrowserContextClockSetFixedTimeResult = tOptional(tObject({})); +scheme.BrowserContextClockSetSystemTimeParams = tObject({ + timeNumber: tOptional(tNumber), + timeString: tOptional(tString) +}); +scheme.BrowserContextClockSetSystemTimeResult = tOptional(tObject({})); +scheme.PageInitializer = tObject({ + mainFrame: tChannel(["Frame"]), + viewportSize: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + isClosed: tBoolean, + opener: tOptional(tChannel(["Page"])) +}); +scheme.PageBindingCallEvent = tObject({ + binding: tChannel(["BindingCall"]) +}); +scheme.PageCloseEvent = tOptional(tObject({})); +scheme.PageCrashEvent = tOptional(tObject({})); +scheme.PageDownloadEvent = tObject({ + url: tString, + suggestedFilename: tString, + artifact: tChannel(["Artifact"]) +}); +scheme.PageViewportSizeChangedEvent = tObject({ + viewportSize: tOptional(tObject({ + width: tNumber, + height: tNumber + })) +}); +scheme.PageFileChooserEvent = tObject({ + element: tChannel(["ElementHandle"]), + isMultiple: tBoolean +}); +scheme.PageFrameAttachedEvent = tObject({ + frame: tChannel(["Frame"]) +}); +scheme.PageFrameDetachedEvent = tObject({ + frame: tChannel(["Frame"]) +}); +scheme.PageLocatorHandlerTriggeredEvent = tObject({ + uid: tNumber +}); +scheme.PageRouteEvent = tObject({ + route: tChannel(["Route"]) +}); +scheme.PageWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) +}); +scheme.PageVideoEvent = tObject({ + artifact: tChannel(["Artifact"]) +}); +scheme.PageWebSocketEvent = tObject({ + webSocket: tChannel(["WebSocket"]) +}); +scheme.PageWorkerEvent = tObject({ + worker: tChannel(["Worker"]) +}); +scheme.PageAddInitScriptParams = tObject({ + source: tString +}); +scheme.PageAddInitScriptResult = tOptional(tObject({})); +scheme.PageCloseParams = tObject({ + runBeforeUnload: tOptional(tBoolean), + reason: tOptional(tString) +}); +scheme.PageCloseResult = tOptional(tObject({})); +scheme.PageEmulateMediaParams = tObject({ + media: tOptional(tEnum(["screen", "print", "no-override"])), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])) +}); +scheme.PageEmulateMediaResult = tOptional(tObject({})); +scheme.PageExposeBindingParams = tObject({ + name: tString, + needsHandle: tOptional(tBoolean) +}); +scheme.PageExposeBindingResult = tOptional(tObject({})); +scheme.PageGoBackParams = tObject({ + timeout: tNumber, + waitUntil: tOptional(tType("LifecycleEvent")) +}); +scheme.PageGoBackResult = tObject({ + response: tOptional(tChannel(["Response"])) +}); +scheme.PageGoForwardParams = tObject({ + timeout: tNumber, + waitUntil: tOptional(tType("LifecycleEvent")) +}); +scheme.PageGoForwardResult = tObject({ + response: tOptional(tChannel(["Response"])) +}); +scheme.PageRequestGCParams = tOptional(tObject({})); +scheme.PageRequestGCResult = tOptional(tObject({})); +scheme.PageRegisterLocatorHandlerParams = tObject({ + selector: tString, + noWaitAfter: tOptional(tBoolean) +}); +scheme.PageRegisterLocatorHandlerResult = tObject({ + uid: tNumber +}); +scheme.PageResolveLocatorHandlerNoReplyParams = tObject({ + uid: tNumber, + remove: tOptional(tBoolean) +}); +scheme.PageResolveLocatorHandlerNoReplyResult = tOptional(tObject({})); +scheme.PageUnregisterLocatorHandlerParams = tObject({ + uid: tNumber +}); +scheme.PageUnregisterLocatorHandlerResult = tOptional(tObject({})); +scheme.PageReloadParams = tObject({ + timeout: tNumber, + waitUntil: tOptional(tType("LifecycleEvent")) +}); +scheme.PageReloadResult = tObject({ + response: tOptional(tChannel(["Response"])) +}); +scheme.PageExpectScreenshotParams = tObject({ + expected: tOptional(tBinary), + timeout: tNumber, + isNot: tBoolean, + locator: tOptional(tObject({ + frame: tChannel(["Frame"]), + selector: tString + })), + comparator: tOptional(tString), + maxDiffPixels: tOptional(tNumber), + maxDiffPixelRatio: tOptional(tNumber), + threshold: tOptional(tNumber), + fullPage: tOptional(tBoolean), + clip: tOptional(tType("Rect")), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) +}); +scheme.PageExpectScreenshotResult = tObject({ + diff: tOptional(tBinary), + errorMessage: tOptional(tString), + actual: tOptional(tBinary), + previous: tOptional(tBinary), + timedOut: tOptional(tBoolean), + log: tOptional(tArray(tString)) +}); +scheme.PageScreenshotParams = tObject({ + timeout: tNumber, + type: tOptional(tEnum(["png", "jpeg"])), + quality: tOptional(tNumber), + fullPage: tOptional(tBoolean), + clip: tOptional(tType("Rect")), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) +}); +scheme.PageScreenshotResult = tObject({ + binary: tBinary +}); +scheme.PageSetExtraHTTPHeadersParams = tObject({ + headers: tArray(tType("NameValue")) +}); +scheme.PageSetExtraHTTPHeadersResult = tOptional(tObject({})); +scheme.PageSetNetworkInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString) + })) +}); +scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({})); +scheme.PageSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString) + })) +}); +scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); +scheme.PageSetViewportSizeParams = tObject({ + viewportSize: tObject({ + width: tNumber, + height: tNumber + }) +}); +scheme.PageSetViewportSizeResult = tOptional(tObject({})); +scheme.PageKeyboardDownParams = tObject({ + key: tString +}); +scheme.PageKeyboardDownResult = tOptional(tObject({})); +scheme.PageKeyboardUpParams = tObject({ + key: tString +}); +scheme.PageKeyboardUpResult = tOptional(tObject({})); +scheme.PageKeyboardInsertTextParams = tObject({ + text: tString +}); +scheme.PageKeyboardInsertTextResult = tOptional(tObject({})); +scheme.PageKeyboardTypeParams = tObject({ + text: tString, + delay: tOptional(tNumber) +}); +scheme.PageKeyboardTypeResult = tOptional(tObject({})); +scheme.PageKeyboardPressParams = tObject({ + key: tString, + delay: tOptional(tNumber) +}); +scheme.PageKeyboardPressResult = tOptional(tObject({})); +scheme.PageMouseMoveParams = tObject({ + x: tNumber, + y: tNumber, + steps: tOptional(tNumber) +}); +scheme.PageMouseMoveResult = tOptional(tObject({})); +scheme.PageMouseDownParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tNumber) +}); +scheme.PageMouseDownResult = tOptional(tObject({})); +scheme.PageMouseUpParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tNumber) +}); +scheme.PageMouseUpResult = tOptional(tObject({})); +scheme.PageMouseClickParams = tObject({ + x: tNumber, + y: tNumber, + delay: tOptional(tNumber), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tNumber) +}); +scheme.PageMouseClickResult = tOptional(tObject({})); +scheme.PageMouseWheelParams = tObject({ + deltaX: tNumber, + deltaY: tNumber +}); +scheme.PageMouseWheelResult = tOptional(tObject({})); +scheme.PageTouchscreenTapParams = tObject({ + x: tNumber, + y: tNumber +}); +scheme.PageTouchscreenTapResult = tOptional(tObject({})); +scheme.PageAccessibilitySnapshotParams = tObject({ + interestingOnly: tOptional(tBoolean), + root: tOptional(tChannel(["ElementHandle"])) +}); +scheme.PageAccessibilitySnapshotResult = tObject({ + rootAXNode: tOptional(tType("AXNode")) +}); +scheme.PagePdfParams = tObject({ + scale: tOptional(tNumber), + displayHeaderFooter: tOptional(tBoolean), + headerTemplate: tOptional(tString), + footerTemplate: tOptional(tString), + printBackground: tOptional(tBoolean), + landscape: tOptional(tBoolean), + pageRanges: tOptional(tString), + format: tOptional(tString), + width: tOptional(tString), + height: tOptional(tString), + preferCSSPageSize: tOptional(tBoolean), + margin: tOptional(tObject({ + top: tOptional(tString), + bottom: tOptional(tString), + left: tOptional(tString), + right: tOptional(tString) + })), + tagged: tOptional(tBoolean), + outline: tOptional(tBoolean) +}); +scheme.PagePdfResult = tObject({ + pdf: tBinary +}); +scheme.PageSnapshotForAIParams = tOptional(tObject({})); +scheme.PageSnapshotForAIResult = tObject({ + snapshot: tString +}); +scheme.PageStartJSCoverageParams = tObject({ + resetOnNavigation: tOptional(tBoolean), + reportAnonymousScripts: tOptional(tBoolean) +}); +scheme.PageStartJSCoverageResult = tOptional(tObject({})); +scheme.PageStopJSCoverageParams = tOptional(tObject({})); +scheme.PageStopJSCoverageResult = tObject({ + entries: tArray(tObject({ + url: tString, + scriptId: tString, + source: tOptional(tString), + functions: tArray(tObject({ + functionName: tString, + isBlockCoverage: tBoolean, + ranges: tArray(tObject({ + startOffset: tNumber, + endOffset: tNumber, + count: tNumber + })) + })) + })) +}); +scheme.PageStartCSSCoverageParams = tObject({ + resetOnNavigation: tOptional(tBoolean) +}); +scheme.PageStartCSSCoverageResult = tOptional(tObject({})); +scheme.PageStopCSSCoverageParams = tOptional(tObject({})); +scheme.PageStopCSSCoverageResult = tObject({ + entries: tArray(tObject({ + url: tString, + text: tOptional(tString), + ranges: tArray(tObject({ + start: tNumber, + end: tNumber + })) + })) +}); +scheme.PageBringToFrontParams = tOptional(tObject({})); +scheme.PageBringToFrontResult = tOptional(tObject({})); +scheme.PageUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "fileChooser", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean +}); +scheme.PageUpdateSubscriptionResult = tOptional(tObject({})); +scheme.FrameInitializer = tObject({ + url: tString, + name: tString, + parentFrame: tOptional(tChannel(["Frame"])), + loadStates: tArray(tType("LifecycleEvent")) +}); +scheme.FrameLoadstateEvent = tObject({ + add: tOptional(tType("LifecycleEvent")), + remove: tOptional(tType("LifecycleEvent")) +}); +scheme.FrameNavigatedEvent = tObject({ + url: tString, + name: tString, + newDocument: tOptional(tObject({ + request: tOptional(tChannel(["Request"])) + })), + error: tOptional(tString) +}); +scheme.FrameEvalOnSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.FrameEvalOnSelectorResult = tObject({ + value: tType("SerializedValue") +}); +scheme.FrameEvalOnSelectorAllParams = tObject({ + selector: tString, + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.FrameEvalOnSelectorAllResult = tObject({ + value: tType("SerializedValue") +}); +scheme.FrameAddScriptTagParams = tObject({ + url: tOptional(tString), + content: tOptional(tString), + type: tOptional(tString) +}); +scheme.FrameAddScriptTagResult = tObject({ + element: tChannel(["ElementHandle"]) +}); +scheme.FrameAddStyleTagParams = tObject({ + url: tOptional(tString), + content: tOptional(tString) +}); +scheme.FrameAddStyleTagResult = tObject({ + element: tChannel(["ElementHandle"]) +}); +scheme.FrameAriaSnapshotParams = tObject({ + selector: tString, + forAI: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameAriaSnapshotResult = tObject({ + snapshot: tString +}); +scheme.FrameBlurParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameBlurResult = tOptional(tObject({})); +scheme.FrameCheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.FrameCheckResult = tOptional(tObject({})); +scheme.FrameClickParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + noWaitAfter: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tNumber), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tNumber), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.FrameClickResult = tOptional(tObject({})); +scheme.FrameContentParams = tOptional(tObject({})); +scheme.FrameContentResult = tObject({ + value: tString +}); +scheme.FrameDragAndDropParams = tObject({ + source: tString, + target: tString, + force: tOptional(tBoolean), + timeout: tNumber, + trial: tOptional(tBoolean), + sourcePosition: tOptional(tType("Point")), + targetPosition: tOptional(tType("Point")), + strict: tOptional(tBoolean) +}); +scheme.FrameDragAndDropResult = tOptional(tObject({})); +scheme.FrameDblclickParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tNumber), + button: tOptional(tEnum(["left", "right", "middle"])), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.FrameDblclickResult = tOptional(tObject({})); +scheme.FrameDispatchEventParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + type: tString, + eventInit: tType("SerializedArgument"), + timeout: tNumber +}); +scheme.FrameDispatchEventResult = tOptional(tObject({})); +scheme.FrameEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.FrameEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") +}); +scheme.FrameEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.FrameEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.FrameFillParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + value: tString, + force: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameFillResult = tOptional(tObject({})); +scheme.FrameFocusParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameFocusResult = tOptional(tObject({})); +scheme.FrameFrameElementParams = tOptional(tObject({})); +scheme.FrameFrameElementResult = tObject({ + element: tChannel(["ElementHandle"]) +}); +scheme.FrameHighlightParams = tObject({ + selector: tString +}); +scheme.FrameHighlightResult = tOptional(tObject({})); +scheme.FrameGetAttributeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + name: tString, + timeout: tNumber +}); +scheme.FrameGetAttributeResult = tObject({ + value: tOptional(tString) +}); +scheme.FrameGotoParams = tObject({ + url: tString, + timeout: tNumber, + waitUntil: tOptional(tType("LifecycleEvent")), + referer: tOptional(tString) +}); +scheme.FrameGotoResult = tObject({ + response: tOptional(tChannel(["Response"])) +}); +scheme.FrameHoverParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.FrameHoverResult = tOptional(tObject({})); +scheme.FrameInnerHTMLParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameInnerHTMLResult = tObject({ + value: tString +}); +scheme.FrameInnerTextParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameInnerTextResult = tObject({ + value: tString +}); +scheme.FrameInputValueParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameInputValueResult = tObject({ + value: tString +}); +scheme.FrameIsCheckedParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameIsCheckedResult = tObject({ + value: tBoolean +}); +scheme.FrameIsDisabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameIsDisabledResult = tObject({ + value: tBoolean +}); +scheme.FrameIsEnabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameIsEnabledResult = tObject({ + value: tBoolean +}); +scheme.FrameIsHiddenParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) +}); +scheme.FrameIsHiddenResult = tObject({ + value: tBoolean +}); +scheme.FrameIsVisibleParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) +}); +scheme.FrameIsVisibleResult = tObject({ + value: tBoolean +}); +scheme.FrameIsEditableParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameIsEditableResult = tObject({ + value: tBoolean +}); +scheme.FramePressParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + key: tString, + delay: tOptional(tNumber), + noWaitAfter: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FramePressResult = tOptional(tObject({})); +scheme.FrameQuerySelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) +}); +scheme.FrameQuerySelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) +}); +scheme.FrameQuerySelectorAllParams = tObject({ + selector: tString +}); +scheme.FrameQuerySelectorAllResult = tObject({ + elements: tArray(tChannel(["ElementHandle"])) +}); +scheme.FrameQueryCountParams = tObject({ + selector: tString +}); +scheme.FrameQueryCountResult = tObject({ + value: tNumber +}); +scheme.FrameSelectOptionParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + elements: tOptional(tArray(tChannel(["ElementHandle"]))), + options: tOptional(tArray(tObject({ + valueOrLabel: tOptional(tString), + value: tOptional(tString), + label: tOptional(tString), + index: tOptional(tNumber) + }))), + force: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameSelectOptionResult = tObject({ + values: tArray(tString) +}); +scheme.FrameSetContentParams = tObject({ + html: tString, + timeout: tNumber, + waitUntil: tOptional(tType("LifecycleEvent")) +}); +scheme.FrameSetContentResult = tOptional(tObject({})); +scheme.FrameSetInputFilesParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localDirectory: tOptional(tString), + directoryStream: tOptional(tChannel(["WritableStream"])), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))), + timeout: tNumber +}); +scheme.FrameSetInputFilesResult = tOptional(tObject({})); +scheme.FrameTapParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.FrameTapResult = tOptional(tObject({})); +scheme.FrameTextContentParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber +}); +scheme.FrameTextContentResult = tObject({ + value: tOptional(tString) +}); +scheme.FrameTitleParams = tOptional(tObject({})); +scheme.FrameTitleResult = tObject({ + value: tString +}); +scheme.FrameTypeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + text: tString, + delay: tOptional(tNumber), + timeout: tNumber +}); +scheme.FrameTypeResult = tOptional(tObject({})); +scheme.FrameUncheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.FrameUncheckResult = tOptional(tObject({})); +scheme.FrameWaitForTimeoutParams = tObject({ + timeout: tNumber +}); +scheme.FrameWaitForTimeoutResult = tOptional(tObject({})); +scheme.FrameWaitForFunctionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument"), + timeout: tNumber, + pollingInterval: tOptional(tNumber) +}); +scheme.FrameWaitForFunctionResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.FrameWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber, + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])), + omitReturnValue: tOptional(tBoolean) +}); +scheme.FrameWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) +}); +scheme.FrameExpectParams = tObject({ + selector: tString, + expression: tString, + expressionArg: tOptional(tAny), + expectedText: tOptional(tArray(tType("ExpectedTextValue"))), + expectedNumber: tOptional(tNumber), + expectedValue: tOptional(tType("SerializedArgument")), + useInnerText: tOptional(tBoolean), + isNot: tBoolean, + timeout: tNumber +}); +scheme.FrameExpectResult = tObject({ + matches: tBoolean, + received: tOptional(tType("SerializedValue")), + timedOut: tOptional(tBoolean), + log: tOptional(tArray(tString)) +}); +scheme.WorkerInitializer = tObject({ + url: tString +}); +scheme.WorkerCloseEvent = tOptional(tObject({})); +scheme.WorkerEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.WorkerEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") +}); +scheme.WorkerEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.WorkerEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.JSHandleInitializer = tObject({ + preview: tString +}); +scheme.JSHandlePreviewUpdatedEvent = tObject({ + preview: tString +}); +scheme.ElementHandlePreviewUpdatedEvent = tType("JSHandlePreviewUpdatedEvent"); +scheme.JSHandleDisposeParams = tOptional(tObject({})); +scheme.ElementHandleDisposeParams = tType("JSHandleDisposeParams"); +scheme.JSHandleDisposeResult = tOptional(tObject({})); +scheme.ElementHandleDisposeResult = tType("JSHandleDisposeResult"); +scheme.JSHandleEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.ElementHandleEvaluateExpressionParams = tType("JSHandleEvaluateExpressionParams"); +scheme.JSHandleEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") +}); +scheme.ElementHandleEvaluateExpressionResult = tType("JSHandleEvaluateExpressionResult"); +scheme.JSHandleEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.ElementHandleEvaluateExpressionHandleParams = tType("JSHandleEvaluateExpressionHandleParams"); +scheme.JSHandleEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.ElementHandleEvaluateExpressionHandleResult = tType("JSHandleEvaluateExpressionHandleResult"); +scheme.JSHandleGetPropertyListParams = tOptional(tObject({})); +scheme.ElementHandleGetPropertyListParams = tType("JSHandleGetPropertyListParams"); +scheme.JSHandleGetPropertyListResult = tObject({ + properties: tArray(tObject({ + name: tString, + value: tChannel(["ElementHandle", "JSHandle"]) + })) +}); +scheme.ElementHandleGetPropertyListResult = tType("JSHandleGetPropertyListResult"); +scheme.JSHandleGetPropertyParams = tObject({ + name: tString +}); +scheme.ElementHandleGetPropertyParams = tType("JSHandleGetPropertyParams"); +scheme.JSHandleGetPropertyResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.ElementHandleGetPropertyResult = tType("JSHandleGetPropertyResult"); +scheme.JSHandleJsonValueParams = tOptional(tObject({})); +scheme.ElementHandleJsonValueParams = tType("JSHandleJsonValueParams"); +scheme.JSHandleJsonValueResult = tObject({ + value: tType("SerializedValue") +}); +scheme.ElementHandleJsonValueResult = tType("JSHandleJsonValueResult"); +scheme.ElementHandleInitializer = tObject({ + preview: tString +}); +scheme.ElementHandleEvalOnSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.ElementHandleEvalOnSelectorResult = tObject({ + value: tType("SerializedValue") +}); +scheme.ElementHandleEvalOnSelectorAllParams = tObject({ + selector: tString, + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.ElementHandleEvalOnSelectorAllResult = tObject({ + value: tType("SerializedValue") +}); +scheme.ElementHandleBoundingBoxParams = tOptional(tObject({})); +scheme.ElementHandleBoundingBoxResult = tObject({ + value: tOptional(tType("Rect")) +}); +scheme.ElementHandleCheckParams = tObject({ + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.ElementHandleCheckResult = tOptional(tObject({})); +scheme.ElementHandleClickParams = tObject({ + force: tOptional(tBoolean), + noWaitAfter: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tNumber), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tNumber), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.ElementHandleClickResult = tOptional(tObject({})); +scheme.ElementHandleContentFrameParams = tOptional(tObject({})); +scheme.ElementHandleContentFrameResult = tObject({ + frame: tOptional(tChannel(["Frame"])) +}); +scheme.ElementHandleDblclickParams = tObject({ + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tNumber), + button: tOptional(tEnum(["left", "right", "middle"])), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.ElementHandleDblclickResult = tOptional(tObject({})); +scheme.ElementHandleDispatchEventParams = tObject({ + type: tString, + eventInit: tType("SerializedArgument") +}); +scheme.ElementHandleDispatchEventResult = tOptional(tObject({})); +scheme.ElementHandleFillParams = tObject({ + value: tString, + force: tOptional(tBoolean), + timeout: tNumber +}); +scheme.ElementHandleFillResult = tOptional(tObject({})); +scheme.ElementHandleFocusParams = tOptional(tObject({})); +scheme.ElementHandleFocusResult = tOptional(tObject({})); +scheme.ElementHandleGenerateLocatorStringParams = tOptional(tObject({})); +scheme.ElementHandleGenerateLocatorStringResult = tObject({ + value: tOptional(tString) +}); +scheme.ElementHandleGetAttributeParams = tObject({ + name: tString +}); +scheme.ElementHandleGetAttributeResult = tObject({ + value: tOptional(tString) +}); +scheme.ElementHandleHoverParams = tObject({ + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.ElementHandleHoverResult = tOptional(tObject({})); +scheme.ElementHandleInnerHTMLParams = tOptional(tObject({})); +scheme.ElementHandleInnerHTMLResult = tObject({ + value: tString +}); +scheme.ElementHandleInnerTextParams = tOptional(tObject({})); +scheme.ElementHandleInnerTextResult = tObject({ + value: tString +}); +scheme.ElementHandleInputValueParams = tOptional(tObject({})); +scheme.ElementHandleInputValueResult = tObject({ + value: tString +}); +scheme.ElementHandleIsCheckedParams = tOptional(tObject({})); +scheme.ElementHandleIsCheckedResult = tObject({ + value: tBoolean +}); +scheme.ElementHandleIsDisabledParams = tOptional(tObject({})); +scheme.ElementHandleIsDisabledResult = tObject({ + value: tBoolean +}); +scheme.ElementHandleIsEditableParams = tOptional(tObject({})); +scheme.ElementHandleIsEditableResult = tObject({ + value: tBoolean +}); +scheme.ElementHandleIsEnabledParams = tOptional(tObject({})); +scheme.ElementHandleIsEnabledResult = tObject({ + value: tBoolean +}); +scheme.ElementHandleIsHiddenParams = tOptional(tObject({})); +scheme.ElementHandleIsHiddenResult = tObject({ + value: tBoolean +}); +scheme.ElementHandleIsVisibleParams = tOptional(tObject({})); +scheme.ElementHandleIsVisibleResult = tObject({ + value: tBoolean +}); +scheme.ElementHandleOwnerFrameParams = tOptional(tObject({})); +scheme.ElementHandleOwnerFrameResult = tObject({ + frame: tOptional(tChannel(["Frame"])) +}); +scheme.ElementHandlePressParams = tObject({ + key: tString, + delay: tOptional(tNumber), + timeout: tNumber, + noWaitAfter: tOptional(tBoolean) +}); +scheme.ElementHandlePressResult = tOptional(tObject({})); +scheme.ElementHandleQuerySelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) +}); +scheme.ElementHandleQuerySelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) +}); +scheme.ElementHandleQuerySelectorAllParams = tObject({ + selector: tString +}); +scheme.ElementHandleQuerySelectorAllResult = tObject({ + elements: tArray(tChannel(["ElementHandle"])) +}); +scheme.ElementHandleScreenshotParams = tObject({ + timeout: tNumber, + type: tOptional(tEnum(["png", "jpeg"])), + quality: tOptional(tNumber), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) +}); +scheme.ElementHandleScreenshotResult = tObject({ + binary: tBinary +}); +scheme.ElementHandleScrollIntoViewIfNeededParams = tObject({ + timeout: tNumber +}); +scheme.ElementHandleScrollIntoViewIfNeededResult = tOptional(tObject({})); +scheme.ElementHandleSelectOptionParams = tObject({ + elements: tOptional(tArray(tChannel(["ElementHandle"]))), + options: tOptional(tArray(tObject({ + valueOrLabel: tOptional(tString), + value: tOptional(tString), + label: tOptional(tString), + index: tOptional(tNumber) + }))), + force: tOptional(tBoolean), + timeout: tNumber +}); +scheme.ElementHandleSelectOptionResult = tObject({ + values: tArray(tString) +}); +scheme.ElementHandleSelectTextParams = tObject({ + force: tOptional(tBoolean), + timeout: tNumber +}); +scheme.ElementHandleSelectTextResult = tOptional(tObject({})); +scheme.ElementHandleSetInputFilesParams = tObject({ + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localDirectory: tOptional(tString), + directoryStream: tOptional(tChannel(["WritableStream"])), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))), + timeout: tNumber +}); +scheme.ElementHandleSetInputFilesResult = tOptional(tObject({})); +scheme.ElementHandleTapParams = tObject({ + force: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.ElementHandleTapResult = tOptional(tObject({})); +scheme.ElementHandleTextContentParams = tOptional(tObject({})); +scheme.ElementHandleTextContentResult = tObject({ + value: tOptional(tString) +}); +scheme.ElementHandleTypeParams = tObject({ + text: tString, + delay: tOptional(tNumber), + timeout: tNumber +}); +scheme.ElementHandleTypeResult = tOptional(tObject({})); +scheme.ElementHandleUncheckParams = tObject({ + force: tOptional(tBoolean), + position: tOptional(tType("Point")), + timeout: tNumber, + trial: tOptional(tBoolean) +}); +scheme.ElementHandleUncheckResult = tOptional(tObject({})); +scheme.ElementHandleWaitForElementStateParams = tObject({ + state: tEnum(["visible", "hidden", "stable", "enabled", "disabled", "editable"]), + timeout: tNumber +}); +scheme.ElementHandleWaitForElementStateResult = tOptional(tObject({})); +scheme.ElementHandleWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + timeout: tNumber, + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])) +}); +scheme.ElementHandleWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) +}); +scheme.RequestInitializer = tObject({ + frame: tOptional(tChannel(["Frame"])), + serviceWorker: tOptional(tChannel(["Worker"])), + url: tString, + resourceType: tString, + method: tString, + postData: tOptional(tBinary), + headers: tArray(tType("NameValue")), + isNavigationRequest: tBoolean, + redirectedFrom: tOptional(tChannel(["Request"])) +}); +scheme.RequestResponseParams = tOptional(tObject({})); +scheme.RequestResponseResult = tObject({ + response: tOptional(tChannel(["Response"])) +}); +scheme.RequestRawRequestHeadersParams = tOptional(tObject({})); +scheme.RequestRawRequestHeadersResult = tObject({ + headers: tArray(tType("NameValue")) +}); +scheme.RouteInitializer = tObject({ + request: tChannel(["Request"]) +}); +scheme.RouteRedirectNavigationRequestParams = tObject({ + url: tString +}); +scheme.RouteRedirectNavigationRequestResult = tOptional(tObject({})); +scheme.RouteAbortParams = tObject({ + errorCode: tOptional(tString) +}); +scheme.RouteAbortResult = tOptional(tObject({})); +scheme.RouteContinueParams = tObject({ + url: tOptional(tString), + method: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + postData: tOptional(tBinary), + isFallback: tBoolean +}); +scheme.RouteContinueResult = tOptional(tObject({})); +scheme.RouteFulfillParams = tObject({ + status: tOptional(tNumber), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tString), + isBase64: tOptional(tBoolean), + fetchResponseUid: tOptional(tString) +}); +scheme.RouteFulfillResult = tOptional(tObject({})); +scheme.WebSocketRouteInitializer = tObject({ + url: tString +}); +scheme.WebSocketRouteMessageFromPageEvent = tObject({ + message: tString, + isBase64: tBoolean +}); +scheme.WebSocketRouteMessageFromServerEvent = tObject({ + message: tString, + isBase64: tBoolean +}); +scheme.WebSocketRouteClosePageEvent = tObject({ + code: tOptional(tNumber), + reason: tOptional(tString), + wasClean: tBoolean +}); +scheme.WebSocketRouteCloseServerEvent = tObject({ + code: tOptional(tNumber), + reason: tOptional(tString), + wasClean: tBoolean +}); +scheme.WebSocketRouteConnectParams = tOptional(tObject({})); +scheme.WebSocketRouteConnectResult = tOptional(tObject({})); +scheme.WebSocketRouteEnsureOpenedParams = tOptional(tObject({})); +scheme.WebSocketRouteEnsureOpenedResult = tOptional(tObject({})); +scheme.WebSocketRouteSendToPageParams = tObject({ + message: tString, + isBase64: tBoolean +}); +scheme.WebSocketRouteSendToPageResult = tOptional(tObject({})); +scheme.WebSocketRouteSendToServerParams = tObject({ + message: tString, + isBase64: tBoolean +}); +scheme.WebSocketRouteSendToServerResult = tOptional(tObject({})); +scheme.WebSocketRouteClosePageParams = tObject({ + code: tOptional(tNumber), + reason: tOptional(tString), + wasClean: tBoolean +}); +scheme.WebSocketRouteClosePageResult = tOptional(tObject({})); +scheme.WebSocketRouteCloseServerParams = tObject({ + code: tOptional(tNumber), + reason: tOptional(tString), + wasClean: tBoolean +}); +scheme.WebSocketRouteCloseServerResult = tOptional(tObject({})); +scheme.ResourceTiming = tObject({ + startTime: tNumber, + domainLookupStart: tNumber, + domainLookupEnd: tNumber, + connectStart: tNumber, + secureConnectionStart: tNumber, + connectEnd: tNumber, + requestStart: tNumber, + responseStart: tNumber +}); +scheme.ResponseInitializer = tObject({ + request: tChannel(["Request"]), + url: tString, + status: tNumber, + statusText: tString, + headers: tArray(tType("NameValue")), + timing: tType("ResourceTiming"), + fromServiceWorker: tBoolean +}); +scheme.ResponseBodyParams = tOptional(tObject({})); +scheme.ResponseBodyResult = tObject({ + binary: tBinary +}); +scheme.ResponseSecurityDetailsParams = tOptional(tObject({})); +scheme.ResponseSecurityDetailsResult = tObject({ + value: tOptional(tType("SecurityDetails")) +}); +scheme.ResponseServerAddrParams = tOptional(tObject({})); +scheme.ResponseServerAddrResult = tObject({ + value: tOptional(tType("RemoteAddr")) +}); +scheme.ResponseRawResponseHeadersParams = tOptional(tObject({})); +scheme.ResponseRawResponseHeadersResult = tObject({ + headers: tArray(tType("NameValue")) +}); +scheme.ResponseSizesParams = tOptional(tObject({})); +scheme.ResponseSizesResult = tObject({ + sizes: tType("RequestSizes") +}); +scheme.SecurityDetails = tObject({ + issuer: tOptional(tString), + protocol: tOptional(tString), + subjectName: tOptional(tString), + validFrom: tOptional(tNumber), + validTo: tOptional(tNumber) +}); +scheme.RequestSizes = tObject({ + requestBodySize: tNumber, + requestHeadersSize: tNumber, + responseBodySize: tNumber, + responseHeadersSize: tNumber +}); +scheme.RemoteAddr = tObject({ + ipAddress: tString, + port: tNumber +}); +scheme.WebSocketInitializer = tObject({ + url: tString +}); +scheme.WebSocketOpenEvent = tOptional(tObject({})); +scheme.WebSocketFrameSentEvent = tObject({ + opcode: tNumber, + data: tString +}); +scheme.WebSocketFrameReceivedEvent = tObject({ + opcode: tNumber, + data: tString +}); +scheme.WebSocketSocketErrorEvent = tObject({ + error: tString +}); +scheme.WebSocketCloseEvent = tOptional(tObject({})); +scheme.BindingCallInitializer = tObject({ + frame: tChannel(["Frame"]), + name: tString, + args: tOptional(tArray(tType("SerializedValue"))), + handle: tOptional(tChannel(["ElementHandle", "JSHandle"])) +}); +scheme.BindingCallRejectParams = tObject({ + error: tType("SerializedError") +}); +scheme.BindingCallRejectResult = tOptional(tObject({})); +scheme.BindingCallResolveParams = tObject({ + result: tType("SerializedArgument") +}); +scheme.BindingCallResolveResult = tOptional(tObject({})); +scheme.DialogInitializer = tObject({ + page: tOptional(tChannel(["Page"])), + type: tString, + message: tString, + defaultValue: tString +}); +scheme.DialogAcceptParams = tObject({ + promptText: tOptional(tString) +}); +scheme.DialogAcceptResult = tOptional(tObject({})); +scheme.DialogDismissParams = tOptional(tObject({})); +scheme.DialogDismissResult = tOptional(tObject({})); +scheme.TracingInitializer = tOptional(tObject({})); +scheme.TracingTracingStartParams = tObject({ + name: tOptional(tString), + snapshots: tOptional(tBoolean), + screenshots: tOptional(tBoolean), + live: tOptional(tBoolean) +}); +scheme.TracingTracingStartResult = tOptional(tObject({})); +scheme.TracingTracingStartChunkParams = tObject({ + name: tOptional(tString), + title: tOptional(tString) +}); +scheme.TracingTracingStartChunkResult = tObject({ + traceName: tString +}); +scheme.TracingTracingGroupParams = tObject({ + name: tString, + location: tOptional(tObject({ + file: tString, + line: tOptional(tNumber), + column: tOptional(tNumber) + })) +}); +scheme.TracingTracingGroupResult = tOptional(tObject({})); +scheme.TracingTracingGroupEndParams = tOptional(tObject({})); +scheme.TracingTracingGroupEndResult = tOptional(tObject({})); +scheme.TracingTracingStopChunkParams = tObject({ + mode: tEnum(["archive", "discard", "entries"]) +}); +scheme.TracingTracingStopChunkResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])), + entries: tOptional(tArray(tType("NameValue"))) +}); +scheme.TracingTracingStopParams = tOptional(tObject({})); +scheme.TracingTracingStopResult = tOptional(tObject({})); +scheme.ArtifactInitializer = tObject({ + absolutePath: tString +}); +scheme.ArtifactPathAfterFinishedParams = tOptional(tObject({})); +scheme.ArtifactPathAfterFinishedResult = tObject({ + value: tString +}); +scheme.ArtifactSaveAsParams = tObject({ + path: tString +}); +scheme.ArtifactSaveAsResult = tOptional(tObject({})); +scheme.ArtifactSaveAsStreamParams = tOptional(tObject({})); +scheme.ArtifactSaveAsStreamResult = tObject({ + stream: tChannel(["Stream"]) +}); +scheme.ArtifactFailureParams = tOptional(tObject({})); +scheme.ArtifactFailureResult = tObject({ + error: tOptional(tString) +}); +scheme.ArtifactStreamParams = tOptional(tObject({})); +scheme.ArtifactStreamResult = tObject({ + stream: tChannel(["Stream"]) +}); +scheme.ArtifactCancelParams = tOptional(tObject({})); +scheme.ArtifactCancelResult = tOptional(tObject({})); +scheme.ArtifactDeleteParams = tOptional(tObject({})); +scheme.ArtifactDeleteResult = tOptional(tObject({})); +scheme.StreamInitializer = tOptional(tObject({})); +scheme.StreamReadParams = tObject({ + size: tOptional(tNumber) +}); +scheme.StreamReadResult = tObject({ + binary: tBinary +}); +scheme.StreamCloseParams = tOptional(tObject({})); +scheme.StreamCloseResult = tOptional(tObject({})); +scheme.WritableStreamInitializer = tOptional(tObject({})); +scheme.WritableStreamWriteParams = tObject({ + binary: tBinary +}); +scheme.WritableStreamWriteResult = tOptional(tObject({})); +scheme.WritableStreamCloseParams = tOptional(tObject({})); +scheme.WritableStreamCloseResult = tOptional(tObject({})); +scheme.CDPSessionInitializer = tOptional(tObject({})); +scheme.CDPSessionEventEvent = tObject({ + method: tString, + params: tOptional(tAny) +}); +scheme.CDPSessionSendParams = tObject({ + method: tString, + params: tOptional(tAny) +}); +scheme.CDPSessionSendResult = tObject({ + result: tAny +}); +scheme.CDPSessionDetachParams = tOptional(tObject({})); +scheme.CDPSessionDetachResult = tOptional(tObject({})); +scheme.ElectronInitializer = tOptional(tObject({})); +scheme.ElectronLaunchParams = tObject({ + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + cwd: tOptional(tString), + env: tOptional(tArray(tType("NameValue"))), + timeout: tNumber, + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + bypassCSP: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString) + })), + ignoreHTTPSErrors: tOptional(tBoolean), + locale: tOptional(tString), + offline: tOptional(tBoolean), + recordVideo: tOptional(tObject({ + dir: tString, + size: tOptional(tObject({ + width: tNumber, + height: tNumber + })) + })), + strictSelectors: tOptional(tBoolean), + timezoneId: tOptional(tString), + tracesDir: tOptional(tString), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString) +}); +scheme.ElectronLaunchResult = tObject({ + electronApplication: tChannel(["ElectronApplication"]) +}); +scheme.ElectronApplicationInitializer = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.ElectronApplicationCloseEvent = tOptional(tObject({})); +scheme.ElectronApplicationConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tNumber, + columnNumber: tNumber + }) +}); +scheme.ElectronApplicationBrowserWindowParams = tObject({ + page: tChannel(["Page"]) +}); +scheme.ElectronApplicationBrowserWindowResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.ElectronApplicationEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.ElectronApplicationEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") +}); +scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") +}); +scheme.ElectronApplicationEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) +}); +scheme.ElectronApplicationUpdateSubscriptionParams = tObject({ + event: tEnum(["console"]), + enabled: tBoolean +}); +scheme.ElectronApplicationUpdateSubscriptionResult = tOptional(tObject({})); +scheme.AndroidInitializer = tOptional(tObject({})); +scheme.AndroidDevicesParams = tObject({ + host: tOptional(tString), + port: tOptional(tNumber), + omitDriverInstall: tOptional(tBoolean) +}); +scheme.AndroidDevicesResult = tObject({ + devices: tArray(tChannel(["AndroidDevice"])) +}); +scheme.AndroidSocketInitializer = tOptional(tObject({})); +scheme.AndroidSocketDataEvent = tObject({ + data: tBinary +}); +scheme.AndroidSocketCloseEvent = tOptional(tObject({})); +scheme.AndroidSocketWriteParams = tObject({ + data: tBinary +}); +scheme.AndroidSocketWriteResult = tOptional(tObject({})); +scheme.AndroidSocketCloseParams = tOptional(tObject({})); +scheme.AndroidSocketCloseResult = tOptional(tObject({})); +scheme.AndroidDeviceInitializer = tObject({ + model: tString, + serial: tString +}); +scheme.AndroidDeviceCloseEvent = tOptional(tObject({})); +scheme.AndroidDeviceWebViewAddedEvent = tObject({ + webView: tType("AndroidWebView") +}); +scheme.AndroidDeviceWebViewRemovedEvent = tObject({ + socketName: tString +}); +scheme.AndroidDeviceWaitParams = tObject({ + androidSelector: tType("AndroidSelector"), + state: tOptional(tEnum(["gone"])), + timeout: tNumber +}); +scheme.AndroidDeviceWaitResult = tOptional(tObject({})); +scheme.AndroidDeviceFillParams = tObject({ + androidSelector: tType("AndroidSelector"), + text: tString, + timeout: tNumber +}); +scheme.AndroidDeviceFillResult = tOptional(tObject({})); +scheme.AndroidDeviceTapParams = tObject({ + androidSelector: tType("AndroidSelector"), + duration: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDeviceTapResult = tOptional(tObject({})); +scheme.AndroidDeviceDragParams = tObject({ + androidSelector: tType("AndroidSelector"), + dest: tType("Point"), + speed: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDeviceDragResult = tOptional(tObject({})); +scheme.AndroidDeviceFlingParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + speed: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDeviceFlingResult = tOptional(tObject({})); +scheme.AndroidDeviceLongTapParams = tObject({ + androidSelector: tType("AndroidSelector"), + timeout: tNumber +}); +scheme.AndroidDeviceLongTapResult = tOptional(tObject({})); +scheme.AndroidDevicePinchCloseParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tNumber, + speed: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDevicePinchCloseResult = tOptional(tObject({})); +scheme.AndroidDevicePinchOpenParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tNumber, + speed: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDevicePinchOpenResult = tOptional(tObject({})); +scheme.AndroidDeviceScrollParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tNumber, + speed: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDeviceScrollResult = tOptional(tObject({})); +scheme.AndroidDeviceSwipeParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tNumber, + speed: tOptional(tNumber), + timeout: tNumber +}); +scheme.AndroidDeviceSwipeResult = tOptional(tObject({})); +scheme.AndroidDeviceInfoParams = tObject({ + androidSelector: tType("AndroidSelector") +}); +scheme.AndroidDeviceInfoResult = tObject({ + info: tType("AndroidElementInfo") +}); +scheme.AndroidDeviceScreenshotParams = tOptional(tObject({})); +scheme.AndroidDeviceScreenshotResult = tObject({ + binary: tBinary +}); +scheme.AndroidDeviceInputTypeParams = tObject({ + text: tString +}); +scheme.AndroidDeviceInputTypeResult = tOptional(tObject({})); +scheme.AndroidDeviceInputPressParams = tObject({ + key: tString +}); +scheme.AndroidDeviceInputPressResult = tOptional(tObject({})); +scheme.AndroidDeviceInputTapParams = tObject({ + point: tType("Point") +}); +scheme.AndroidDeviceInputTapResult = tOptional(tObject({})); +scheme.AndroidDeviceInputSwipeParams = tObject({ + segments: tArray(tType("Point")), + steps: tNumber +}); +scheme.AndroidDeviceInputSwipeResult = tOptional(tObject({})); +scheme.AndroidDeviceInputDragParams = tObject({ + from: tType("Point"), + to: tType("Point"), + steps: tNumber +}); +scheme.AndroidDeviceInputDragResult = tOptional(tObject({})); +scheme.AndroidDeviceLaunchBrowserParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + screen: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tNumber, + latitude: tNumber, + accuracy: tOptional(tNumber) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + })), + deviceScaleFactor: tOptional(tNumber), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tString, + size: tOptional(tObject({ + width: tNumber, + height: tNumber + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + pkg: tOptional(tString), + args: tOptional(tArray(tString)), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })) +}); +scheme.AndroidDeviceLaunchBrowserResult = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.AndroidDeviceOpenParams = tObject({ + command: tString +}); +scheme.AndroidDeviceOpenResult = tObject({ + socket: tChannel(["AndroidSocket"]) +}); +scheme.AndroidDeviceShellParams = tObject({ + command: tString +}); +scheme.AndroidDeviceShellResult = tObject({ + result: tBinary +}); +scheme.AndroidDeviceInstallApkParams = tObject({ + file: tBinary, + args: tOptional(tArray(tString)) +}); +scheme.AndroidDeviceInstallApkResult = tOptional(tObject({})); +scheme.AndroidDevicePushParams = tObject({ + file: tBinary, + path: tString, + mode: tOptional(tNumber) +}); +scheme.AndroidDevicePushResult = tOptional(tObject({})); +scheme.AndroidDeviceConnectToWebViewParams = tObject({ + socketName: tString +}); +scheme.AndroidDeviceConnectToWebViewResult = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.AndroidDeviceCloseParams = tOptional(tObject({})); +scheme.AndroidDeviceCloseResult = tOptional(tObject({})); +scheme.AndroidWebView = tObject({ + pid: tNumber, + pkg: tString, + socketName: tString +}); +scheme.AndroidSelector = tObject({ + checkable: tOptional(tBoolean), + checked: tOptional(tBoolean), + clazz: tOptional(tString), + clickable: tOptional(tBoolean), + depth: tOptional(tNumber), + desc: tOptional(tString), + enabled: tOptional(tBoolean), + focusable: tOptional(tBoolean), + focused: tOptional(tBoolean), + hasChild: tOptional(tObject({ + androidSelector: tType("AndroidSelector") + })), + hasDescendant: tOptional(tObject({ + androidSelector: tType("AndroidSelector"), + maxDepth: tOptional(tNumber) + })), + longClickable: tOptional(tBoolean), + pkg: tOptional(tString), + res: tOptional(tString), + scrollable: tOptional(tBoolean), + selected: tOptional(tBoolean), + text: tOptional(tString) +}); +scheme.AndroidElementInfo = tObject({ + children: tOptional(tArray(tType("AndroidElementInfo"))), + clazz: tString, + desc: tString, + res: tString, + pkg: tString, + text: tString, + bounds: tType("Rect"), + checkable: tBoolean, + checked: tBoolean, + clickable: tBoolean, + enabled: tBoolean, + focusable: tBoolean, + focused: tBoolean, + longClickable: tBoolean, + scrollable: tBoolean, + selected: tBoolean +}); +scheme.JsonPipeInitializer = tOptional(tObject({})); +scheme.JsonPipeMessageEvent = tObject({ + message: tAny +}); +scheme.JsonPipeClosedEvent = tObject({ + reason: tOptional(tString) +}); +scheme.JsonPipeSendParams = tObject({ + message: tAny +}); +scheme.JsonPipeSendResult = tOptional(tObject({})); +scheme.JsonPipeCloseParams = tOptional(tObject({})); +scheme.JsonPipeCloseResult = tOptional(tObject({})); +const tBrowserContextOptions = () => tObject({ + colorScheme: tOptional(tEnum(["dark", "light", "no-preference"])), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + latitude: tNumber, + longitude: tNumber + })), + viewport: tOptional(tObject({ + width: tNumber, + height: tNumber + })), + permissions: tOptional(tArray(tString)), + serviceWorkers: tOptional(tEnum(["allow", "block"])) +}); +scheme.PlaywrightInitializer = tObject({ + chromium: tChannel(["BrowserType"]), + firefox: tChannel(["BrowserType"]), + webkit: tChannel(["BrowserType"]), + bidiChromium: tChannel(["BrowserType"]), + bidiFirefox: tChannel(["BrowserType"]), + android: tChannel(["Android"]), + electron: tChannel(["Electron"]), + utils: tOptional(tChannel(["LocalUtils"])), + preLaunchedBrowser: tOptional(tChannel(["Browser"])), + preConnectedAndroidDevice: tOptional(tChannel(["AndroidDevice"])), + socksSupport: tOptional(tChannel(["SocksSupport"])), + _crx: tChannel(["Crx"]) +}); +scheme.CrxInitializer = tOptional(tObject({})); +scheme.CrxStartParams = tObject({ + slowMo: tOptional(tNumber), + artifactsDir: tOptional(tString), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + incognito: tOptional(tBoolean), + deviceName: tOptional(tString), + contextOptions: tOptional(tBrowserContextOptions()) +}); +scheme.CrxStartResult = tObject({ + crxApplication: tChannel(["CrxApplication"]) +}); +scheme.CrxApplicationInitializer = tObject({ + context: tChannel(["BrowserContext"]) +}); +scheme.CrxApplicationHideEvent = tOptional(tObject({})); +scheme.CrxApplicationShowEvent = tOptional(tObject({})); +scheme.CrxApplicationAttachedEvent = tObject({ + page: tChannel(["Page"]), + tabId: tNumber +}); +scheme.CrxApplicationDetachedEvent = tObject({ + tabId: tNumber +}); +scheme.CrxApplicationModeChangedEvent = tObject({ + mode: tEnum(["none", "recording", "inspecting", "assertingText", "recording-inspecting", "standby", "assertingVisibility", "assertingValue"]) +}); +scheme.CrxApplicationAttachParams = tObject({ + tabId: tNumber +}); +scheme.CrxApplicationAttachResult = tObject({ + page: tChannel(["Page"]) +}); +scheme.CrxApplicationAttachAllParams = tObject({ + status: tOptional(tEnum(["loading", "complete"])), + lastFocusedWindow: tOptional(tBoolean), + windowId: tOptional(tNumber), + windowType: tOptional(tEnum(["normal", "popup", "panel", "app", "devtools"])), + active: tOptional(tBoolean), + index: tOptional(tNumber), + title: tOptional(tString), + url: tOptional(tArray(tString)), + currentWindow: tOptional(tBoolean), + highlighted: tOptional(tBoolean), + discarded: tOptional(tBoolean), + autoDiscardable: tOptional(tBoolean), + pinned: tOptional(tBoolean), + audible: tOptional(tBoolean), + muted: tOptional(tBoolean), + groupId: tOptional(tNumber) +}); +scheme.CrxApplicationAttachAllResult = tObject({ + pages: tArray(tChannel(["Page"])) +}); +scheme.CrxApplicationDetachParams = tObject({ + tabId: tOptional(tNumber), + page: tOptional(tChannel(["Page"])) +}); +scheme.CrxApplicationDetachResult = tOptional(tObject({})); +scheme.CrxApplicationDetachAllParams = tOptional(tObject({})); +scheme.CrxApplicationDetachAllResult = tOptional(tObject({})); +scheme.CrxApplicationNewPageParams = tObject({ + index: tOptional(tNumber), + openerTabId: tOptional(tNumber), + url: tOptional(tString), + pinned: tOptional(tBoolean), + windowId: tOptional(tNumber), + active: tOptional(tBoolean), + selected: tOptional(tBoolean) +}); +scheme.CrxApplicationNewPageResult = tObject({ + page: tChannel(["Page"]) +}); +scheme.CrxApplicationShowRecorderParams = tObject({ + mode: tOptional(tEnum(["none", "recording", "inspecting", "assertingText", "recording-inspecting", "standby", "assertingVisibility", "assertingValue"])), + language: tOptional(tString), + testIdAttributeName: tOptional(tString), + playInIncognito: tOptional(tBoolean), + window: tOptional(tObject({ + type: tOptional(tEnum(["popup", "sidepanel"])), + url: tOptional(tString) + })) +}); +scheme.CrxApplicationShowRecorderResult = tOptional(tObject({})); +scheme.CrxApplicationHideRecorderParams = tOptional(tObject({})); +scheme.CrxApplicationHideRecorderResult = tOptional(tObject({})); +scheme.CrxApplicationSetModeParams = tObject({ + mode: tEnum(["none", "recording", "inspecting", "assertingText", "recording-inspecting", "standby", "assertingVisibility", "assertingValue"]) +}); +scheme.CrxApplicationSetModeResult = tOptional(tObject({})); +scheme.CrxApplicationCloseParams = tOptional(tObject({})); +scheme.CrxApplicationCloseResult = tOptional(tObject({})); +scheme.CrxApplicationListParams = tObject({ + code: tString +}); +scheme.CrxApplicationListResult = tObject({ + tests: tArray(tObject({ + title: tString, + options: tOptional(tObject({ + deviceName: tOptional(tString), + contextOptions: tOptional(tBrowserContextOptions()) + })), + location: tOptional(tObject({ + file: tString, + line: tOptional(tNumber), + column: tOptional(tNumber) + })) + })) +}); +scheme.CrxApplicationLoadParams = tObject({ + code: tString +}); +scheme.CrxApplicationLoadResult = tOptional(tObject({})); +scheme.CrxApplicationRunParams = tObject({ + page: tOptional(tChannel(["Page"])), + code: tString +}); +scheme.CrxApplicationRunResult = tOptional(tObject({})); +function commonjsRequire(path2) { + throw new Error('Could not dynamically require "' + path2 + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} +const comment = "Do not edit this file, use utils/roll_browser.js"; +const browsers = [{ "name": "chromium", "revision": "1178", "installByDefault": true, "browserVersion": "138.0.7204.15" }, { "name": "chromium-headless-shell", "revision": "1178", "installByDefault": true, "browserVersion": "138.0.7204.15" }, { "name": "chromium-tip-of-tree", "revision": "1337", "installByDefault": false, "browserVersion": "139.0.7216.0" }, { "name": "chromium-tip-of-tree-headless-shell", "revision": "1337", "installByDefault": false, "browserVersion": "139.0.7216.0" }, { "name": "firefox", "revision": "1487", "installByDefault": true, "browserVersion": "139.0" }, { "name": "firefox-beta", "revision": "1482", "installByDefault": false, "browserVersion": "138.0b10" }, { "name": "webkit", "revision": "2182", "installByDefault": true, "revisionOverrides": { "debian11-x64": "2105", "debian11-arm64": "2105", "mac10.14": "1446", "mac10.15": "1616", "mac11": "1816", "mac11-arm64": "1816", "mac12": "2009", "mac12-arm64": "2009", "mac13": "2140", "mac13-arm64": "2140", "ubuntu20.04-x64": "2092", "ubuntu20.04-arm64": "2092" }, "browserVersion": "18.5" }, { "name": "ffmpeg", "revision": "1011", "installByDefault": true, "revisionOverrides": { "mac12": "1010", "mac12-arm64": "1010" } }, { "name": "winldd", "revision": "1007", "installByDefault": false }, { "name": "android", "revision": "1001", "installByDefault": false }]; +const require$$0$5 = { + comment, + browsers +}; +var browser$g = {}; +var hasRequiredBrowser$g; +function requireBrowser$g() { + if (hasRequiredBrowser$g) return browser$g; + hasRequiredBrowser$g = 1; + browser$g.endianness = function() { + return "LE"; + }; + browser$g.hostname = function() { + if (typeof location !== "undefined") { + return location.hostname; + } else return ""; + }; + browser$g.loadavg = function() { + return []; + }; + browser$g.uptime = function() { + return 0; + }; + browser$g.freemem = function() { + return Number.MAX_VALUE; + }; + browser$g.totalmem = function() { + return Number.MAX_VALUE; + }; + browser$g.cpus = function() { + return []; + }; + browser$g.type = function() { + return "Browser"; + }; + browser$g.release = function() { + if (typeof navigator !== "undefined") { + return navigator.appVersion; + } + return ""; + }; + browser$g.networkInterfaces = browser$g.getNetworkInterfaces = function() { + return {}; + }; + browser$g.arch = function() { + return "javascript"; + }; + browser$g.platform = function() { + return "browser"; + }; + browser$g.tmpdir = browser$g.tmpDir = function() { + return "/tmp"; + }; + browser$g.EOL = "\n"; + browser$g.homedir = function() { + return "/"; + }; + return browser$g; +} +var browserExports$3 = requireBrowser$g(); +const os = /* @__PURE__ */ getDefaultExportFromCjs(browserExports$3); +var pathExports = requirePath(); +const path = /* @__PURE__ */ getDefaultExportFromCjs(pathExports); +var utilExports = requireUtil$5(); +function noop$4() { +} +const spawn = noop$4; +const spawnSync = noop$4; +const execSync = noop$4; +const fork = noop$4; +const child_process = { + spawn, + spawnSync, + execSync, + fork +}; +const child_process$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: child_process, + execSync, + fork, + spawn, + spawnSync +}, Symbol.toStringTag, { value: "Module" })); +var lockfile$2 = {}; +const require$$2$1 = /* @__PURE__ */ getAugmentedNamespace(fs$1); +var retry$1 = {}; +var retry_operation; +var hasRequiredRetry_operation; +function requireRetry_operation() { + if (hasRequiredRetry_operation) return retry_operation; + hasRequiredRetry_operation = 1; + function RetryOperation(timeouts, options2) { + if (typeof options2 === "boolean") { + options2 = { forever: options2 }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options2 || {}; + this._maxRetryTime = options2 && options2.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } + } + retry_operation = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts; + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(this._errors.length - 1, this._errors.length); + this._timeouts = this._cachedTimeouts.slice(0); + timeout = this._timeouts.shift(); + } else { + return false; + } + } + var self2 = this; + var timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = function(fn) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i = 0; i < this._errors.length; i++) { + var error2 = this._errors[i]; + var message = error2.message; + var count = (counts[message] || 0) + 1; + counts[message] = count; + if (count >= mainErrorCount) { + mainError = error2; + mainErrorCount = count; + } + } + return mainError; + }; + return retry_operation; +} +var hasRequiredRetry$1; +function requireRetry$1() { + if (hasRequiredRetry$1) return retry$1; + hasRequiredRetry$1 = 1; + (function(exports) { + var RetryOperation = requireRetry_operation(); + exports.operation = function(options2) { + var timeouts = exports.timeouts(options2); + return new RetryOperation(timeouts, { + forever: options2 && options2.forever, + unref: options2 && options2.unref, + maxRetryTime: options2 && options2.maxRetryTime + }); + }; + exports.timeouts = function(options2) { + if (options2 instanceof Array) { + return [].concat(options2); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key2 in options2) { + opts[key2] = options2[key2]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + if (options2 && options2.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + timeouts.sort(function(a, b) { + return a - b; + }); + return timeouts; + }; + exports.createTimeout = function(attempt, opts) { + var random2 = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random2 * opts.minTimeout * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports.wrap = function(obj, options2, methods) { + if (options2 instanceof Array) { + methods = options2; + options2 = null; + } + if (!methods) { + methods = []; + for (var key2 in obj) { + if (typeof obj[key2] === "function") { + methods.push(key2); + } + } + } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + obj[method] = (function retryWrapper(original2) { + var op = exports.operation(options2); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); + op.attempt(function() { + original2.apply(obj, args); + }); + }).bind(obj, original); + obj[method].options = options2; + } + }; + })(retry$1); + return retry$1; +} +var retry; +var hasRequiredRetry; +function requireRetry() { + if (hasRequiredRetry) return retry; + hasRequiredRetry = 1; + retry = requireRetry$1(); + return retry; +} +var signalExit = { exports: {} }; +var signals = { exports: {} }; +var hasRequiredSignals; +function requireSignals() { + if (hasRequiredSignals) return signals.exports; + hasRequiredSignals = 1; + (function(module) { + module.exports = [ + "SIGABRT", + "SIGALRM", + "SIGHUP", + "SIGINT", + "SIGTERM" + ]; + if (process.platform !== "win32") { + module.exports.push( + "SIGVTALRM", + "SIGXCPU", + "SIGXFSZ", + "SIGUSR2", + "SIGTRAP", + "SIGSYS", + "SIGQUIT", + "SIGIOT" + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ); + } + if (process.platform === "linux") { + module.exports.push( + "SIGIO", + "SIGPOLL", + "SIGPWR", + "SIGSTKFLT", + "SIGUNUSED" + ); + } + })(signals); + return signals.exports; +} +var hasRequiredSignalExit; +function requireSignalExit() { + if (hasRequiredSignalExit) return signalExit.exports; + hasRequiredSignalExit = 1; + var process2 = commonjsGlobal.process; + const processOk = function(process3) { + return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function"; + }; + if (!processOk(process2)) { + signalExit.exports = function() { + return function() { + }; + }; + } else { + var assert2 = requireAssert(); + var signals2 = requireSignals(); + var isWin2 = /^win/i.test(process2.platform); + var EE = requireEvents(); + if (typeof EE !== "function") { + EE = EE.EventEmitter; + } + var emitter; + if (process2.__signal_exit_emitter__) { + emitter = process2.__signal_exit_emitter__; + } else { + emitter = process2.__signal_exit_emitter__ = new EE(); + emitter.count = 0; + emitter.emitted = {}; + } + if (!emitter.infinite) { + emitter.setMaxListeners(Infinity); + emitter.infinite = true; + } + signalExit.exports = function(cb, opts) { + if (!processOk(commonjsGlobal.process)) { + return function() { + }; + } + assert2.equal(typeof cb, "function", "a callback must be provided for exit handler"); + if (loaded === false) { + load(); + } + var ev = "exit"; + if (opts && opts.alwaysLast) { + ev = "afterexit"; + } + var remove = function() { + emitter.removeListener(ev, cb); + if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) { + unload(); + } + }; + emitter.on(ev, cb); + return remove; + }; + var unload = function unload2() { + if (!loaded || !processOk(commonjsGlobal.process)) { + return; + } + loaded = false; + signals2.forEach(function(sig) { + try { + process2.removeListener(sig, sigListeners[sig]); + } catch (er) { + } + }); + process2.emit = originalProcessEmit; + process2.reallyExit = originalProcessReallyExit; + emitter.count -= 1; + }; + signalExit.exports.unload = unload; + var emit = function emit2(event, code, signal) { + if (emitter.emitted[event]) { + return; + } + emitter.emitted[event] = true; + emitter.emit(event, code, signal); + }; + var sigListeners = {}; + signals2.forEach(function(sig) { + sigListeners[sig] = function listener() { + if (!processOk(commonjsGlobal.process)) { + return; + } + var listeners = process2.listeners(sig); + if (listeners.length === emitter.count) { + unload(); + emit("exit", null, sig); + emit("afterexit", null, sig); + if (isWin2 && sig === "SIGHUP") { + sig = "SIGINT"; + } + process2.kill(process2.pid, sig); + } + }; + }); + signalExit.exports.signals = function() { + return signals2; + }; + var loaded = false; + var load = function load2() { + if (loaded || !processOk(commonjsGlobal.process)) { + return; + } + loaded = true; + emitter.count += 1; + signals2 = signals2.filter(function(sig) { + try { + process2.on(sig, sigListeners[sig]); + return true; + } catch (er) { + return false; + } + }); + process2.emit = processEmit; + process2.reallyExit = processReallyExit; + }; + signalExit.exports.load = load; + var originalProcessReallyExit = process2.reallyExit; + var processReallyExit = function processReallyExit2(code) { + if (!processOk(commonjsGlobal.process)) { + return; + } + process2.exitCode = code || /* istanbul ignore next */ + 0; + emit("exit", process2.exitCode, null); + emit("afterexit", process2.exitCode, null); + originalProcessReallyExit.call(process2, process2.exitCode); + }; + var originalProcessEmit = process2.emit; + var processEmit = function processEmit2(ev, arg) { + if (ev === "exit" && processOk(commonjsGlobal.process)) { + if (arg !== void 0) { + process2.exitCode = arg; + } + var ret = originalProcessEmit.apply(this, arguments); + emit("exit", process2.exitCode, null); + emit("afterexit", process2.exitCode, null); + return ret; + } else { + return originalProcessEmit.apply(this, arguments); + } + }; + } + return signalExit.exports; +} +var hasRequiredLockfile; +function requireLockfile() { + if (hasRequiredLockfile) return lockfile$2; + hasRequiredLockfile = 1; + const path2 = requirePath(); + const fs2 = require$$2$1; + const retry2 = requireRetry(); + const onExit = requireSignalExit(); + const locks = {}; + const cacheSymbol = Symbol(); + function probe(file, fs3, callback) { + const cachedPrecision = fs3[cacheSymbol]; + if (cachedPrecision) { + return fs3.stat(file, (err, stat2) => { + if (err) { + return callback(err); + } + callback(null, stat2.mtime, cachedPrecision); + }); + } + const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5); + fs3.utimes(file, mtime, mtime, (err) => { + if (err) { + return callback(err); + } + fs3.stat(file, (err2, stat2) => { + if (err2) { + return callback(err2); + } + const precision = stat2.mtime.getTime() % 1e3 === 0 ? "s" : "ms"; + Object.defineProperty(fs3, cacheSymbol, { value: precision }); + callback(null, stat2.mtime, precision); + }); + }); + } + function getMtime(precision) { + let now = Date.now(); + if (precision === "s") { + now = Math.ceil(now / 1e3) * 1e3; + } + return new Date(now); + } + function getLockFile(file, options2) { + return options2.lockfilePath || `${file}.lock`; + } + function resolveCanonicalPath(file, options2, callback) { + if (!options2.realpath) { + return callback(null, path2.resolve(file)); + } + options2.fs.realpath(file, callback); + } + function acquireLock(file, options2, callback) { + const lockfilePath = getLockFile(file, options2); + options2.fs.mkdir(lockfilePath, (err) => { + if (!err) { + return probe(lockfilePath, options2.fs, (err2, mtime, mtimePrecision) => { + if (err2) { + options2.fs.rmdir(lockfilePath, () => { + }); + return callback(err2); + } + callback(null, mtime, mtimePrecision); + }); + } + if (err.code !== "EEXIST") { + return callback(err); + } + if (options2.stale <= 0) { + return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file })); + } + options2.fs.stat(lockfilePath, (err2, stat2) => { + if (err2) { + if (err2.code === "ENOENT") { + return acquireLock(file, { ...options2, stale: 0 }, callback); + } + return callback(err2); + } + if (!isLockStale(stat2, options2)) { + return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file })); + } + removeLock(file, options2, (err3) => { + if (err3) { + return callback(err3); + } + acquireLock(file, { ...options2, stale: 0 }, callback); + }); + }); + }); + } + function isLockStale(stat2, options2) { + return stat2.mtime.getTime() < Date.now() - options2.stale; + } + function removeLock(file, options2, callback) { + options2.fs.rmdir(getLockFile(file, options2), (err) => { + if (err && err.code !== "ENOENT") { + return callback(err); + } + callback(); + }); + } + function updateLock(file, options2) { + const lock2 = locks[file]; + if (lock2.updateTimeout) { + return; + } + lock2.updateDelay = lock2.updateDelay || options2.update; + lock2.updateTimeout = setTimeout(() => { + lock2.updateTimeout = null; + options2.fs.stat(lock2.lockfilePath, (err, stat2) => { + const isOverThreshold = lock2.lastUpdate + options2.stale < Date.now(); + if (err) { + if (err.code === "ENOENT" || isOverThreshold) { + return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" })); + } + lock2.updateDelay = 1e3; + return updateLock(file, options2); + } + const isMtimeOurs = lock2.mtime.getTime() === stat2.mtime.getTime(); + if (!isMtimeOurs) { + return setLockAsCompromised( + file, + lock2, + Object.assign( + new Error("Unable to update lock within the stale threshold"), + { code: "ECOMPROMISED" } + ) + ); + } + const mtime = getMtime(lock2.mtimePrecision); + options2.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => { + const isOverThreshold2 = lock2.lastUpdate + options2.stale < Date.now(); + if (lock2.released) { + return; + } + if (err2) { + if (err2.code === "ENOENT" || isOverThreshold2) { + return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" })); + } + lock2.updateDelay = 1e3; + return updateLock(file, options2); + } + lock2.mtime = mtime; + lock2.lastUpdate = Date.now(); + lock2.updateDelay = null; + updateLock(file, options2); + }); + }); + }, lock2.updateDelay); + if (lock2.updateTimeout.unref) { + lock2.updateTimeout.unref(); + } + } + function setLockAsCompromised(file, lock2, err) { + lock2.released = true; + if (lock2.updateTimeout) { + clearTimeout(lock2.updateTimeout); + } + if (locks[file] === lock2) { + delete locks[file]; + } + lock2.options.onCompromised(err); + } + function lock(file, options2, callback) { + options2 = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: fs2, + onCompromised: (err) => { + throw err; + }, + ...options2 + }; + options2.retries = options2.retries || 0; + options2.retries = typeof options2.retries === "number" ? { retries: options2.retries } : options2.retries; + options2.stale = Math.max(options2.stale || 0, 2e3); + options2.update = options2.update == null ? options2.stale / 2 : options2.update || 0; + options2.update = Math.max(Math.min(options2.update, options2.stale / 2), 1e3); + resolveCanonicalPath(file, options2, (err, file2) => { + if (err) { + return callback(err); + } + const operation = retry2.operation(options2.retries); + operation.attempt(() => { + acquireLock(file2, options2, (err2, mtime, mtimePrecision) => { + if (operation.retry(err2)) { + return; + } + if (err2) { + return callback(operation.mainError()); + } + const lock2 = locks[file2] = { + lockfilePath: getLockFile(file2, options2), + mtime, + mtimePrecision, + options: options2, + lastUpdate: Date.now() + }; + updateLock(file2, options2); + callback(null, (releasedCallback) => { + if (lock2.released) { + return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" })); + } + unlock(file2, { ...options2, realpath: false }, releasedCallback); + }); + }); + }); + }); + } + function unlock(file, options2, callback) { + options2 = { + fs: fs2, + realpath: true, + ...options2 + }; + resolveCanonicalPath(file, options2, (err, file2) => { + if (err) { + return callback(err); + } + const lock2 = locks[file2]; + if (!lock2) { + return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" })); + } + lock2.updateTimeout && clearTimeout(lock2.updateTimeout); + lock2.released = true; + delete locks[file2]; + removeLock(file2, options2, callback); + }); + } + function toPromise(method) { + return (...args) => new Promise((resolve, reject) => { + args.push((err, result) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + method(...args); + }); + } + let cleanupInitialized = false; + function ensureCleanup() { + if (cleanupInitialized) { + return; + } + cleanupInitialized = true; + onExit(() => { + for (const file in locks) { + const options2 = locks[file].options; + try { + options2.fs.rmdirSync(getLockFile(file, options2)); + } catch (e) { + } + } + }); + } + lockfile$2.lock = async (file, options2) => { + ensureCleanup(); + const release = await toPromise(lock)(file, options2); + return toPromise(release); + }; + return lockfile$2; +} +var safe = { exports: {} }; +var colors$2 = { exports: {} }; +var styles = { exports: {} }; +var hasRequiredStyles; +function requireStyles() { + if (hasRequiredStyles) return styles.exports; + hasRequiredStyles = 1; + (function(module) { + var styles2 = {}; + module["exports"] = styles2; + var codes = { + reset: [0, 0], + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49] + }; + Object.keys(codes).forEach(function(key2) { + var val = codes[key2]; + var style = styles2[key2] = []; + style.open = "\x1B[" + val[0] + "m"; + style.close = "\x1B[" + val[1] + "m"; + }); + })(styles); + return styles.exports; +} +var hasFlag; +var hasRequiredHasFlag; +function requireHasFlag() { + if (hasRequiredHasFlag) return hasFlag; + hasRequiredHasFlag = 1; + hasFlag = function(flag, argv) { + argv = argv || process.argv; + var terminatorPos = argv.indexOf("--"); + var prefix = /^-{1,2}/.test(flag) ? "" : "--"; + var pos = argv.indexOf(prefix + flag); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + return hasFlag; +} +var supportsColors; +var hasRequiredSupportsColors; +function requireSupportsColors() { + if (hasRequiredSupportsColors) return supportsColors; + hasRequiredSupportsColors = 1; + var os2 = requireBrowser$g(); + var hasFlag2 = requireHasFlag(); + var env = define_process_env_default; + var forceColor = void 0; + if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false")) { + forceColor = false; + } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) { + forceColor = true; + } + if ("FORCE_COLOR" in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(stream2) { + if (forceColor === false) { + return 0; + } + if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) { + return 3; + } + if (hasFlag2("color=256")) { + return 2; + } + if (stream2 && !stream2.isTTY && forceColor !== true) { + return 0; + } + var min2 = forceColor ? 1 : 0; + if (process.platform === "win32") { + var osRelease2 = os2.release().split("."); + if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease2[0]) >= 10 && Number(osRelease2[2]) >= 10586) { + return Number(osRelease2[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign2) { + return sign2 in env; + }) || env.CI_NAME === "codeship") { + return 1; + } + return min2; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if ("TERM_PROGRAM" in env) { + var version2 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version2 >= 3 ? 3 : 2; + case "Hyper": + return 3; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + if (env.TERM === "dumb") { + return min2; + } + return min2; + } + function getSupportLevel(stream2) { + var level = supportsColor(stream2); + return translateLevel(level); + } + supportsColors = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) + }; + return supportsColors; +} +var trap = { exports: {} }; +var hasRequiredTrap; +function requireTrap() { + if (hasRequiredTrap) return trap.exports; + hasRequiredTrap = 1; + (function(module) { + module["exports"] = function runTheTrap(text, options2) { + var result = ""; + text = text || "Run the trap, drop the bass"; + text = text.split(""); + var trap2 = { + 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: ["Ƶ", "ɀ"] + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap2[c] || [" "]; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap2[c] !== "undefined") { + result += trap2[c][rand]; + } else { + result += c; + } + }); + return result; + }; + })(trap); + return trap.exports; +} +var zalgo = { exports: {} }; +var hasRequiredZalgo; +function requireZalgo() { + if (hasRequiredZalgo) return zalgo.exports; + hasRequiredZalgo = 1; + (function(module) { + module["exports"] = function zalgo2(text, options2) { + text = text || " he is here "; + var soul = { + "up": [ + "̍", + "̎", + "̄", + "̅", + "̿", + "̑", + "̆", + "̐", + "͒", + "͗", + "͑", + "̇", + "̈", + "̊", + "͂", + "̓", + "̈", + "͊", + "͋", + "͌", + "̃", + "̂", + "̌", + "͐", + "̀", + "́", + "̋", + "̏", + "̒", + "̓", + "̔", + "̽", + "̉", + "ͣ", + "ͤ", + "ͥ", + "ͦ", + "ͧ", + "ͨ", + "ͩ", + "ͪ", + "ͫ", + "ͬ", + "ͭ", + "ͮ", + "ͯ", + "̾", + "͛", + "͆", + "̚" + ], + "down": [ + "̖", + "̗", + "̘", + "̙", + "̜", + "̝", + "̞", + "̟", + "̠", + "̤", + "̥", + "̦", + "̩", + "̪", + "̫", + "̬", + "̭", + "̮", + "̯", + "̰", + "̱", + "̲", + "̳", + "̹", + "̺", + "̻", + "̼", + "ͅ", + "͇", + "͈", + "͉", + "͍", + "͎", + "͓", + "͔", + "͕", + "͖", + "͙", + "͚", + "̣" + ], + "mid": [ + "̕", + "̛", + "̀", + "́", + "͘", + "̡", + "̢", + "̧", + "̨", + "̴", + "̵", + "̶", + "͜", + "͝", + "͞", + "͟", + "͠", + "͢", + "̸", + "̷", + "͡", + " ҉" + ] + }; + var all = [].concat(soul.up, soul.down, soul.mid); + function randomNumber(range2) { + var r = Math.floor(Math.random() * range2); + return r; + } + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = i === character; + }); + return bool; + } + function heComes(text2, options3) { + var result = ""; + var counts; + var l; + options3 = options3 || {}; + options3["up"] = typeof options3["up"] !== "undefined" ? options3["up"] : true; + options3["mid"] = typeof options3["mid"] !== "undefined" ? options3["mid"] : true; + options3["down"] = typeof options3["down"] !== "undefined" ? options3["down"] : true; + options3["size"] = typeof options3["size"] !== "undefined" ? options3["size"] : "maxi"; + text2 = text2.split(""); + for (l in text2) { + if (isChar(l)) { + continue; + } + result = result + text2[l]; + counts = { "up": 0, "down": 0, "mid": 0 }; + switch (options3.size) { + case "mini": + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case "maxi": + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + var arr = ["up", "mid", "down"]; + for (var d in arr) { + var index2 = arr[d]; + for (var i = 0; i <= counts[index2]; i++) { + if (options3[index2]) { + result = result + soul[index2][randomNumber(soul[index2].length)]; + } + } + } + } + return result; + } + return heComes(text, options2); + }; + })(zalgo); + return zalgo.exports; +} +var america = { exports: {} }; +var hasRequiredAmerica; +function requireAmerica() { + if (hasRequiredAmerica) return america.exports; + hasRequiredAmerica = 1; + (function(module) { + module["exports"] = function(colors2) { + return function(letter2, i, exploded) { + if (letter2 === " ") return letter2; + switch (i % 3) { + case 0: + return colors2.red(letter2); + case 1: + return colors2.white(letter2); + case 2: + return colors2.blue(letter2); + } + }; + }; + })(america); + return america.exports; +} +var zebra = { exports: {} }; +var hasRequiredZebra; +function requireZebra() { + if (hasRequiredZebra) return zebra.exports; + hasRequiredZebra = 1; + (function(module) { + module["exports"] = function(colors2) { + return function(letter2, i, exploded) { + return i % 2 === 0 ? letter2 : colors2.inverse(letter2); + }; + }; + })(zebra); + return zebra.exports; +} +var rainbow = { exports: {} }; +var hasRequiredRainbow; +function requireRainbow() { + if (hasRequiredRainbow) return rainbow.exports; + hasRequiredRainbow = 1; + (function(module) { + module["exports"] = function(colors2) { + var rainbowColors = ["red", "yellow", "green", "blue", "magenta"]; + return function(letter2, i, exploded) { + if (letter2 === " ") { + return letter2; + } else { + return colors2[rainbowColors[i++ % rainbowColors.length]](letter2); + } + }; + }; + })(rainbow); + return rainbow.exports; +} +var random = { exports: {} }; +var hasRequiredRandom; +function requireRandom() { + if (hasRequiredRandom) return random.exports; + hasRequiredRandom = 1; + (function(module) { + module["exports"] = function(colors2) { + var available = [ + "underline", + "inverse", + "grey", + "yellow", + "red", + "green", + "blue", + "white", + "cyan", + "magenta", + "brightYellow", + "brightRed", + "brightGreen", + "brightBlue", + "brightWhite", + "brightCyan", + "brightMagenta" + ]; + return function(letter2, i, exploded) { + return letter2 === " " ? letter2 : colors2[available[Math.round(Math.random() * (available.length - 2))]](letter2); + }; + }; + })(random); + return random.exports; +} +var hasRequiredColors; +function requireColors() { + if (hasRequiredColors) return colors$2.exports; + hasRequiredColors = 1; + (function(module) { + var colors2 = {}; + module["exports"] = colors2; + colors2.themes = {}; + var util2 = requireUtil$5(); + var ansiStyles = colors2.styles = requireStyles(); + var defineProps = Object.defineProperties; + var newLineRegex = new RegExp(/[\r\n]+/g); + colors2.supportsColor = requireSupportsColors().supportsColor; + if (typeof colors2.enabled === "undefined") { + colors2.enabled = colors2.supportsColor() !== false; + } + colors2.enable = function() { + colors2.enabled = true; + }; + colors2.disable = function() { + colors2.enabled = false; + }; + colors2.stripColors = colors2.strip = function(str) { + return ("" + str).replace(/\x1B\[\d+m/g, ""); + }; + colors2.stylize = function stylize(str, style) { + if (!colors2.enabled) { + return str + ""; + } + var styleMap = ansiStyles[style]; + if (!styleMap && style in colors2) { + return colors2[style](str); + } + return styleMap.open + str + styleMap.close; + }; + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + var escapeStringRegexp = function(str) { + if (typeof str !== "string") { + throw new TypeError("Expected a string"); + } + return str.replace(matchOperatorsRe, "\\$&"); + }; + function build2(_styles) { + var builder = function builder2() { + return applyStyle.apply(builder2, arguments); + }; + builder._styles = _styles; + builder.__proto__ = proto; + return builder; + } + var styles2 = function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key2) { + ansiStyles[key2].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key2].close), "g"); + ret[key2] = { + get: function() { + return build2(this._styles.concat(key2)); + } + }; + }); + return ret; + }(); + var proto = defineProps(function colors3() { + }, styles2); + function applyStyle() { + var args = Array.prototype.slice.call(arguments); + var str = args.map(function(arg) { + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util2.inspect(arg); + } + }).join(" "); + if (!colors2.enabled || !str) { + return str; + } + var newLinesPresent = str.indexOf("\n") != -1; + var nestedStyles = this._styles; + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); + } + } + return str; + } + colors2.setTheme = function(theme) { + if (typeof theme === "string") { + console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));"); + return; + } + for (var style in theme) { + (function(style2) { + colors2[style2] = function(str) { + if (typeof theme[style2] === "object") { + var out = str; + for (var i in theme[style2]) { + out = colors2[theme[style2][i]](out); + } + return out; + } + return colors2[theme[style2]](str); + }; + })(style); + } + }; + function init() { + var ret = {}; + Object.keys(styles2).forEach(function(name) { + ret[name] = { + get: function() { + return build2([name]); + } + }; + }); + return ret; + } + var sequencer = function sequencer2(map3, str) { + var exploded = str.split(""); + exploded = exploded.map(map3); + return exploded.join(""); + }; + colors2.trap = requireTrap(); + colors2.zalgo = requireZalgo(); + colors2.maps = {}; + colors2.maps.america = requireAmerica()(colors2); + colors2.maps.zebra = requireZebra()(colors2); + colors2.maps.rainbow = requireRainbow()(colors2); + colors2.maps.random = requireRandom()(colors2); + for (var map2 in colors2.maps) { + (function(map3) { + colors2[map3] = function(str) { + return sequencer(colors2.maps[map3], str); + }; + })(map2); + } + defineProps(colors2, init()); + })(colors$2); + return colors$2.exports; +} +var hasRequiredSafe; +function requireSafe() { + if (hasRequiredSafe) return safe.exports; + hasRequiredSafe = 1; + (function(module) { + var colors2 = requireColors(); + module["exports"] = colors2; + })(safe); + return safe.exports; +} +var safeExports = requireSafe(); +const colorsLibrary = /* @__PURE__ */ getDefaultExportFromCjs(safeExports); +var browser$f = { exports: {} }; +var ms; +var hasRequiredMs; +function requireMs() { + if (hasRequiredMs) return ms; + hasRequiredMs = 1; + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + ms = function(val, options2) { + options2 = options2 || {}; + var type2 = typeof val; + if (type2 === "string" && val.length > 0) { + return parse4(val); + } else if (type2 === "number" && isFinite(val)) { + return options2.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse4(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type2 = (match[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms2) { + var msAbs = Math.abs(ms2); + if (msAbs >= d) { + return Math.round(ms2 / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms2 / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms2 / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms2 / s) + "s"; + } + return ms2 + "ms"; + } + function fmtLong(ms2) { + var msAbs = Math.abs(ms2); + if (msAbs >= d) { + return plural(ms2, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms2, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms2, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms2, msAbs, s, "second"); + } + return ms2 + " ms"; + } + function plural(ms2, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : ""); + } + return ms; +} +var common$4; +var hasRequiredCommon$4; +function requireCommon$4() { + if (hasRequiredCommon$4) return common$4; + hasRequiredCommon$4 = 1; + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key2) => { + createDebug[key2] = env[key2]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0; i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; + } + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug2(...args) { + if (!debug2.enabled) { + return; + } + const self2 = debug2; + const curr = Number(/* @__PURE__ */ new Date()); + const ms2 = curr - (prevTime || curr); + self2.diff = ms2; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index2++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index2]; + match = formatter.call(self2, val); + args.splice(index2, 1); + index2--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug2.namespace = namespace; + debug2.useColors = createDebug.useColors(); + debug2.color = createDebug.selectColor(namespace); + debug2.extend = extend2; + debug2.destroy = createDebug.destroy; + Object.defineProperty(debug2, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug2); + } + return debug2; + } + function extend2(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + let i; + const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/); + const len = split.length; + for (i = 0; i < len; i++) { + if (!split[i]) { + continue; + } + namespaces = split[i].replace(/\*/g, ".*?"); + if (namespaces[0] === "-") { + createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$")); + } else { + createDebug.names.push(new RegExp("^" + namespaces + "$")); + } + } + } + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + if (name[name.length - 1] === "*") { + return true; + } + let i; + let len; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + return false; + } + function toNamespace(regexp) { + return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*"); + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + common$4 = setup; + return common$4; +} +var hasRequiredBrowser$f; +function requireBrowser$f() { + if (hasRequiredBrowser$f) return browser$f.exports; + hasRequiredBrowser$f = 1; + (function(module, exports) { + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.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" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index2++; + if (match === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c); + } + exports.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); + } else { + exports.storage.removeItem("debug"); + } + } catch (error2) { + } + } + function load() { + let r; + try { + r = exports.storage.getItem("debug"); + } catch (error2) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = define_process_env_default.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error2) { + } + } + module.exports = requireCommon$4()(exports); + const { formatters } = module.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error2) { + return "[UnexpectedJSONParseError]: " + error2.message; + } + }; + })(browser$f, browser$f.exports); + return browser$f.exports; +} +var browserExports$2 = requireBrowser$f(); +const debugLibrary = /* @__PURE__ */ getDefaultExportFromCjs(browserExports$2); +function Diff() { +} +Diff.prototype = { + diff: function diff(oldString, newString) { + var _options$timeout; + var options2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; + var callback = options2.callback; + if (typeof options2 === "function") { + callback = options2; + options2 = {}; + } + var self2 = this; + function done(value) { + value = self2.postProcess(value, options2); + if (callback) { + setTimeout(function() { + callback(value); + }, 0); + return true; + } else { + return value; + } + } + oldString = this.castInput(oldString, options2); + newString = this.castInput(newString, options2); + oldString = this.removeEmpty(this.tokenize(oldString, options2)); + newString = this.removeEmpty(this.tokenize(newString, options2)); + var newLen = newString.length, oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + if (options2.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options2.maxEditLength); + } + var maxExecutionTime = (_options$timeout = options2.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; + var abortAfterTimestamp = Date.now() + maxExecutionTime; + var bestPath = [{ + oldPos: -1, + lastComponent: void 0 + }]; + var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options2); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(buildValues(self2, bestPath[0].lastComponent, newString, oldString, self2.useLongestToken)); + } + var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + function execEditLength() { + for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + var basePath = void 0; + var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + bestPath[diagonalPath - 1] = void 0; + } + var canAdd = false; + if (addPath) { + var addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + var canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = void 0; + continue; + } + if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { + basePath = self2.addToPath(addPath, true, false, 0, options2); + } else { + basePath = self2.addToPath(removePath, false, true, 1, options2); + } + newPos = self2.extractCommon(basePath, newString, oldString, diagonalPath, options2); + if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(buildValues(self2, basePath.lastComponent, newString, oldString, self2.useLongestToken)); + } else { + bestPath[diagonalPath] = basePath; + if (basePath.oldPos + 1 >= oldLen) { + maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); + } + if (newPos + 1 >= newLen) { + minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); + } + } + } + editLength++; + } + if (callback) { + (function exec() { + setTimeout(function() { + if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { + return callback(); + } + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }, + addToPath: function addToPath(path2, added, removed, oldPosInc, options2) { + var last = path2.lastComponent; + if (last && !options2.oneChangePerToken && last.added === added && last.removed === removed) { + return { + oldPos: path2.oldPos + oldPosInc, + lastComponent: { + count: last.count + 1, + added, + removed, + previousComponent: last.previousComponent + } + }; + } else { + return { + oldPos: path2.oldPos + oldPosInc, + lastComponent: { + count: 1, + added, + removed, + previousComponent: last + } + }; + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options2) { + var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options2)) { + newPos++; + oldPos++; + commonCount++; + if (options2.oneChangePerToken) { + basePath.lastComponent = { + count: 1, + previousComponent: basePath.lastComponent, + added: false, + removed: false + }; + } + } + if (commonCount && !options2.oneChangePerToken) { + basePath.lastComponent = { + count: commonCount, + previousComponent: basePath.lastComponent, + added: false, + removed: false + }; + } + basePath.oldPos = oldPos; + return newPos; + }, + equals: function equals(left, right, options2) { + if (options2.comparator) { + return options2.comparator(left, right); + } else { + return left === right || options2.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return Array.from(value); + }, + join: function join(chars) { + return chars.join(""); + }, + postProcess: function postProcess(changeObjects) { + return changeObjects; + } +}; +function buildValues(diff3, lastComponent, newString, oldString, useLongestToken) { + var components = []; + var nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function(value2, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value2.length ? oldValue : value2; + }); + component.value = diff3.join(value); + } else { + component.value = diff3.join(newString.slice(newPos, newPos + component.count)); + } + newPos += component.count; + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff3.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; +} +var characterDiff = new Diff(); +function diffChars(oldStr, newStr, options2) { + return characterDiff.diff(oldStr, newStr, options2); +} +function longestCommonPrefix(str1, str2) { + var i; + for (i = 0; i < str1.length && i < str2.length; i++) { + if (str1[i] != str2[i]) { + return str1.slice(0, i); + } + } + return str1.slice(0, i); +} +function longestCommonSuffix(str1, str2) { + var i; + if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { + return ""; + } + for (i = 0; i < str1.length && i < str2.length; i++) { + if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { + return str1.slice(-i); + } + } + return str1.slice(-i); +} +function replacePrefix(string2, oldPrefix, newPrefix) { + if (string2.slice(0, oldPrefix.length) != oldPrefix) { + throw Error("string ".concat(JSON.stringify(string2), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug")); + } + return newPrefix + string2.slice(oldPrefix.length); +} +function replaceSuffix(string2, oldSuffix, newSuffix) { + if (!oldSuffix) { + return string2 + newSuffix; + } + if (string2.slice(-oldSuffix.length) != oldSuffix) { + throw Error("string ".concat(JSON.stringify(string2), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug")); + } + return string2.slice(0, -oldSuffix.length) + newSuffix; +} +function removePrefix(string2, oldPrefix) { + return replacePrefix(string2, oldPrefix, ""); +} +function removeSuffix(string2, oldSuffix) { + return replaceSuffix(string2, oldSuffix, ""); +} +function maximumOverlap(string1, string2) { + return string2.slice(0, overlapCount(string1, string2)); +} +function overlapCount(a, b) { + var startA = 0; + if (a.length > b.length) { + startA = a.length - b.length; + } + var endB = b.length; + if (a.length < b.length) { + endB = a.length; + } + var map2 = Array(endB); + var k = 0; + map2[0] = 0; + for (var j = 1; j < endB; j++) { + if (b[j] == b[k]) { + map2[j] = map2[k]; + } else { + map2[j] = k; + } + while (k > 0 && b[j] != b[k]) { + k = map2[k]; + } + if (b[j] == b[k]) { + k++; + } + } + k = 0; + for (var i = startA; i < a.length; i++) { + while (k > 0 && a[i] != b[k]) { + k = map2[k]; + } + if (a[i] == b[k]) { + k++; + } + } + return k; +} +function hasOnlyWinLineEndings(string2) { + return string2.includes("\r\n") && !string2.startsWith("\n") && !string2.match(/[^\r]\n/); +} +function hasOnlyUnixLineEndings(string2) { + return !string2.includes("\r\n") && string2.includes("\n"); +} +var extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}"; +var tokenizeIncludingWhitespace = new RegExp("[".concat(extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), "ug"); +var wordDiff = new Diff(); +wordDiff.equals = function(left, right, options2) { + if (options2.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + return left.trim() === right.trim(); +}; +wordDiff.tokenize = function(value) { + var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var parts; + if (options2.intlSegmenter) { + if (options2.intlSegmenter.resolvedOptions().granularity != "word") { + throw new Error('The segmenter passed must have a granularity of "word"'); + } + parts = Array.from(options2.intlSegmenter.segment(value), function(segment) { + return segment.segment; + }); + } else { + parts = value.match(tokenizeIncludingWhitespace) || []; + } + var tokens = []; + var prevPart = null; + parts.forEach(function(part) { + if (/\s/.test(part)) { + if (prevPart == null) { + tokens.push(part); + } else { + tokens.push(tokens.pop() + part); + } + } else if (/\s/.test(prevPart)) { + if (tokens[tokens.length - 1] == prevPart) { + tokens.push(tokens.pop() + part); + } else { + tokens.push(prevPart + part); + } + } else { + tokens.push(part); + } + prevPart = part; + }); + return tokens; +}; +wordDiff.join = function(tokens) { + return tokens.map(function(token, i) { + if (i == 0) { + return token; + } else { + return token.replace(/^\s+/, ""); + } + }).join(""); +}; +wordDiff.postProcess = function(changes, options2) { + if (!changes || options2.oneChangePerToken) { + return changes; + } + var lastKeep = null; + var insertion = null; + var deletion = null; + changes.forEach(function(change) { + if (change.added) { + insertion = change; + } else if (change.removed) { + deletion = change; + } else { + if (insertion || deletion) { + dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change); + } + lastKeep = change; + insertion = null; + deletion = null; + } + }); + if (insertion || deletion) { + dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null); + } + return changes; +}; +function diffWords(oldStr, newStr, options2) { + if ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreWhitespace) != null && !options2.ignoreWhitespace) { + return diffWordsWithSpace(oldStr, newStr, options2); + } + return wordDiff.diff(oldStr, newStr, options2); +} +function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) { + if (deletion && insertion) { + var oldWsPrefix = deletion.value.match(/^\s*/)[0]; + var oldWsSuffix = deletion.value.match(/\s*$/)[0]; + var newWsPrefix = insertion.value.match(/^\s*/)[0]; + var newWsSuffix = insertion.value.match(/\s*$/)[0]; + if (startKeep) { + var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix); + startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix); + deletion.value = removePrefix(deletion.value, commonWsPrefix); + insertion.value = removePrefix(insertion.value, commonWsPrefix); + } + if (endKeep) { + var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix); + endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix); + deletion.value = removeSuffix(deletion.value, commonWsSuffix); + insertion.value = removeSuffix(insertion.value, commonWsSuffix); + } + } else if (insertion) { + if (startKeep) { + insertion.value = insertion.value.replace(/^\s*/, ""); + } + if (endKeep) { + endKeep.value = endKeep.value.replace(/^\s*/, ""); + } + } else if (startKeep && endKeep) { + var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0]; + var newWsStart = longestCommonPrefix(newWsFull, delWsStart); + deletion.value = removePrefix(deletion.value, newWsStart); + var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd); + deletion.value = removeSuffix(deletion.value, newWsEnd); + endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd); + startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); + } else if (endKeep) { + var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0]; + var deletionWsSuffix = deletion.value.match(/\s*$/)[0]; + var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix); + deletion.value = removeSuffix(deletion.value, overlap); + } else if (startKeep) { + var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0]; + var deletionWsPrefix = deletion.value.match(/^\s*/)[0]; + var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); + deletion.value = removePrefix(deletion.value, _overlap); + } +} +var wordWithSpaceDiff = new Diff(); +wordWithSpaceDiff.tokenize = function(value) { + var regex = new RegExp("(\\r?\\n)|[".concat(extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), "ug"); + return value.match(regex) || []; +}; +function diffWordsWithSpace(oldStr, newStr, options2) { + return wordWithSpaceDiff.diff(oldStr, newStr, options2); +} +function generateOptions(options2, defaults) { + if (typeof options2 === "function") { + defaults.callback = options2; + } else if (options2) { + for (var name in options2) { + if (options2.hasOwnProperty(name)) { + defaults[name] = options2[name]; + } + } + } + return defaults; +} +var lineDiff = new Diff(); +lineDiff.tokenize = function(value, options2) { + if (options2.stripTrailingCr) { + value = value.replace(/\r\n/g, "\n"); + } + var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + if (i % 2 && !options2.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + retLines.push(line); + } + } + return retLines; +}; +lineDiff.equals = function(left, right, options2) { + if (options2.ignoreWhitespace) { + if (!options2.newlineIsToken || !left.includes("\n")) { + left = left.trim(); + } + if (!options2.newlineIsToken || !right.includes("\n")) { + right = right.trim(); + } + } else if (options2.ignoreNewlineAtEof && !options2.newlineIsToken) { + if (left.endsWith("\n")) { + left = left.slice(0, -1); + } + if (right.endsWith("\n")) { + right = right.slice(0, -1); + } + } + return Diff.prototype.equals.call(this, left, right, options2); +}; +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} +function diffTrimmedLines(oldStr, newStr, callback) { + var options2 = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options2); +} +var sentenceDiff = new Diff(); +sentenceDiff.tokenize = function(value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} +var cssDiff = new Diff(); +cssDiff.tokenize = function(value) { + return value.split(/([{}:;,]|\s+)/); +}; +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} +function ownKeys(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; +} +function _objectSpread2(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { + _defineProperty(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; +} +function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _typeof(o) { + "@babel/helpers - typeof"; + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { + return typeof o2; + } : function(o2) { + return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; + }, _typeof(o); +} +function _defineProperty(obj, key2, value) { + key2 = _toPropertyKey(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { + value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key2] = value; + } + return obj; +} +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; +} +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +var jsonDiff = new Diff(); +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; +jsonDiff.castInput = function(value, options2) { + var undefinedReplacement = options2.undefinedReplacement, _options$stringifyRep = options2.stringifyReplacer, stringifyReplacer = _options$stringifyRep === void 0 ? function(k, v) { + return typeof v === "undefined" ? undefinedReplacement : v; + } : _options$stringifyRep; + return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " "); +}; +jsonDiff.equals = function(left, right, options2) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"), options2); +}; +function diffJson(oldObj, newObj, options2) { + return jsonDiff.diff(oldObj, newObj, options2); +} +function canonicalize(obj, stack, replacementStack, replacer, key2) { + stack = stack || []; + replacementStack = replacementStack || []; + if (replacer) { + obj = replacer(key2, obj); + } + var i; + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + var canonicalizedObj; + if ("[object Array]" === Object.prototype.toString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key2); + } + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + if (_typeof(obj) === "object" && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], _key; + for (_key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, _key)) { + sortedKeys.push(_key); + } + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + return canonicalizedObj; +} +var arrayDiff = new Diff(); +arrayDiff.tokenize = function(value) { + return value.slice(); +}; +arrayDiff.join = arrayDiff.removeEmpty = function(value) { + return value; +}; +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} +function unixToWin(patch) { + if (Array.isArray(patch)) { + return patch.map(unixToWin); + } + return _objectSpread2(_objectSpread2({}, patch), {}, { + hunks: patch.hunks.map(function(hunk) { + return _objectSpread2(_objectSpread2({}, hunk), {}, { + lines: hunk.lines.map(function(line, i) { + var _hunk$lines; + return line.startsWith("\\") || line.endsWith("\r") || (_hunk$lines = hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && _hunk$lines.startsWith("\\") ? line : line + "\r"; + }) + }); + }) + }); +} +function winToUnix(patch) { + if (Array.isArray(patch)) { + return patch.map(winToUnix); + } + return _objectSpread2(_objectSpread2({}, patch), {}, { + hunks: patch.hunks.map(function(hunk) { + return _objectSpread2(_objectSpread2({}, hunk), {}, { + lines: hunk.lines.map(function(line) { + return line.endsWith("\r") ? line.substring(0, line.length - 1) : line; + }) + }); + }) + }); +} +function isUnix(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; + } + return !patch.some(function(index2) { + return index2.hunks.some(function(hunk) { + return hunk.lines.some(function(line) { + return !line.startsWith("\\") && line.endsWith("\r"); + }); + }); + }); +} +function isWin(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; + } + return patch.some(function(index2) { + return index2.hunks.some(function(hunk) { + return hunk.lines.some(function(line) { + return line.endsWith("\r"); + }); + }); + }) && patch.every(function(index2) { + return index2.hunks.every(function(hunk) { + return hunk.lines.every(function(line, i) { + var _hunk$lines2; + return line.startsWith("\\") || line.endsWith("\r") || ((_hunk$lines2 = hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : _hunk$lines2.startsWith("\\")); + }); + }); + }); +} +function parsePatch(uniDiff) { + var diffstr = uniDiff.split(/\n/), list = [], i = 0; + function parseIndex() { + var index2 = {}; + list.push(index2); + while (i < diffstr.length) { + var line = diffstr[i]; + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + if (header) { + index2.index = header[1]; + } + i++; + } + parseFileHeader(index2); + parseFileHeader(index2); + index2.hunks = []; + while (i < diffstr.length) { + var _line = diffstr[i]; + if (/^(Index:\s|diff\s|\-\-\-\s|\+\+\+\s|===================================================================)/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index2.hunks.push(parseHunk()); + } else if (_line) { + throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(_line)); + } else { + i++; + } + } + } + function parseFileHeader(index2) { + var fileHeader = /^(---|\+\+\+)\s+(.*)\r?$/.exec(diffstr[i]); + if (fileHeader) { + var keyPrefix = fileHeader[1] === "---" ? "old" : "new"; + var data2 = fileHeader[2].split(" ", 2); + var fileName = data2[0].replace(/\\\\/g, "\\"); + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + index2[keyPrefix + "FileName"] = fileName; + index2[keyPrefix + "Header"] = (data2[1] || "").trim(); + i++; + } + } + function parseHunk() { + var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2], + newStart: +chunkHeader[3], + newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4], + lines: [] + }; + if (hunk.oldLines === 0) { + hunk.oldStart += 1; + } + if (hunk.newLines === 0) { + hunk.newStart += 1; + } + var addCount = 0, removeCount = 0; + for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || (_diffstr$i = diffstr[i]) !== null && _diffstr$i !== void 0 && _diffstr$i.startsWith("\\")); i++) { + var _diffstr$i; + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0]; + if (operation === "+" || operation === "-" || operation === " " || operation === "\\") { + hunk.lines.push(diffstr[i]); + if (operation === "+") { + addCount++; + } else if (operation === "-") { + removeCount++; + } else if (operation === " ") { + addCount++; + removeCount++; + } + } else { + throw new Error("Hunk at line ".concat(chunkHeaderIndex + 1, " contained invalid line ").concat(diffstr[i])); + } + } + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } + if (addCount !== hunk.newLines) { + throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + } + if (removeCount !== hunk.oldLines) { + throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + } + return hunk; + } + while (i < diffstr.length) { + parseIndex(); + } + return list; +} +function distanceIterator(start, minLine, maxLine) { + var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } + if (start + localOffset <= maxLine) { + return start + localOffset; + } + forwardExhausted = true; + } + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } + if (minLine <= start - localOffset) { + return start - localOffset++; + } + backwardExhausted = true; + return iterator(); + } + }; +} +function applyPatch(source2, uniDiff) { + var options2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; + if (typeof uniDiff === "string") { + uniDiff = parsePatch(uniDiff); + } + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error("applyPatch only works with a single input."); + } + uniDiff = uniDiff[0]; + } + if (options2.autoConvertLineEndings || options2.autoConvertLineEndings == null) { + if (hasOnlyWinLineEndings(source2) && isUnix(uniDiff)) { + uniDiff = unixToWin(uniDiff); + } else if (hasOnlyUnixLineEndings(source2) && isWin(uniDiff)) { + uniDiff = winToUnix(uniDiff); + } + } + var lines = source2.split("\n"), hunks = uniDiff.hunks, compareLine = options2.compareLine || function(lineNumber, line2, operation, patchContent) { + return line2 === patchContent; + }, fuzzFactor = options2.fuzzFactor || 0, minLine = 0; + if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { + throw new Error("fuzzFactor must be a non-negative integer"); + } + if (!hunks.length) { + return source2; + } + var prevLine = "", removeEOFNL = false, addEOFNL = false; + for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) { + var line = hunks[hunks.length - 1].lines[i]; + if (line[0] == "\\") { + if (prevLine[0] == "+") { + removeEOFNL = true; + } else if (prevLine[0] == "-") { + addEOFNL = true; + } + } + prevLine = line; + } + if (removeEOFNL) { + if (addEOFNL) { + if (!fuzzFactor && lines[lines.length - 1] == "") { + return false; + } + } else if (lines[lines.length - 1] == "") { + lines.pop(); + } else if (!fuzzFactor) { + return false; + } + } else if (addEOFNL) { + if (lines[lines.length - 1] != "") { + lines.push(""); + } else if (!fuzzFactor) { + return false; + } + } + function applyHunk(hunkLines, toPos2, maxErrors2) { + var hunkLinesI = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; + var lastContextLineMatched = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true; + var patchedLines = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : []; + var patchedLinesLength = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : 0; + var nConsecutiveOldContextLines = 0; + var nextContextLineMustMatch = false; + for (; hunkLinesI < hunkLines.length; hunkLinesI++) { + var hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : " ", content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; + if (operation === "-") { + if (compareLine(toPos2 + 1, lines[toPos2], operation, content)) { + toPos2++; + nConsecutiveOldContextLines = 0; + } else { + if (!maxErrors2 || lines[toPos2] == null) { + return null; + } + patchedLines[patchedLinesLength] = lines[toPos2]; + return applyHunk(hunkLines, toPos2 + 1, maxErrors2 - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); + } + } + if (operation === "+") { + if (!lastContextLineMatched) { + return null; + } + patchedLines[patchedLinesLength] = content; + patchedLinesLength++; + nConsecutiveOldContextLines = 0; + nextContextLineMustMatch = true; + } + if (operation === " ") { + nConsecutiveOldContextLines++; + patchedLines[patchedLinesLength] = lines[toPos2]; + if (compareLine(toPos2 + 1, lines[toPos2], operation, content)) { + patchedLinesLength++; + lastContextLineMatched = true; + nextContextLineMustMatch = false; + toPos2++; + } else { + if (nextContextLineMustMatch || !maxErrors2) { + return null; + } + return lines[toPos2] && (applyHunk(hunkLines, toPos2 + 1, maxErrors2 - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos2 + 1, maxErrors2 - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos2, maxErrors2 - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); + } + } + } + patchedLinesLength -= nConsecutiveOldContextLines; + toPos2 -= nConsecutiveOldContextLines; + patchedLines.length = patchedLinesLength; + return { + patchedLines, + oldLineLastI: toPos2 - 1 + }; + } + var resultLines = []; + var prevHunkOffset = 0; + for (var _i2 = 0; _i2 < hunks.length; _i2++) { + var hunk = hunks[_i2]; + var hunkResult = void 0; + var maxLine = lines.length - hunk.oldLines + fuzzFactor; + var toPos = void 0; + for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { + toPos = hunk.oldStart + prevHunkOffset - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + for (; toPos !== void 0; toPos = iterator()) { + hunkResult = applyHunk(hunk.lines, toPos, maxErrors); + if (hunkResult) { + break; + } + } + if (hunkResult) { + break; + } + } + if (!hunkResult) { + return false; + } + for (var _i22 = minLine; _i22 < toPos; _i22++) { + resultLines.push(lines[_i22]); + } + for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) { + var _line = hunkResult.patchedLines[_i3]; + resultLines.push(_line); + } + minLine = hunkResult.oldLineLastI + 1; + prevHunkOffset = toPos + 1 - hunk.oldStart; + } + for (var _i4 = minLine; _i4 < lines.length; _i4++) { + resultLines.push(lines[_i4]); + } + return resultLines.join("\n"); +} +function applyPatches(uniDiff, options2) { + if (typeof uniDiff === "string") { + uniDiff = parsePatch(uniDiff); + } + var currentIndex = 0; + function processIndex() { + var index2 = uniDiff[currentIndex++]; + if (!index2) { + return options2.complete(); + } + options2.loadFile(index2, function(err, data2) { + if (err) { + return options2.complete(err); + } + var updatedContent = applyPatch(data2, index2, options2); + options2.patched(index2, updatedContent, function(err2) { + if (err2) { + return options2.complete(err2); + } + processIndex(); + }); + }); + } + processIndex(); +} +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options2) { + if (!options2) { + options2 = {}; + } + if (typeof options2 === "function") { + options2 = { + callback: options2 + }; + } + if (typeof options2.context === "undefined") { + options2.context = 4; + } + if (options2.newlineIsToken) { + throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); + } + if (!options2.callback) { + return diffLinesResultToPatch(diffLines(oldStr, newStr, options2)); + } else { + var _options = options2, _callback = _options.callback; + diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options2), {}, { + callback: function callback(diff3) { + var patch = diffLinesResultToPatch(diff3); + _callback(patch); + } + })); + } + function diffLinesResultToPatch(diff3) { + if (!diff3) { + return; + } + diff3.push({ + value: "", + lines: [] + }); + function contextLines(lines) { + return lines.map(function(entry) { + return " " + entry; + }); + } + var hunks = []; + var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + var _loop = function _loop2() { + var current2 = diff3[i], lines = current2.lines || splitLines$1(current2.value); + current2.lines = lines; + if (current2.added || current2.removed) { + var _curRange; + if (!oldRangeStart) { + var prev = diff3[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = options2.context > 0 ? contextLines(prev.lines.slice(-options2.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) { + return (current2.added ? "+" : "-") + entry; + }))); + if (current2.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + if (lines.length <= options2.context * 2 && i < diff3.length - 2) { + var _curRange2; + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + var contextSize = Math.min(lines.length, options2.context); + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + var _hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + hunks.push(_hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + }; + for (var i = 0; i < diff3.length; i++) { + _loop(); + } + for (var _i2 = 0, _hunks = hunks; _i2 < _hunks.length; _i2++) { + var hunk = _hunks[_i2]; + for (var _i22 = 0; _i22 < hunk.lines.length; _i22++) { + if (hunk.lines[_i22].endsWith("\n")) { + hunk.lines[_i22] = hunk.lines[_i22].slice(0, -1); + } else { + hunk.lines.splice(_i22 + 1, 0, "\\ No newline at end of file"); + _i22++; + } + } + } + return { + oldFileName, + newFileName, + oldHeader, + newHeader, + hunks + }; + } +} +function formatPatch(diff3) { + if (Array.isArray(diff3)) { + return diff3.map(formatPatch).join("\n"); + } + var ret = []; + if (diff3.oldFileName == diff3.newFileName) { + ret.push("Index: " + diff3.oldFileName); + } + ret.push("==================================================================="); + ret.push("--- " + diff3.oldFileName + (typeof diff3.oldHeader === "undefined" ? "" : " " + diff3.oldHeader)); + ret.push("+++ " + diff3.newFileName + (typeof diff3.newHeader === "undefined" ? "" : " " + diff3.newHeader)); + for (var i = 0; i < diff3.hunks.length; i++) { + var hunk = diff3.hunks[i]; + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; + } + if (hunk.newLines === 0) { + hunk.newStart -= 1; + } + ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); + ret.push.apply(ret, hunk.lines); + } + return ret.join("\n") + "\n"; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options2) { + var _options2; + if (typeof options2 === "function") { + options2 = { + callback: options2 + }; + } + if (!((_options2 = options2) !== null && _options2 !== void 0 && _options2.callback)) { + var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options2); + if (!patchObj) { + return; + } + return formatPatch(patchObj); + } else { + var _options3 = options2, _callback2 = _options3.callback; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options2), {}, { + callback: function callback(patchObj2) { + if (!patchObj2) { + _callback2(); + } else { + _callback2(formatPatch(patchObj2)); + } + } + })); + } +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options2) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options2); +} +function splitLines$1(text) { + var hasTrailingNl = text.endsWith("\n"); + var result = text.split("\n").map(function(line) { + return line + "\n"; + }); + if (hasTrailingNl) { + result.pop(); + } else { + result.push(result.pop().slice(0, -1)); + } + return result; +} +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + return arrayStartsWith(a, b); +} +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + return true; +} +function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; + if (oldLines !== void 0) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + if (newLines !== void 0) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} +function merge$1(mine, theirs, base2) { + mine = loadPatch(mine, base2); + theirs = loadPatch(theirs, base2); + var ret = {}; + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + ret.hunks = []; + var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + if (hunkBefore(mineCurrent, theirsCurrent)) { + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + return ret; +} +function loadPatch(param, base2) { + if (typeof param === "string") { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + if (!base2) { + throw new Error("Must provide a base reference or pass in a patch"); + } + return structuredPatch(void 0, void 0, base2, param); + } + return param; +} +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} +function selectField(index2, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index2.conflict = true; + return { + mine, + theirs + }; + } +} +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} +function cloneHunk(hunk, offset2) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset2, + newLines: hunk.newLines, + lines: hunk.lines + }; +} +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; + if ((mineCurrent[0] === "-" || mineCurrent[0] === "+") && (theirCurrent[0] === "-" || theirCurrent[0] === "+")) { + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === "+" && theirCurrent[0] === " ") { + var _hunk$lines; + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === "+" && mineCurrent[0] === " ") { + var _hunk$lines2; + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === "-" && theirCurrent[0] === " ") { + removal(hunk, mine, their); + } else if (theirCurrent[0] === "-" && mineCurrent[0] === " ") { + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + conflict(hunk, collectChange(mine), collectChange(their)); + } + } + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), theirChanges = collectChange(their); + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + return; + } + conflict(hunk, myChanges, theirChanges); +} +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); + if (theirChanges.merged) { + var _hunk$lines6; + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine, + theirs: their + }); +} +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} +function collectChange(state2) { + var ret = [], operation = state2.lines[state2.index][0]; + while (state2.index < state2.lines.length) { + var line = state2.lines[state2.index]; + if (operation === "-" && line[0] === "+") { + operation = "+"; + } + if (operation === line[0]) { + ret.push(line); + state2.index++; + } else { + break; + } + } + return ret; +} +function collectContext(state2, matchChanges) { + var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; + while (matchIndex < matchChanges.length && state2.index < state2.lines.length) { + var change = state2.lines[state2.index], match = matchChanges[matchIndex]; + if (match[0] === "+") { + break; + } + contextChanges = contextChanges || change[0] !== " "; + merged.push(match); + matchIndex++; + if (change[0] === "+") { + conflicted = true; + while (change[0] === "+") { + changes.push(change); + change = state2.lines[++state2.index]; + } + } + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state2.index++; + } else { + conflicted = true; + } + } + if ((matchChanges[matchIndex] || "")[0] === "+" && contextChanges) { + conflicted = true; + } + if (conflicted) { + return changes; + } + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + return { + merged, + changes + }; +} +function allRemoves(changes) { + return changes.reduce(function(prev, change) { + return prev && change[0] === "-"; + }, true); +} +function skipRemoveSuperset(state2, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + if (state2.lines[state2.index + i] !== " " + changeContent) { + return false; + } + } + state2.index += delta; + return true; +} +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function(line) { + if (typeof line !== "string") { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + if (oldLines !== void 0) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = void 0; + } + } + if (newLines !== void 0) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = void 0; + } + } + } else { + if (newLines !== void 0 && (line[0] === "+" || line[0] === " ")) { + newLines++; + } + if (oldLines !== void 0 && (line[0] === "-" || line[0] === " ")) { + oldLines++; + } + } + }); + return { + oldLines, + newLines + }; +} +function reversePatch(structuredPatch2) { + if (Array.isArray(structuredPatch2)) { + return structuredPatch2.map(reversePatch).reverse(); + } + return _objectSpread2(_objectSpread2({}, structuredPatch2), {}, { + oldFileName: structuredPatch2.newFileName, + oldHeader: structuredPatch2.newHeader, + newFileName: structuredPatch2.oldFileName, + newHeader: structuredPatch2.oldHeader, + hunks: structuredPatch2.hunks.map(function(hunk) { + return { + oldLines: hunk.newLines, + oldStart: hunk.newStart, + newLines: hunk.oldLines, + newStart: hunk.oldStart, + lines: hunk.lines.map(function(l) { + if (l.startsWith("-")) { + return "+".concat(l.slice(1)); + } + if (l.startsWith("+")) { + return "-".concat(l.slice(1)); + } + return l; + }) + }; + }) + }); +} +function convertChangesToDMP(changes) { + var ret = [], change, operation; + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + ret.push([operation, change.value]); + } + return ret; +} +function convertChangesToXML(changes) { + var ret = []; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push(""); + } else if (change.removed) { + ret.push(""); + } + ret.push(escapeHTML$1(change.value)); + if (change.added) { + ret.push(""); + } else if (change.removed) { + ret.push(""); + } + } + return ret.join(""); +} +function escapeHTML$1(s) { + var n = s; + n = n.replace(/&/g, "&"); + n = n.replace(//g, ">"); + n = n.replace(/"/g, """); + return n; +} +const diffLibrary = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Diff, + applyPatch, + applyPatches, + canonicalize, + convertChangesToDMP, + convertChangesToXML, + createPatch, + createTwoFilesPatch, + diffArrays, + diffChars, + diffCss, + diffJson, + diffLines, + diffSentences, + diffTrimmedLines, + diffWords, + diffWordsWithSpace, + formatPatch, + merge: merge$1, + parsePatch, + reversePatch, + structuredPatch +}, Symbol.toStringTag, { value: "Module" })); +var main = { exports: {} }; +var cryptoBrowserify = {}; +var browser$e = { exports: {} }; +var hasRequiredBrowser$e; +function requireBrowser$e() { + if (hasRequiredBrowser$e) return browser$e.exports; + hasRequiredBrowser$e = 1; + var MAX_BYTES = 65536; + var MAX_UINT32 = 4294967295; + function oldBrowser() { + throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11"); + } + var Buffer2 = requireSafeBuffer().Buffer; + var crypto2 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + if (crypto2 && crypto2.getRandomValues) { + browser$e.exports = randomBytes; + } else { + browser$e.exports = oldBrowser; + } + function randomBytes(size, cb) { + if (size > MAX_UINT32) throw new RangeError("requested too many random bytes"); + var bytes = Buffer2.allocUnsafe(size); + if (size > 0) { + if (size > MAX_BYTES) { + for (var generated = 0; generated < size; generated += MAX_BYTES) { + crypto2.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); + } + } else { + crypto2.getRandomValues(bytes); + } + } + if (typeof cb === "function") { + return process.nextTick(function() { + cb(null, bytes); + }); + } + return bytes; + } + return browser$e.exports; +} +var readableBrowser$2 = { exports: {} }; +var streamBrowser$2; +var hasRequiredStreamBrowser$2; +function requireStreamBrowser$2() { + if (hasRequiredStreamBrowser$2) return streamBrowser$2; + hasRequiredStreamBrowser$2 = 1; + streamBrowser$2 = requireEvents().EventEmitter; + return streamBrowser$2; +} +var buffer_list$2; +var hasRequiredBuffer_list$2; +function requireBuffer_list$2() { + if (hasRequiredBuffer_list$2) return buffer_list$2; + hasRequiredBuffer_list$2 = 1; + function ownKeys2(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source2 = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys2(Object(source2), true).forEach(function(key2) { + _defineProperty2(target, key2, source2[key2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2)) : ownKeys2(Object(source2)).forEach(function(key2) { + Object.defineProperty(target, key2, Object.getOwnPropertyDescriptor(source2, key2)); + }); + } + return target; + } + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey2(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return typeof key2 === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return String(input); + } + var _require = requireBuffer$2(), Buffer2 = _require.Buffer; + var _require2 = require$$3, inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src2, target, offset2) { + Buffer2.prototype.copy.call(src2, target, offset2); + } + buffer_list$2 = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join2(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer2.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options2) { + return inspect(this, _objectSpread(_objectSpread({}, options2), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + return buffer_list$2; +} +var destroy_1$2; +var hasRequiredDestroy$2; +function requireDestroy$2() { + if (hasRequiredDestroy$2) return destroy_1$2; + hasRequiredDestroy$2 = 1; + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err2); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) return; + if (self2._readableState && !self2._readableState.emitClose) return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream2, err) { + var rState = stream2._readableState; + var wState = stream2._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream2.destroy(err); + else stream2.emit("error", err); + } + destroy_1$2 = { + destroy, + undestroy, + errorOrDestroy + }; + return destroy_1$2; +} +var errorsBrowser$2 = {}; +var hasRequiredErrorsBrowser$2; +function requireErrorsBrowser$2() { + if (hasRequiredErrorsBrowser$2) return errorsBrowser$2; + hasRequiredErrorsBrowser$2 = 1; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; + } + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /* @__PURE__ */ function(_Base) { + _inheritsLoose(NodeError2, _Base); + function NodeError2(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + return NodeError2; + }(Base); + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function(i) { + return String(i); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } + function startsWith(str, search, pos) { + return str.substr(0, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + var determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + var msg; + if (endsWith(name, " argument")) { + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } else { + var type2 = includes(name, ".") ? "property" : "argument"; + msg = 'The "'.concat(name, '" ').concat(type2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { + return "The " + name + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name) { + return "Cannot call " + name + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + errorsBrowser$2.codes = codes; + return errorsBrowser$2; +} +var state$2; +var hasRequiredState$2; +function requireState$2() { + if (hasRequiredState$2) return state$2; + hasRequiredState$2 = 1; + var ERR_INVALID_OPT_VALUE = requireErrorsBrowser$2().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options2, isDuplex, duplexKey) { + return options2.highWaterMark != null ? options2.highWaterMark : isDuplex ? options2[duplexKey] : null; + } + function getHighWaterMark(state2, options2, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options2, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + return state2.objectMode ? 16 : 16 * 1024; + } + state$2 = { + getHighWaterMark + }; + return state$2; +} +var browser$d; +var hasRequiredBrowser$d; +function requireBrowser$d() { + if (hasRequiredBrowser$d) return browser$d; + hasRequiredBrowser$d = 1; + browser$d = deprecate; + function deprecate(fn, msg) { + if (config("noDeprecation")) { + return fn; + } + var warned = false; + function deprecated() { + if (!warned) { + if (config("throwDeprecation")) { + throw new Error(msg); + } else if (config("traceDeprecation")) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + return deprecated; + } + function config(name) { + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; + } + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === "true"; + } + return browser$d; +} +var _stream_writable$2; +var hasRequired_stream_writable$2; +function require_stream_writable$2() { + if (hasRequired_stream_writable$2) return _stream_writable$2; + hasRequired_stream_writable$2 = 1; + _stream_writable$2 = Writable; + function CorkedRequest(state2) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state2); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: requireBrowser$d() + }; + var Stream2 = requireStreamBrowser$2(); + var Buffer2 = requireBuffer$2().Buffer; + var OurUint8Array = (typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = requireDestroy$2(); + var _require = requireState$2(), getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrorsBrowser$2().codes, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + requireInherits_browser$1()(Writable, Stream2); + function nop() { + } + function WritableState(options2, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex$2(); + options2 = options2 || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof Duplex; + this.objectMode = !!options2.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options2.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options2, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options2.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options2.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream2, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options2.emitClose !== false; + this.autoDestroy = !!options2.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current2 = this.bufferedRequest; + var out = []; + while (current2) { + out.push(current2); + current2 = current2.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable(options2) { + Duplex = Duplex || require_stream_duplex$2(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options2); + this._writableState = new WritableState(options2, this, isDuplex); + this.writable = true; + if (options2) { + if (typeof options2.write === "function") this._write = options2.write; + if (typeof options2.writev === "function") this._writev = options2.writev; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + if (typeof options2.final === "function") this._final = options2.final; + } + Stream2.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream2, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + } + function validChunk(stream2, state2, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding2, cb) { + var state2 = this._writableState; + var ret = false; + var isBuf = !state2.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + if (isBuf) encoding2 = "buffer"; + else if (!encoding2) encoding2 = state2.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state2.ending) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state2, chunk, cb)) { + state2.pendingcb++; + ret = writeOrBuffer(this, state2, isBuf, chunk, encoding2, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state2 = this._writableState; + if (state2.corked) { + state2.corked--; + if (!state2.writing && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) clearBuffer(this, state2); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding2) { + if (typeof encoding2 === "string") encoding2 = encoding2.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding2 + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding2); + this._writableState.defaultEncoding = encoding2; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state2, chunk, encoding2) { + if (!state2.objectMode && state2.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding2); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream2, state2, isBuf, chunk, encoding2, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state2, chunk, encoding2); + if (chunk !== newChunk) { + isBuf = true; + encoding2 = "buffer"; + chunk = newChunk; + } + } + var len = state2.objectMode ? 1 : chunk.length; + state2.length += len; + var ret = state2.length < state2.highWaterMark; + if (!ret) state2.needDrain = true; + if (state2.writing || state2.corked) { + var last = state2.lastBufferedRequest; + state2.lastBufferedRequest = { + chunk, + encoding: encoding2, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state2.lastBufferedRequest; + } else { + state2.bufferedRequest = state2.lastBufferedRequest; + } + state2.bufferedRequestCount += 1; + } else { + doWrite(stream2, state2, false, len, chunk, encoding2, cb); + } + return ret; + } + function doWrite(stream2, state2, writev2, len, chunk, encoding2, cb) { + state2.writelen = len; + state2.writecb = cb; + state2.writing = true; + state2.sync = true; + if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev2) stream2._writev(chunk, state2.onwrite); + else stream2._write(chunk, encoding2, state2.onwrite); + state2.sync = false; + } + function onwriteError(stream2, state2, sync, er, cb) { + --state2.pendingcb; + if (sync) { + process.nextTick(cb, er); + process.nextTick(finishMaybe, stream2, state2); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + } else { + cb(er); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + finishMaybe(stream2, state2); + } + } + function onwriteStateUpdate(state2) { + state2.writing = false; + state2.writecb = null; + state2.length -= state2.writelen; + state2.writelen = 0; + } + function onwrite(stream2, er) { + var state2 = stream2._writableState; + var sync = state2.sync; + var cb = state2.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state2); + if (er) onwriteError(stream2, state2, sync, er, cb); + else { + var finished = needFinish(state2) || stream2.destroyed; + if (!finished && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) { + clearBuffer(stream2, state2); + } + if (sync) { + process.nextTick(afterWrite, stream2, state2, finished, cb); + } else { + afterWrite(stream2, state2, finished, cb); + } + } + } + function afterWrite(stream2, state2, finished, cb) { + if (!finished) onwriteDrain(stream2, state2); + state2.pendingcb--; + cb(); + finishMaybe(stream2, state2); + } + function onwriteDrain(stream2, state2) { + if (state2.length === 0 && state2.needDrain) { + state2.needDrain = false; + stream2.emit("drain"); + } + } + function clearBuffer(stream2, state2) { + state2.bufferProcessing = true; + var entry = state2.bufferedRequest; + if (stream2._writev && entry && entry.next) { + var l = state2.bufferedRequestCount; + var buffer2 = new Array(l); + var holder = state2.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer2[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer2.allBuffers = allBuffers; + doWrite(stream2, state2, true, state2.length, buffer2, "", holder.finish); + state2.pendingcb++; + state2.lastBufferedRequest = null; + if (holder.next) { + state2.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state2.corkedRequestsFree = new CorkedRequest(state2); + } + state2.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding2 = entry.encoding; + var cb = entry.callback; + var len = state2.objectMode ? 1 : chunk.length; + doWrite(stream2, state2, false, len, chunk, encoding2, cb); + entry = entry.next; + state2.bufferedRequestCount--; + if (state2.writing) { + break; + } + } + if (entry === null) state2.lastBufferedRequest = null; + } + state2.bufferedRequest = entry; + state2.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding2, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding2, cb) { + var state2 = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding2 = null; + } else if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding2); + if (state2.corked) { + state2.corked = 1; + this.uncork(); + } + if (!state2.ending) endWritable(this, state2, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function needFinish(state2) { + return state2.ending && state2.length === 0 && state2.bufferedRequest === null && !state2.finished && !state2.writing; + } + function callFinal(stream2, state2) { + stream2._final(function(err) { + state2.pendingcb--; + if (err) { + errorOrDestroy(stream2, err); + } + state2.prefinished = true; + stream2.emit("prefinish"); + finishMaybe(stream2, state2); + }); + } + function prefinish(stream2, state2) { + if (!state2.prefinished && !state2.finalCalled) { + if (typeof stream2._final === "function" && !state2.destroyed) { + state2.pendingcb++; + state2.finalCalled = true; + process.nextTick(callFinal, stream2, state2); + } else { + state2.prefinished = true; + stream2.emit("prefinish"); + } + } + } + function finishMaybe(stream2, state2) { + var need = needFinish(state2); + if (need) { + prefinish(stream2, state2); + if (state2.pendingcb === 0) { + state2.finished = true; + stream2.emit("finish"); + if (state2.autoDestroy) { + var rState = stream2._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream2.destroy(); + } + } + } + } + return need; + } + function endWritable(stream2, state2, cb) { + state2.ending = true; + finishMaybe(stream2, state2); + if (cb) { + if (state2.finished) process.nextTick(cb); + else stream2.once("finish", cb); + } + state2.ended = true; + stream2.writable = false; + } + function onCorkedFinish(corkReq, state2, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state2.pendingcb--; + cb(err); + entry = entry.next; + } + state2.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set2(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + return _stream_writable$2; +} +var _stream_duplex$2; +var hasRequired_stream_duplex$2; +function require_stream_duplex$2() { + if (hasRequired_stream_duplex$2) return _stream_duplex$2; + hasRequired_stream_duplex$2 = 1; + var objectKeys2 = Object.keys || function(obj) { + var keys2 = []; + for (var key2 in obj) keys2.push(key2); + return keys2; + }; + _stream_duplex$2 = Duplex; + var Readable = require_stream_readable$2(); + var Writable = require_stream_writable$2(); + requireInherits_browser$1()(Duplex, Readable); + { + var keys = objectKeys2(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options2) { + if (!(this instanceof Duplex)) return new Duplex(options2); + Readable.call(this, options2); + Writable.call(this, options2); + this.allowHalfOpen = true; + if (options2) { + if (options2.readable === false) this.readable = false; + if (options2.writable === false) this.writable = false; + if (options2.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) return; + process.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set2(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + return _stream_duplex$2; +} +var endOfStream$3; +var hasRequiredEndOfStream$3; +function requireEndOfStream$3() { + if (hasRequiredEndOfStream$3) return endOfStream$3; + hasRequiredEndOfStream$3 = 1; + var ERR_STREAM_PREMATURE_CLOSE = requireErrorsBrowser$2().codes.ERR_STREAM_PREMATURE_CLOSE; + function once2(callback) { + var called = false; + return function() { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop2() { + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function eos(stream2, opts, callback) { + if (typeof opts === "function") return eos(stream2, null, opts); + if (!opts) opts = {}; + callback = once2(callback || noop2); + var readable2 = opts.readable || opts.readable !== false && stream2.readable; + var writable2 = opts.writable || opts.writable !== false && stream2.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream2.writable) onfinish(); + }; + var writableEnded = stream2._writableState && stream2._writableState.finished; + var onfinish = function onfinish2() { + writable2 = false; + writableEnded = true; + if (!readable2) callback.call(stream2); + }; + var readableEnded = stream2._readableState && stream2._readableState.endEmitted; + var onend = function onend2() { + readable2 = false; + readableEnded = true; + if (!writable2) callback.call(stream2); + }; + var onerror = function onerror2(err) { + callback.call(stream2, err); + }; + var onclose = function onclose2() { + var err; + if (readable2 && !readableEnded) { + if (!stream2._readableState || !stream2._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + if (writable2 && !writableEnded) { + if (!stream2._writableState || !stream2._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + }; + var onrequest = function onrequest2() { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + stream2.on("abort", onclose); + if (stream2.req) onrequest(); + else stream2.on("request", onrequest); + } else if (writable2 && !stream2._writableState) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (opts.error !== false) stream2.on("error", onerror); + stream2.on("close", onclose); + return function() { + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.removeListener("close", onclose); + }; + } + endOfStream$3 = eos; + return endOfStream$3; +} +var async_iterator$2; +var hasRequiredAsync_iterator$2; +function requireAsync_iterator$2() { + if (hasRequiredAsync_iterator$2) return async_iterator$2; + hasRequiredAsync_iterator$2 = 1; + var _Object$setPrototypeO; + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return typeof key2 === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = requireEndOfStream$3(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data2 = iter[kStream].read(); + if (data2 !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data2, false)); + } + } + } + function onReadable(iter) { + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error2 = this[kError]; + if (error2 !== null) { + return Promise.reject(error2); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + process.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data2 = this[kStream].read(); + if (data2 !== null) { + return Promise.resolve(createIterResult(data2, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty2(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty2(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream2) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty2(_Object$create, kStream, { + value: stream2, + writable: true + }), _defineProperty2(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kEnded, { + value: stream2._readableState.endEmitted, + writable: true + }), _defineProperty2(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data2 = iterator[kStream].read(); + if (data2) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data2, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream2, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator[kLastReject]; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(void 0, true)); + } + iterator[kEnded] = true; + }); + stream2.on("readable", onReadable.bind(null, iterator)); + return iterator; + }; + async_iterator$2 = createReadableStreamAsyncIterator; + return async_iterator$2; +} +var fromBrowser$2; +var hasRequiredFromBrowser$2; +function requireFromBrowser$2() { + if (hasRequiredFromBrowser$2) return fromBrowser$2; + hasRequiredFromBrowser$2 = 1; + fromBrowser$2 = function() { + throw new Error("Readable.from is not available in the browser"); + }; + return fromBrowser$2; +} +var _stream_readable$2; +var hasRequired_stream_readable$2; +function require_stream_readable$2() { + if (hasRequired_stream_readable$2) return _stream_readable$2; + hasRequired_stream_readable$2 = 1; + _stream_readable$2 = Readable; + var Duplex; + Readable.ReadableState = ReadableState; + requireEvents().EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type2) { + return emitter.listeners(type2).length; + }; + var Stream2 = requireStreamBrowser$2(); + var Buffer2 = requireBuffer$2().Buffer; + var OurUint8Array = (typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = require$$3; + var debug2; + if (debugUtil && debugUtil.debuglog) { + debug2 = debugUtil.debuglog("stream"); + } else { + debug2 = function debug3() { + }; + } + var BufferList = requireBuffer_list$2(); + var destroyImpl = requireDestroy$2(); + var _require = requireState$2(), getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrorsBrowser$2().codes, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from2; + requireInherits_browser$1()(Readable, Stream2); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options2, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex$2(); + options2 = options2 || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof Duplex; + this.objectMode = !!options2.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options2.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options2, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options2.emitClose !== false; + this.autoDestroy = !!options2.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options2.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options2.encoding) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + this.decoder = new StringDecoder(options2.encoding); + this.encoding = options2.encoding; + } + } + function Readable(options2) { + Duplex = Duplex || require_stream_duplex$2(); + if (!(this instanceof Readable)) return new Readable(options2); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options2, this, isDuplex); + this.readable = true; + if (options2) { + if (typeof options2.read === "function") this._read = options2.read; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + } + Stream2.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set2(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype.push = function(chunk, encoding2) { + var state2 = this._readableState; + var skipChunkCheck; + if (!state2.objectMode) { + if (typeof chunk === "string") { + encoding2 = encoding2 || state2.defaultEncoding; + if (encoding2 !== state2.encoding) { + chunk = Buffer2.from(chunk, encoding2); + encoding2 = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding2, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream2, chunk, encoding2, addToFront, skipChunkCheck) { + debug2("readableAddChunk", chunk); + var state2 = stream2._readableState; + if (chunk === null) { + state2.reading = false; + onEofChunk(stream2, state2); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state2, chunk); + if (er) { + errorOrDestroy(stream2, er); + } else if (state2.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state2.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state2.endEmitted) errorOrDestroy(stream2, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream2, state2, chunk, true); + } else if (state2.ended) { + errorOrDestroy(stream2, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state2.destroyed) { + return false; + } else { + state2.reading = false; + if (state2.decoder && !encoding2) { + chunk = state2.decoder.write(chunk); + if (state2.objectMode || chunk.length !== 0) addChunk(stream2, state2, chunk, false); + else maybeReadMore(stream2, state2); + } else { + addChunk(stream2, state2, chunk, false); + } + } + } else if (!addToFront) { + state2.reading = false; + maybeReadMore(stream2, state2); + } + } + return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0); + } + function addChunk(stream2, state2, chunk, addToFront) { + if (state2.flowing && state2.length === 0 && !state2.sync) { + state2.awaitDrain = 0; + stream2.emit("data", chunk); + } else { + state2.length += state2.objectMode ? 1 : chunk.length; + if (addToFront) state2.buffer.unshift(chunk); + else state2.buffer.push(chunk); + if (state2.needReadable) emitReadable(stream2); + } + maybeReadMore(stream2, state2); + } + function chunkInvalid(state2, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + var decoder2 = new StringDecoder(enc); + this._readableState.decoder = decoder2; + this._readableState.encoding = this._readableState.decoder.encoding; + var p = this._readableState.buffer.head; + var content = ""; + while (p !== null) { + content += decoder2.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== "") this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state2) { + if (n <= 0 || state2.length === 0 && state2.ended) return 0; + if (state2.objectMode) return 1; + if (n !== n) { + if (state2.flowing && state2.length) return state2.buffer.head.data.length; + else return state2.length; + } + if (n > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n); + if (n <= state2.length) return n; + if (!state2.ended) { + state2.needReadable = true; + return 0; + } + return state2.length; + } + Readable.prototype.read = function(n) { + debug2("read", n); + n = parseInt(n, 10); + var state2 = this._readableState; + var nOrig = n; + if (n !== 0) state2.emittedReadable = false; + if (n === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) { + debug2("read: emitReadable", state2.length, state2.ended); + if (state2.length === 0 && state2.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state2); + if (n === 0 && state2.ended) { + if (state2.length === 0) endReadable(this); + return null; + } + var doRead = state2.needReadable; + debug2("need readable", doRead); + if (state2.length === 0 || state2.length - n < state2.highWaterMark) { + doRead = true; + debug2("length less than watermark", doRead); + } + if (state2.ended || state2.reading) { + doRead = false; + debug2("reading or ended", doRead); + } else if (doRead) { + debug2("do read"); + state2.reading = true; + state2.sync = true; + if (state2.length === 0) state2.needReadable = true; + this._read(state2.highWaterMark); + state2.sync = false; + if (!state2.reading) n = howMuchToRead(nOrig, state2); + } + var ret; + if (n > 0) ret = fromList(n, state2); + else ret = null; + if (ret === null) { + state2.needReadable = state2.length <= state2.highWaterMark; + n = 0; + } else { + state2.length -= n; + state2.awaitDrain = 0; + } + if (state2.length === 0) { + if (!state2.ended) state2.needReadable = true; + if (nOrig !== n && state2.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream2, state2) { + debug2("onEofChunk"); + if (state2.ended) return; + if (state2.decoder) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) { + state2.buffer.push(chunk); + state2.length += state2.objectMode ? 1 : chunk.length; + } + } + state2.ended = true; + if (state2.sync) { + emitReadable(stream2); + } else { + state2.needReadable = false; + if (!state2.emittedReadable) { + state2.emittedReadable = true; + emitReadable_(stream2); + } + } + } + function emitReadable(stream2) { + var state2 = stream2._readableState; + debug2("emitReadable", state2.needReadable, state2.emittedReadable); + state2.needReadable = false; + if (!state2.emittedReadable) { + debug2("emitReadable", state2.flowing); + state2.emittedReadable = true; + process.nextTick(emitReadable_, stream2); + } + } + function emitReadable_(stream2) { + var state2 = stream2._readableState; + debug2("emitReadable_", state2.destroyed, state2.length, state2.ended); + if (!state2.destroyed && (state2.length || state2.ended)) { + stream2.emit("readable"); + state2.emittedReadable = false; + } + state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark; + flow(stream2); + } + function maybeReadMore(stream2, state2) { + if (!state2.readingMore) { + state2.readingMore = true; + process.nextTick(maybeReadMore_, stream2, state2); + } + } + function maybeReadMore_(stream2, state2) { + while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) { + var len = state2.length; + debug2("maybeReadMore read 0"); + stream2.read(0); + if (len === state2.length) + break; + } + state2.readingMore = false; + } + Readable.prototype._read = function(n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src2 = this; + var state2 = this._readableState; + switch (state2.pipesCount) { + case 0: + state2.pipes = dest; + break; + case 1: + state2.pipes = [state2.pipes, dest]; + break; + default: + state2.pipes.push(dest); + break; + } + state2.pipesCount += 1; + debug2("pipe count=%d opts=%j", state2.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state2.endEmitted) process.nextTick(endFn); + else src2.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable2, unpipeInfo) { + debug2("onunpipe"); + if (readable2 === src2) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug2("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src2); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug2("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src2.removeListener("end", onend); + src2.removeListener("end", unpipe); + src2.removeListener("data", ondata); + cleanedUp = true; + if (state2.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src2.on("data", ondata); + function ondata(chunk) { + debug2("ondata"); + var ret = dest.write(chunk); + debug2("dest.write", ret); + if (ret === false) { + if ((state2.pipesCount === 1 && state2.pipes === dest || state2.pipesCount > 1 && indexOf(state2.pipes, dest) !== -1) && !cleanedUp) { + debug2("false write response, pause", state2.awaitDrain); + state2.awaitDrain++; + } + src2.pause(); + } + } + function onerror(er) { + debug2("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug2("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug2("unpipe"); + src2.unpipe(dest); + } + dest.emit("pipe", src2); + if (!state2.flowing) { + debug2("pipe resume"); + src2.resume(); + } + return dest; + }; + function pipeOnDrain(src2) { + return function pipeOnDrainFunctionResult() { + var state2 = src2._readableState; + debug2("pipeOnDrain", state2.awaitDrain); + if (state2.awaitDrain) state2.awaitDrain--; + if (state2.awaitDrain === 0 && EElistenerCount(src2, "data")) { + state2.flowing = true; + flow(src2); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state2 = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state2.pipesCount === 0) return this; + if (state2.pipesCount === 1) { + if (dest && dest !== state2.pipes) return this; + if (!dest) dest = state2.pipes; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state2.pipes; + var len = state2.pipesCount; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index2 = indexOf(state2.pipes, dest); + if (index2 === -1) return this; + state2.pipes.splice(index2, 1); + state2.pipesCount -= 1; + if (state2.pipesCount === 1) state2.pipes = state2.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream2.prototype.on.call(this, ev, fn); + var state2 = this._readableState; + if (ev === "data") { + state2.readableListening = this.listenerCount("readable") > 0; + if (state2.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state2.endEmitted && !state2.readableListening) { + state2.readableListening = state2.needReadable = true; + state2.flowing = false; + state2.emittedReadable = false; + debug2("on readable", state2.length, state2.reading); + if (state2.length) { + emitReadable(this); + } else if (!state2.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + var res = Stream2.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + process.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.removeAllListeners = function(ev) { + var res = Stream2.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state2 = self2._readableState; + state2.readableListening = self2.listenerCount("readable") > 0; + if (state2.resumeScheduled && !state2.paused) { + state2.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug2("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + var state2 = this._readableState; + if (!state2.flowing) { + debug2("resume"); + state2.flowing = !state2.readableListening; + resume(this, state2); + } + state2.paused = false; + return this; + }; + function resume(stream2, state2) { + if (!state2.resumeScheduled) { + state2.resumeScheduled = true; + process.nextTick(resume_, stream2, state2); + } + } + function resume_(stream2, state2) { + debug2("resume", state2.reading); + if (!state2.reading) { + stream2.read(0); + } + state2.resumeScheduled = false; + stream2.emit("resume"); + flow(stream2); + if (state2.flowing && !state2.reading) stream2.read(0); + } + Readable.prototype.pause = function() { + debug2("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug2("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream2) { + var state2 = stream2._readableState; + debug2("flow", state2.flowing); + while (state2.flowing && stream2.read() !== null) ; + } + Readable.prototype.wrap = function(stream2) { + var _this = this; + var state2 = this._readableState; + var paused = false; + stream2.on("end", function() { + debug2("wrapped end"); + if (state2.decoder && !state2.ended) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream2.on("data", function(chunk) { + debug2("wrapped data"); + if (state2.decoder) chunk = state2.decoder.write(chunk); + if (state2.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state2.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream2.pause(); + } + }); + for (var i in stream2) { + if (this[i] === void 0 && typeof stream2[i] === "function") { + this[i] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream2[method].apply(stream2, arguments); + }; + }(i); + } + } + for (var n = 0; n < kProxyEvents.length; n++) { + stream2.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + this._read = function(n2) { + debug2("wrapped _read", n2); + if (paused) { + paused = false; + stream2.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = requireAsync_iterator$2(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.flowing; + }, + set: function set2(state2) { + if (this._readableState) { + this._readableState.flowing = state2; + } + } + }); + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.length; + } + }); + function fromList(n, state2) { + if (state2.length === 0) return null; + var ret; + if (state2.objectMode) ret = state2.buffer.shift(); + else if (!n || n >= state2.length) { + if (state2.decoder) ret = state2.buffer.join(""); + else if (state2.buffer.length === 1) ret = state2.buffer.first(); + else ret = state2.buffer.concat(state2.length); + state2.buffer.clear(); + } else { + ret = state2.buffer.consume(n, state2.decoder); + } + return ret; + } + function endReadable(stream2) { + var state2 = stream2._readableState; + debug2("endReadable", state2.endEmitted); + if (!state2.endEmitted) { + state2.ended = true; + process.nextTick(endReadableNT, state2, stream2); + } + } + function endReadableNT(state2, stream2) { + debug2("endReadableNT", state2.endEmitted, state2.length); + if (!state2.endEmitted && state2.length === 0) { + state2.endEmitted = true; + stream2.readable = false; + stream2.emit("end"); + if (state2.autoDestroy) { + var wState = stream2._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream2.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable.from = function(iterable, opts) { + if (from2 === void 0) { + from2 = requireFromBrowser$2(); + } + return from2(Readable, iterable, opts); + }; + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + return _stream_readable$2; +} +var _stream_transform$2; +var hasRequired_stream_transform$2; +function require_stream_transform$2() { + if (hasRequired_stream_transform$2) return _stream_transform$2; + hasRequired_stream_transform$2 = 1; + _stream_transform$2 = Transform; + var _require$codes = requireErrorsBrowser$2().codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex$2(); + requireInherits_browser$1()(Transform, Duplex); + function afterTransform(er, data2) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data2 != null) + this.push(data2); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options2) { + if (!(this instanceof Transform)) return new Transform(options2); + Duplex.call(this, options2); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options2) { + if (typeof options2.transform === "function") this._transform = options2.transform; + if (typeof options2.flush === "function") this._flush = options2.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er, data2) { + done(_this, er, data2); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding2) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding2); + }; + Transform.prototype._transform = function(chunk, encoding2, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding2, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding2; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream2, er, data2) { + if (er) return stream2.emit("error", er); + if (data2 != null) + stream2.push(data2); + if (stream2._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream2._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream2.push(null); + } + return _stream_transform$2; +} +var _stream_passthrough$2; +var hasRequired_stream_passthrough$2; +function require_stream_passthrough$2() { + if (hasRequired_stream_passthrough$2) return _stream_passthrough$2; + hasRequired_stream_passthrough$2 = 1; + _stream_passthrough$2 = PassThrough; + var Transform = require_stream_transform$2(); + requireInherits_browser$1()(PassThrough, Transform); + function PassThrough(options2) { + if (!(this instanceof PassThrough)) return new PassThrough(options2); + Transform.call(this, options2); + } + PassThrough.prototype._transform = function(chunk, encoding2, cb) { + cb(null, chunk); + }; + return _stream_passthrough$2; +} +var pipeline_1$2; +var hasRequiredPipeline$2; +function requirePipeline$2() { + if (hasRequiredPipeline$2) return pipeline_1$2; + hasRequiredPipeline$2 = 1; + var eos; + function once2(callback) { + var called = false; + return function() { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = requireErrorsBrowser$2().codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop2(err) { + if (err) throw err; + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function destroyer(stream2, reading, writing, callback) { + callback = once2(callback); + var closed = false; + stream2.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = requireEndOfStream$3(); + eos(stream2, { + readable: reading, + writable: writing + }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isRequest(stream2)) return stream2.abort(); + if (typeof stream2.destroy === "function") return stream2.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe(from2, to) { + return from2.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop2; + if (typeof streams[streams.length - 1] !== "function") return noop2; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error2; + var destroys = streams.map(function(stream2, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream2, reading, writing, function(err) { + if (!error2) error2 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error2); + }); + }); + return streams.reduce(pipe); + } + pipeline_1$2 = pipeline; + return pipeline_1$2; +} +var hasRequiredReadableBrowser$2; +function requireReadableBrowser$2() { + if (hasRequiredReadableBrowser$2) return readableBrowser$2.exports; + hasRequiredReadableBrowser$2 = 1; + (function(module, exports) { + exports = module.exports = require_stream_readable$2(); + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = require_stream_writable$2(); + exports.Duplex = require_stream_duplex$2(); + exports.Transform = require_stream_transform$2(); + exports.PassThrough = require_stream_passthrough$2(); + exports.finished = requireEndOfStream$3(); + exports.pipeline = requirePipeline$2(); + })(readableBrowser$2, readableBrowser$2.exports); + return readableBrowser$2.exports; +} +var hashBase; +var hasRequiredHashBase; +function requireHashBase() { + if (hasRequiredHashBase) return hashBase; + hasRequiredHashBase = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var Transform = requireReadableBrowser$2().Transform; + var inherits = requireInherits_browser$1(); + function throwIfNotStringOrBuffer(val, prefix) { + if (!Buffer2.isBuffer(val) && typeof val !== "string") { + throw new TypeError(prefix + " must be a string or a buffer"); + } + } + function HashBase(blockSize) { + Transform.call(this); + this._block = Buffer2.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; + this._finalized = false; + } + inherits(HashBase, Transform); + HashBase.prototype._transform = function(chunk, encoding2, callback) { + var error2 = null; + try { + this.update(chunk, encoding2); + } catch (err) { + error2 = err; + } + callback(error2); + }; + HashBase.prototype._flush = function(callback) { + var error2 = null; + try { + this.push(this.digest()); + } catch (err) { + error2 = err; + } + callback(error2); + }; + HashBase.prototype.update = function(data2, encoding2) { + throwIfNotStringOrBuffer(data2, "Data"); + if (this._finalized) throw new Error("Digest already called"); + if (!Buffer2.isBuffer(data2)) data2 = Buffer2.from(data2, encoding2); + var block = this._block; + var offset2 = 0; + while (this._blockOffset + data2.length - offset2 >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize; ) block[i++] = data2[offset2++]; + this._update(); + this._blockOffset = 0; + } + while (offset2 < data2.length) block[this._blockOffset++] = data2[offset2++]; + for (var j = 0, carry = data2.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = this._length[j] / 4294967296 | 0; + if (carry > 0) this._length[j] -= 4294967296 * carry; + } + return this; + }; + HashBase.prototype._update = function() { + throw new Error("_update is not implemented"); + }; + HashBase.prototype.digest = function(encoding2) { + if (this._finalized) throw new Error("Digest already called"); + this._finalized = true; + var digest = this._digest(); + if (encoding2 !== void 0) digest = digest.toString(encoding2); + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; + return digest; + }; + HashBase.prototype._digest = function() { + throw new Error("_digest is not implemented"); + }; + hashBase = HashBase; + return hashBase; +} +var md5_js; +var hasRequiredMd5_js; +function requireMd5_js() { + if (hasRequiredMd5_js) return md5_js; + hasRequiredMd5_js = 1; + var inherits = requireInherits_browser$1(); + var HashBase = requireHashBase(); + var Buffer2 = requireSafeBuffer().Buffer; + var ARRAY16 = new Array(16); + function MD5() { + HashBase.call(this, 64); + this._a = 1732584193; + this._b = 4023233417; + this._c = 2562383102; + this._d = 271733878; + } + inherits(MD5, HashBase); + MD5.prototype._update = function() { + var M = ARRAY16; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + a = fnF(a, b, c, d, M[0], 3614090360, 7); + d = fnF(d, a, b, c, M[1], 3905402710, 12); + c = fnF(c, d, a, b, M[2], 606105819, 17); + b = fnF(b, c, d, a, M[3], 3250441966, 22); + a = fnF(a, b, c, d, M[4], 4118548399, 7); + d = fnF(d, a, b, c, M[5], 1200080426, 12); + c = fnF(c, d, a, b, M[6], 2821735955, 17); + b = fnF(b, c, d, a, M[7], 4249261313, 22); + a = fnF(a, b, c, d, M[8], 1770035416, 7); + d = fnF(d, a, b, c, M[9], 2336552879, 12); + c = fnF(c, d, a, b, M[10], 4294925233, 17); + b = fnF(b, c, d, a, M[11], 2304563134, 22); + a = fnF(a, b, c, d, M[12], 1804603682, 7); + d = fnF(d, a, b, c, M[13], 4254626195, 12); + c = fnF(c, d, a, b, M[14], 2792965006, 17); + b = fnF(b, c, d, a, M[15], 1236535329, 22); + a = fnG(a, b, c, d, M[1], 4129170786, 5); + d = fnG(d, a, b, c, M[6], 3225465664, 9); + c = fnG(c, d, a, b, M[11], 643717713, 14); + b = fnG(b, c, d, a, M[0], 3921069994, 20); + a = fnG(a, b, c, d, M[5], 3593408605, 5); + d = fnG(d, a, b, c, M[10], 38016083, 9); + c = fnG(c, d, a, b, M[15], 3634488961, 14); + b = fnG(b, c, d, a, M[4], 3889429448, 20); + a = fnG(a, b, c, d, M[9], 568446438, 5); + d = fnG(d, a, b, c, M[14], 3275163606, 9); + c = fnG(c, d, a, b, M[3], 4107603335, 14); + b = fnG(b, c, d, a, M[8], 1163531501, 20); + a = fnG(a, b, c, d, M[13], 2850285829, 5); + d = fnG(d, a, b, c, M[2], 4243563512, 9); + c = fnG(c, d, a, b, M[7], 1735328473, 14); + b = fnG(b, c, d, a, M[12], 2368359562, 20); + a = fnH(a, b, c, d, M[5], 4294588738, 4); + d = fnH(d, a, b, c, M[8], 2272392833, 11); + c = fnH(c, d, a, b, M[11], 1839030562, 16); + b = fnH(b, c, d, a, M[14], 4259657740, 23); + a = fnH(a, b, c, d, M[1], 2763975236, 4); + d = fnH(d, a, b, c, M[4], 1272893353, 11); + c = fnH(c, d, a, b, M[7], 4139469664, 16); + b = fnH(b, c, d, a, M[10], 3200236656, 23); + a = fnH(a, b, c, d, M[13], 681279174, 4); + d = fnH(d, a, b, c, M[0], 3936430074, 11); + c = fnH(c, d, a, b, M[3], 3572445317, 16); + b = fnH(b, c, d, a, M[6], 76029189, 23); + a = fnH(a, b, c, d, M[9], 3654602809, 4); + d = fnH(d, a, b, c, M[12], 3873151461, 11); + c = fnH(c, d, a, b, M[15], 530742520, 16); + b = fnH(b, c, d, a, M[2], 3299628645, 23); + a = fnI(a, b, c, d, M[0], 4096336452, 6); + d = fnI(d, a, b, c, M[7], 1126891415, 10); + c = fnI(c, d, a, b, M[14], 2878612391, 15); + b = fnI(b, c, d, a, M[5], 4237533241, 21); + a = fnI(a, b, c, d, M[12], 1700485571, 6); + d = fnI(d, a, b, c, M[3], 2399980690, 10); + c = fnI(c, d, a, b, M[10], 4293915773, 15); + b = fnI(b, c, d, a, M[1], 2240044497, 21); + a = fnI(a, b, c, d, M[8], 1873313359, 6); + d = fnI(d, a, b, c, M[15], 4264355552, 10); + c = fnI(c, d, a, b, M[6], 2734768916, 15); + b = fnI(b, c, d, a, M[13], 1309151649, 21); + a = fnI(a, b, c, d, M[4], 4149444226, 6); + d = fnI(d, a, b, c, M[11], 3174756917, 10); + c = fnI(c, d, a, b, M[2], 718787259, 15); + b = fnI(b, c, d, a, M[9], 3951481745, 21); + this._a = this._a + a | 0; + this._b = this._b + b | 0; + this._c = this._c + c | 0; + this._d = this._d + d | 0; + }; + MD5.prototype._digest = function() { + this._block[this._blockOffset++] = 128; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + var buffer2 = Buffer2.allocUnsafe(16); + buffer2.writeInt32LE(this._a, 0); + buffer2.writeInt32LE(this._b, 4); + buffer2.writeInt32LE(this._c, 8); + buffer2.writeInt32LE(this._d, 12); + return buffer2; + }; + function rotl(x, n) { + return x << n | x >>> 32 - n; + } + function fnF(a, b, c, d, m, k, s) { + return rotl(a + (b & c | ~b & d) + m + k | 0, s) + b | 0; + } + function fnG(a, b, c, d, m, k, s) { + return rotl(a + (b & d | c & ~d) + m + k | 0, s) + b | 0; + } + function fnH(a, b, c, d, m, k, s) { + return rotl(a + (b ^ c ^ d) + m + k | 0, s) + b | 0; + } + function fnI(a, b, c, d, m, k, s) { + return rotl(a + (c ^ (b | ~d)) + m + k | 0, s) + b | 0; + } + md5_js = MD5; + return md5_js; +} +var ripemd160; +var hasRequiredRipemd160; +function requireRipemd160() { + if (hasRequiredRipemd160) return ripemd160; + hasRequiredRipemd160 = 1; + var Buffer2 = requireBuffer$2().Buffer; + var inherits = requireInherits_browser$1(); + var HashBase = requireHashBase(); + var ARRAY16 = new Array(16); + var zl = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 7, + 4, + 13, + 1, + 10, + 6, + 15, + 3, + 12, + 0, + 9, + 5, + 2, + 14, + 11, + 8, + 3, + 10, + 14, + 4, + 9, + 15, + 8, + 1, + 2, + 7, + 0, + 6, + 13, + 11, + 5, + 12, + 1, + 9, + 11, + 10, + 0, + 8, + 12, + 4, + 13, + 3, + 7, + 15, + 14, + 5, + 6, + 2, + 4, + 0, + 5, + 9, + 7, + 12, + 2, + 10, + 14, + 1, + 3, + 8, + 11, + 6, + 15, + 13 + ]; + var zr = [ + 5, + 14, + 7, + 0, + 9, + 2, + 11, + 4, + 13, + 6, + 15, + 8, + 1, + 10, + 3, + 12, + 6, + 11, + 3, + 7, + 0, + 13, + 5, + 10, + 14, + 15, + 8, + 12, + 4, + 9, + 1, + 2, + 15, + 5, + 1, + 3, + 7, + 14, + 6, + 9, + 11, + 8, + 12, + 2, + 10, + 0, + 4, + 13, + 8, + 6, + 4, + 1, + 3, + 11, + 15, + 0, + 5, + 12, + 2, + 13, + 9, + 7, + 10, + 14, + 12, + 15, + 10, + 4, + 1, + 5, + 8, + 7, + 6, + 2, + 13, + 14, + 0, + 3, + 9, + 11 + ]; + var sl = [ + 11, + 14, + 15, + 12, + 5, + 8, + 7, + 9, + 11, + 13, + 14, + 15, + 6, + 7, + 9, + 8, + 7, + 6, + 8, + 13, + 11, + 9, + 7, + 15, + 7, + 12, + 15, + 9, + 11, + 7, + 13, + 12, + 11, + 13, + 6, + 7, + 14, + 9, + 13, + 15, + 14, + 8, + 13, + 6, + 5, + 12, + 7, + 5, + 11, + 12, + 14, + 15, + 14, + 15, + 9, + 8, + 9, + 14, + 5, + 6, + 8, + 6, + 5, + 12, + 9, + 15, + 5, + 11, + 6, + 8, + 13, + 12, + 5, + 12, + 13, + 14, + 11, + 8, + 5, + 6 + ]; + var sr = [ + 8, + 9, + 9, + 11, + 13, + 15, + 15, + 5, + 7, + 7, + 8, + 11, + 14, + 14, + 12, + 6, + 9, + 13, + 15, + 7, + 12, + 8, + 9, + 11, + 7, + 7, + 12, + 7, + 6, + 15, + 13, + 11, + 9, + 7, + 15, + 11, + 8, + 6, + 6, + 14, + 12, + 13, + 5, + 14, + 13, + 13, + 7, + 5, + 15, + 5, + 8, + 11, + 14, + 14, + 6, + 14, + 6, + 9, + 12, + 9, + 12, + 5, + 15, + 8, + 8, + 5, + 12, + 9, + 12, + 5, + 14, + 6, + 8, + 13, + 6, + 5, + 15, + 13, + 11, + 11 + ]; + var hl = [0, 1518500249, 1859775393, 2400959708, 2840853838]; + var hr = [1352829926, 1548603684, 1836072691, 2053994217, 0]; + function RIPEMD160() { + HashBase.call(this, 64); + this._a = 1732584193; + this._b = 4023233417; + this._c = 2562383102; + this._d = 271733878; + this._e = 3285377520; + } + inherits(RIPEMD160, HashBase); + RIPEMD160.prototype._update = function() { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } + var t = this._b + cl + dr | 0; + this._b = this._c + dl + er | 0; + this._c = this._d + el + ar | 0; + this._d = this._e + al + br | 0; + this._e = this._a + bl + cr | 0; + this._a = t; + }; + RIPEMD160.prototype._digest = function() { + this._block[this._blockOffset++] = 128; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + var buffer2 = Buffer2.alloc ? Buffer2.alloc(20) : new Buffer2(20); + buffer2.writeInt32LE(this._a, 0); + buffer2.writeInt32LE(this._b, 4); + buffer2.writeInt32LE(this._c, 8); + buffer2.writeInt32LE(this._d, 12); + buffer2.writeInt32LE(this._e, 16); + return buffer2; + }; + function rotl(x, n) { + return x << n | x >>> 32 - n; + } + function fn1(a, b, c, d, e, m, k, s) { + return rotl(a + (b ^ c ^ d) + m + k | 0, s) + e | 0; + } + function fn2(a, b, c, d, e, m, k, s) { + return rotl(a + (b & c | ~b & d) + m + k | 0, s) + e | 0; + } + function fn3(a, b, c, d, e, m, k, s) { + return rotl(a + ((b | ~c) ^ d) + m + k | 0, s) + e | 0; + } + function fn4(a, b, c, d, e, m, k, s) { + return rotl(a + (b & d | c & ~d) + m + k | 0, s) + e | 0; + } + function fn5(a, b, c, d, e, m, k, s) { + return rotl(a + (b ^ (c | ~d)) + m + k | 0, s) + e | 0; + } + ripemd160 = RIPEMD160; + return ripemd160; +} +var sha_js = { exports: {} }; +var hash$1; +var hasRequiredHash$1; +function requireHash$1() { + if (hasRequiredHash$1) return hash$1; + hasRequiredHash$1 = 1; + var Buffer2 = requireSafeBuffer().Buffer; + function Hash(blockSize, finalSize) { + this._block = Buffer2.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } + Hash.prototype.update = function(data2, enc) { + if (typeof data2 === "string") { + enc = enc || "utf8"; + data2 = Buffer2.from(data2, enc); + } + var block = this._block; + var blockSize = this._blockSize; + var length = data2.length; + var accum = this._len; + for (var offset2 = 0; offset2 < length; ) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset2, blockSize - assigned); + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data2[offset2 + i]; + } + accum += remainder; + offset2 += remainder; + if (accum % blockSize === 0) { + this._update(block); + } + } + this._len += length; + return this; + }; + Hash.prototype.digest = function(enc) { + var rem = this._len % this._blockSize; + this._block[rem] = 128; + this._block.fill(0, rem + 1); + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + var bits = this._len * 8; + if (bits <= 4294967295) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + } else { + var lowBits = (bits & 4294967295) >>> 0; + var highBits = (bits - lowBits) / 4294967296; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + this._update(this._block); + var hash2 = this._hash(); + return enc ? hash2.toString(enc) : hash2; + }; + Hash.prototype._update = function() { + throw new Error("_update must be implemented by subclass"); + }; + hash$1 = Hash; + return hash$1; +} +var sha$1; +var hasRequiredSha$1; +function requireSha$1() { + if (hasRequiredSha$1) return sha$1; + hasRequiredSha$1 = 1; + var inherits = requireInherits_browser$1(); + var Hash = requireHash$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var K = [ + 1518500249, + 1859775393, + 2400959708 | 0, + 3395469782 | 0 + ]; + var W = new Array(80); + function Sha() { + this.init(); + this._w = W; + Hash.call(this, 64, 56); + } + inherits(Sha, Hash); + Sha.prototype.init = function() { + this._a = 1732584193; + this._b = 4023233417; + this._c = 2562383102; + this._d = 271733878; + this._e = 3285377520; + return this; + }; + function rotl5(num) { + return num << 5 | num >>> 27; + } + function rotl30(num) { + return num << 30 | num >>> 2; + } + function ft(s, b, c, d) { + if (s === 0) return b & c | ~b & d; + if (s === 2) return b & c | b & d | c & d; + return b ^ c ^ d; + } + Sha.prototype._update = function(M) { + var W2 = this._w; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + for (var i = 0; i < 16; ++i) W2[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W2[i] = W2[i - 3] ^ W2[i - 8] ^ W2[i - 14] ^ W2[i - 16]; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = rotl5(a) + ft(s, b, c, d) + e + W2[j] + K[s] | 0; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + this._a = a + this._a | 0; + this._b = b + this._b | 0; + this._c = c + this._c | 0; + this._d = d + this._d | 0; + this._e = e + this._e | 0; + }; + Sha.prototype._hash = function() { + var H = Buffer2.allocUnsafe(20); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + return H; + }; + sha$1 = Sha; + return sha$1; +} +var sha1; +var hasRequiredSha1; +function requireSha1() { + if (hasRequiredSha1) return sha1; + hasRequiredSha1 = 1; + var inherits = requireInherits_browser$1(); + var Hash = requireHash$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var K = [ + 1518500249, + 1859775393, + 2400959708 | 0, + 3395469782 | 0 + ]; + var W = new Array(80); + function Sha1() { + this.init(); + this._w = W; + Hash.call(this, 64, 56); + } + inherits(Sha1, Hash); + Sha1.prototype.init = function() { + this._a = 1732584193; + this._b = 4023233417; + this._c = 2562383102; + this._d = 271733878; + this._e = 3285377520; + return this; + }; + function rotl1(num) { + return num << 1 | num >>> 31; + } + function rotl5(num) { + return num << 5 | num >>> 27; + } + function rotl30(num) { + return num << 30 | num >>> 2; + } + function ft(s, b, c, d) { + if (s === 0) return b & c | ~b & d; + if (s === 2) return b & c | b & d | c & d; + return b ^ c ^ d; + } + Sha1.prototype._update = function(M) { + var W2 = this._w; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + for (var i = 0; i < 16; ++i) W2[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W2[i] = rotl1(W2[i - 3] ^ W2[i - 8] ^ W2[i - 14] ^ W2[i - 16]); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = rotl5(a) + ft(s, b, c, d) + e + W2[j] + K[s] | 0; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + this._a = a + this._a | 0; + this._b = b + this._b | 0; + this._c = c + this._c | 0; + this._d = d + this._d | 0; + this._e = e + this._e | 0; + }; + Sha1.prototype._hash = function() { + var H = Buffer2.allocUnsafe(20); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + return H; + }; + sha1 = Sha1; + return sha1; +} +var sha256$1; +var hasRequiredSha256; +function requireSha256() { + if (hasRequiredSha256) return sha256$1; + hasRequiredSha256 = 1; + var inherits = requireInherits_browser$1(); + var Hash = requireHash$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]; + var W = new Array(64); + function Sha256() { + this.init(); + this._w = W; + Hash.call(this, 64, 56); + } + inherits(Sha256, Hash); + Sha256.prototype.init = function() { + this._a = 1779033703; + this._b = 3144134277; + this._c = 1013904242; + this._d = 2773480762; + this._e = 1359893119; + this._f = 2600822924; + this._g = 528734635; + this._h = 1541459225; + return this; + }; + function ch(x, y, z) { + return z ^ x & (y ^ z); + } + function maj(x, y, z) { + return x & y | z & (x | y); + } + function sigma0(x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10); + } + function sigma1(x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7); + } + function gamma0(x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3; + } + function gamma1(x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ x >>> 10; + } + Sha256.prototype._update = function(M) { + var W2 = this._w; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; + for (var i = 0; i < 16; ++i) W2[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W2[i] = gamma1(W2[i - 2]) + W2[i - 7] + gamma0(W2[i - 15]) + W2[i - 16] | 0; + for (var j = 0; j < 64; ++j) { + var T1 = h + sigma1(e) + ch(e, f, g) + K[j] + W2[j] | 0; + var T2 = sigma0(a) + maj(a, b, c) | 0; + h = g; + g = f; + f = e; + e = d + T1 | 0; + d = c; + c = b; + b = a; + a = T1 + T2 | 0; + } + this._a = a + this._a | 0; + this._b = b + this._b | 0; + this._c = c + this._c | 0; + this._d = d + this._d | 0; + this._e = e + this._e | 0; + this._f = f + this._f | 0; + this._g = g + this._g | 0; + this._h = h + this._h | 0; + }; + Sha256.prototype._hash = function() { + var H = Buffer2.allocUnsafe(32); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); + return H; + }; + sha256$1 = Sha256; + return sha256$1; +} +var sha224$1; +var hasRequiredSha224; +function requireSha224() { + if (hasRequiredSha224) return sha224$1; + hasRequiredSha224 = 1; + var inherits = requireInherits_browser$1(); + var Sha256 = requireSha256(); + var Hash = requireHash$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var W = new Array(64); + function Sha224() { + this.init(); + this._w = W; + Hash.call(this, 64, 56); + } + inherits(Sha224, Sha256); + Sha224.prototype.init = function() { + this._a = 3238371032; + this._b = 914150663; + this._c = 812702999; + this._d = 4144912697; + this._e = 4290775857; + this._f = 1750603025; + this._g = 1694076839; + this._h = 3204075428; + return this; + }; + Sha224.prototype._hash = function() { + var H = Buffer2.allocUnsafe(28); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + return H; + }; + sha224$1 = Sha224; + return sha224$1; +} +var sha512$1; +var hasRequiredSha512; +function requireSha512() { + if (hasRequiredSha512) return sha512$1; + hasRequiredSha512 = 1; + var inherits = requireInherits_browser$1(); + var Hash = requireHash$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var K = [ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 + ]; + var W = new Array(160); + function Sha512() { + this.init(); + this._w = W; + Hash.call(this, 128, 112); + } + inherits(Sha512, Hash); + Sha512.prototype.init = function() { + this._ah = 1779033703; + this._bh = 3144134277; + this._ch = 1013904242; + this._dh = 2773480762; + this._eh = 1359893119; + this._fh = 2600822924; + this._gh = 528734635; + this._hh = 1541459225; + this._al = 4089235720; + this._bl = 2227873595; + this._cl = 4271175723; + this._dl = 1595750129; + this._el = 2917565137; + this._fl = 725511199; + this._gl = 4215389547; + this._hl = 327033209; + return this; + }; + function Ch(x, y, z) { + return z ^ x & (y ^ z); + } + function maj(x, y, z) { + return x & y | z & (x | y); + } + function sigma0(x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25); + } + function sigma1(x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23); + } + function Gamma0(x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ x >>> 7; + } + function Gamma0l(x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25); + } + function Gamma1(x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ x >>> 6; + } + function Gamma1l(x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26); + } + function getCarry(a, b) { + return a >>> 0 < b >>> 0 ? 1 : 0; + } + Sha512.prototype._update = function(M) { + var W2 = this._w; + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh2 = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + for (var i = 0; i < 32; i += 2) { + W2[i] = M.readInt32BE(i * 4); + W2[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W2[i - 15 * 2]; + var xl = W2[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); + xh = W2[i - 2 * 2]; + xl = W2[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); + var Wi7h = W2[i - 7 * 2]; + var Wi7l = W2[i - 7 * 2 + 1]; + var Wi16h = W2[i - 16 * 2]; + var Wi16l = W2[i - 16 * 2 + 1]; + var Wil = gamma0l + Wi7l | 0; + var Wih = gamma0 + Wi7h + getCarry(Wil, gamma0l) | 0; + Wil = Wil + gamma1l | 0; + Wih = Wih + gamma1 + getCarry(Wil, gamma1l) | 0; + Wil = Wil + Wi16l | 0; + Wih = Wih + Wi16h + getCarry(Wil, Wi16l) | 0; + W2[i] = Wih; + W2[i + 1] = Wil; + } + for (var j = 0; j < 160; j += 2) { + Wih = W2[j]; + Wil = W2[j + 1]; + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); + var Kih = K[j]; + var Kil = K[j + 1]; + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); + var t1l = hl + sigma1l | 0; + var t1h = hh + sigma1h + getCarry(t1l, hl) | 0; + t1l = t1l + chl | 0; + t1h = t1h + chh + getCarry(t1l, chl) | 0; + t1l = t1l + Kil | 0; + t1h = t1h + Kih + getCarry(t1l, Kil) | 0; + t1l = t1l + Wil | 0; + t1h = t1h + Wih + getCarry(t1l, Wil) | 0; + var t2l = sigma0l + majl | 0; + var t2h = sigma0h + majh + getCarry(t2l, sigma0l) | 0; + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = dl + t1l | 0; + eh = dh2 + t1h + getCarry(el, dl) | 0; + dh2 = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = t1l + t2l | 0; + ah = t1h + t2h + getCarry(al, t1l) | 0; + } + this._al = this._al + al | 0; + this._bl = this._bl + bl | 0; + this._cl = this._cl + cl | 0; + this._dl = this._dl + dl | 0; + this._el = this._el + el | 0; + this._fl = this._fl + fl | 0; + this._gl = this._gl + gl | 0; + this._hl = this._hl + hl | 0; + this._ah = this._ah + ah + getCarry(this._al, al) | 0; + this._bh = this._bh + bh + getCarry(this._bl, bl) | 0; + this._ch = this._ch + ch + getCarry(this._cl, cl) | 0; + this._dh = this._dh + dh2 + getCarry(this._dl, dl) | 0; + this._eh = this._eh + eh + getCarry(this._el, el) | 0; + this._fh = this._fh + fh + getCarry(this._fl, fl) | 0; + this._gh = this._gh + gh + getCarry(this._gl, gl) | 0; + this._hh = this._hh + hh + getCarry(this._hl, hl) | 0; + }; + Sha512.prototype._hash = function() { + var H = Buffer2.allocUnsafe(64); + function writeInt64BE(h, l, offset2) { + H.writeInt32BE(h, offset2); + H.writeInt32BE(l, offset2 + 4); + } + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + return H; + }; + sha512$1 = Sha512; + return sha512$1; +} +var sha384$1; +var hasRequiredSha384; +function requireSha384() { + if (hasRequiredSha384) return sha384$1; + hasRequiredSha384 = 1; + var inherits = requireInherits_browser$1(); + var SHA512 = requireSha512(); + var Hash = requireHash$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var W = new Array(160); + function Sha384() { + this.init(); + this._w = W; + Hash.call(this, 128, 112); + } + inherits(Sha384, SHA512); + Sha384.prototype.init = function() { + this._ah = 3418070365; + this._bh = 1654270250; + this._ch = 2438529370; + this._dh = 355462360; + this._eh = 1731405415; + this._fh = 2394180231; + this._gh = 3675008525; + this._hh = 1203062813; + this._al = 3238371032; + this._bl = 914150663; + this._cl = 812702999; + this._dl = 4144912697; + this._el = 4290775857; + this._fl = 1750603025; + this._gl = 1694076839; + this._hl = 3204075428; + return this; + }; + Sha384.prototype._hash = function() { + var H = Buffer2.allocUnsafe(48); + function writeInt64BE(h, l, offset2) { + H.writeInt32BE(h, offset2); + H.writeInt32BE(l, offset2 + 4); + } + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + return H; + }; + sha384$1 = Sha384; + return sha384$1; +} +var hasRequiredSha_js; +function requireSha_js() { + if (hasRequiredSha_js) return sha_js.exports; + hasRequiredSha_js = 1; + var exports = sha_js.exports = function SHA(algorithm) { + algorithm = algorithm.toLowerCase(); + var Algorithm = exports[algorithm]; + if (!Algorithm) throw new Error(algorithm + " is not supported (we accept pull requests)"); + return new Algorithm(); + }; + exports.sha = requireSha$1(); + exports.sha1 = requireSha1(); + exports.sha224 = requireSha224(); + exports.sha256 = requireSha256(); + exports.sha384 = requireSha384(); + exports.sha512 = requireSha512(); + return sha_js.exports; +} +var cipherBase; +var hasRequiredCipherBase; +function requireCipherBase() { + if (hasRequiredCipherBase) return cipherBase; + hasRequiredCipherBase = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var Transform = requireBrowser$h().Transform; + var StringDecoder = requireString_decoder().StringDecoder; + var inherits = requireInherits_browser$1(); + function CipherBase(hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === "string"; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; + } + inherits(CipherBase, Transform); + CipherBase.prototype.update = function(data2, inputEnc, outputEnc) { + if (typeof data2 === "string") { + data2 = Buffer2.from(data2, inputEnc); + } + var outData = this._update(data2); + if (this.hashMode) return this; + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } + return outData; + }; + CipherBase.prototype.setAutoPadding = function() { + }; + CipherBase.prototype.getAuthTag = function() { + throw new Error("trying to get auth tag in unsupported state"); + }; + CipherBase.prototype.setAuthTag = function() { + throw new Error("trying to set auth tag in unsupported state"); + }; + CipherBase.prototype.setAAD = function() { + throw new Error("trying to set aad in unsupported state"); + }; + CipherBase.prototype._transform = function(data2, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data2); + } else { + this.push(this._update(data2)); + } + } catch (e) { + err = e; + } finally { + next(err); + } + }; + CipherBase.prototype._flush = function(done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } + done(err); + }; + CipherBase.prototype._finalOrDigest = function(outputEnc) { + var outData = this.__final() || Buffer2.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData; + }; + CipherBase.prototype._toString = function(value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } + if (this._encoding !== enc) throw new Error("can't switch encodings"); + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } + return out; + }; + cipherBase = CipherBase; + return cipherBase; +} +var browser$c; +var hasRequiredBrowser$c; +function requireBrowser$c() { + if (hasRequiredBrowser$c) return browser$c; + hasRequiredBrowser$c = 1; + var inherits = requireInherits_browser$1(); + var MD5 = requireMd5_js(); + var RIPEMD160 = requireRipemd160(); + var sha2 = requireSha_js(); + var Base = requireCipherBase(); + function Hash(hash2) { + Base.call(this, "digest"); + this._hash = hash2; + } + inherits(Hash, Base); + Hash.prototype._update = function(data2) { + this._hash.update(data2); + }; + Hash.prototype._final = function() { + return this._hash.digest(); + }; + browser$c = function createHash(alg) { + alg = alg.toLowerCase(); + if (alg === "md5") return new MD5(); + if (alg === "rmd160" || alg === "ripemd160") return new RIPEMD160(); + return new Hash(sha2(alg)); + }; + return browser$c; +} +var legacy; +var hasRequiredLegacy; +function requireLegacy() { + if (hasRequiredLegacy) return legacy; + hasRequiredLegacy = 1; + var inherits = requireInherits_browser$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var Base = requireCipherBase(); + var ZEROS = Buffer2.alloc(128); + var blocksize = 64; + function Hmac(alg, key2) { + Base.call(this, "digest"); + if (typeof key2 === "string") { + key2 = Buffer2.from(key2); + } + this._alg = alg; + this._key = key2; + if (key2.length > blocksize) { + key2 = alg(key2); + } else if (key2.length < blocksize) { + key2 = Buffer2.concat([key2, ZEROS], blocksize); + } + var ipad = this._ipad = Buffer2.allocUnsafe(blocksize); + var opad = this._opad = Buffer2.allocUnsafe(blocksize); + for (var i = 0; i < blocksize; i++) { + ipad[i] = key2[i] ^ 54; + opad[i] = key2[i] ^ 92; + } + this._hash = [ipad]; + } + inherits(Hmac, Base); + Hmac.prototype._update = function(data2) { + this._hash.push(data2); + }; + Hmac.prototype._final = function() { + var h = this._alg(Buffer2.concat(this._hash)); + return this._alg(Buffer2.concat([this._opad, h])); + }; + legacy = Hmac; + return legacy; +} +var md5; +var hasRequiredMd5; +function requireMd5() { + if (hasRequiredMd5) return md5; + hasRequiredMd5 = 1; + var MD5 = requireMd5_js(); + md5 = function(buffer2) { + return new MD5().update(buffer2).digest(); + }; + return md5; +} +var browser$b; +var hasRequiredBrowser$b; +function requireBrowser$b() { + if (hasRequiredBrowser$b) return browser$b; + hasRequiredBrowser$b = 1; + var inherits = requireInherits_browser$1(); + var Legacy = requireLegacy(); + var Base = requireCipherBase(); + var Buffer2 = requireSafeBuffer().Buffer; + var md52 = requireMd5(); + var RIPEMD160 = requireRipemd160(); + var sha2 = requireSha_js(); + var ZEROS = Buffer2.alloc(128); + function Hmac(alg, key2) { + Base.call(this, "digest"); + if (typeof key2 === "string") { + key2 = Buffer2.from(key2); + } + var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64; + this._alg = alg; + this._key = key2; + if (key2.length > blocksize) { + var hash2 = alg === "rmd160" ? new RIPEMD160() : sha2(alg); + key2 = hash2.update(key2).digest(); + } else if (key2.length < blocksize) { + key2 = Buffer2.concat([key2, ZEROS], blocksize); + } + var ipad = this._ipad = Buffer2.allocUnsafe(blocksize); + var opad = this._opad = Buffer2.allocUnsafe(blocksize); + for (var i = 0; i < blocksize; i++) { + ipad[i] = key2[i] ^ 54; + opad[i] = key2[i] ^ 92; + } + this._hash = alg === "rmd160" ? new RIPEMD160() : sha2(alg); + this._hash.update(ipad); + } + inherits(Hmac, Base); + Hmac.prototype._update = function(data2) { + this._hash.update(data2); + }; + Hmac.prototype._final = function() { + var h = this._hash.digest(); + var hash2 = this._alg === "rmd160" ? new RIPEMD160() : sha2(this._alg); + return hash2.update(this._opad).update(h).digest(); + }; + browser$b = function createHmac(alg, key2) { + alg = alg.toLowerCase(); + if (alg === "rmd160" || alg === "ripemd160") { + return new Hmac("rmd160", key2); + } + if (alg === "md5") { + return new Legacy(md52, key2); + } + return new Hmac(alg, key2); + }; + return browser$b; +} +const sha224WithRSAEncryption = { "sign": "rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" }; +const sha256WithRSAEncryption = { "sign": "rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" }; +const sha384WithRSAEncryption = { "sign": "rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" }; +const sha512WithRSAEncryption = { "sign": "rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" }; +const sha256 = { "sign": "ecdsa", "hash": "sha256", "id": "" }; +const sha224 = { "sign": "ecdsa", "hash": "sha224", "id": "" }; +const sha384 = { "sign": "ecdsa", "hash": "sha384", "id": "" }; +const sha512 = { "sign": "ecdsa", "hash": "sha512", "id": "" }; +const DSA = { "sign": "dsa", "hash": "sha1", "id": "" }; +const ripemd160WithRSA = { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" }; +const md5WithRSAEncryption = { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" }; +const require$$6 = { + sha224WithRSAEncryption, + "RSA-SHA224": { "sign": "ecdsa/rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" }, + sha256WithRSAEncryption, + "RSA-SHA256": { "sign": "ecdsa/rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" }, + sha384WithRSAEncryption, + "RSA-SHA384": { "sign": "ecdsa/rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" }, + sha512WithRSAEncryption, + "RSA-SHA512": { "sign": "ecdsa/rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" }, + "RSA-SHA1": { "sign": "rsa", "hash": "sha1", "id": "3021300906052b0e03021a05000414" }, + "ecdsa-with-SHA1": { "sign": "ecdsa", "hash": "sha1", "id": "" }, + sha256, + sha224, + sha384, + sha512, + "DSA-SHA": { "sign": "dsa", "hash": "sha1", "id": "" }, + "DSA-SHA1": { "sign": "dsa", "hash": "sha1", "id": "" }, + DSA, + "DSA-WITH-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" }, + "DSA-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" }, + "DSA-WITH-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" }, + "DSA-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" }, + "DSA-WITH-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" }, + "DSA-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" }, + "DSA-WITH-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" }, + "DSA-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" }, + "DSA-RIPEMD160": { "sign": "dsa", "hash": "rmd160", "id": "" }, + ripemd160WithRSA, + "RSA-RIPEMD160": { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" }, + md5WithRSAEncryption, + "RSA-MD5": { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" } +}; +var algos; +var hasRequiredAlgos; +function requireAlgos() { + if (hasRequiredAlgos) return algos; + hasRequiredAlgos = 1; + algos = require$$6; + return algos; +} +var browser$a = {}; +var precondition; +var hasRequiredPrecondition; +function requirePrecondition() { + if (hasRequiredPrecondition) return precondition; + hasRequiredPrecondition = 1; + var MAX_ALLOC = Math.pow(2, 30) - 1; + precondition = function(iterations, keylen) { + if (typeof iterations !== "number") { + throw new TypeError("Iterations not a number"); + } + if (iterations < 0) { + throw new TypeError("Bad iterations"); + } + if (typeof keylen !== "number") { + throw new TypeError("Key length not a number"); + } + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { + throw new TypeError("Bad key length"); + } + }; + return precondition; +} +var defaultEncoding_1; +var hasRequiredDefaultEncoding; +function requireDefaultEncoding() { + if (hasRequiredDefaultEncoding) return defaultEncoding_1; + hasRequiredDefaultEncoding = 1; + var defaultEncoding; + if (commonjsGlobal.process && commonjsGlobal.process.browser) { + defaultEncoding = "utf-8"; + } else if (commonjsGlobal.process && commonjsGlobal.process.version) { + var pVersionMajor = parseInt(process.version.split(".")[0].slice(1), 10); + defaultEncoding = pVersionMajor >= 6 ? "utf-8" : "binary"; + } else { + defaultEncoding = "utf-8"; + } + defaultEncoding_1 = defaultEncoding; + return defaultEncoding_1; +} +var toBuffer; +var hasRequiredToBuffer; +function requireToBuffer() { + if (hasRequiredToBuffer) return toBuffer; + hasRequiredToBuffer = 1; + var Buffer2 = requireSafeBuffer().Buffer; + toBuffer = function(thing, encoding2, name) { + if (Buffer2.isBuffer(thing)) { + return thing; + } else if (typeof thing === "string") { + return Buffer2.from(thing, encoding2); + } else if (ArrayBuffer.isView(thing)) { + return Buffer2.from(thing.buffer); + } else { + throw new TypeError(name + " must be a string, a Buffer, a typed array or a DataView"); + } + }; + return toBuffer; +} +var syncBrowser; +var hasRequiredSyncBrowser; +function requireSyncBrowser() { + if (hasRequiredSyncBrowser) return syncBrowser; + hasRequiredSyncBrowser = 1; + var md52 = requireMd5(); + var RIPEMD160 = requireRipemd160(); + var sha2 = requireSha_js(); + var Buffer2 = requireSafeBuffer().Buffer; + var checkParameters = requirePrecondition(); + var defaultEncoding = requireDefaultEncoding(); + var toBuffer2 = requireToBuffer(); + var ZEROS = Buffer2.alloc(128); + var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 + }; + function Hmac(alg, key2, saltLen) { + var hash2 = getDigest(alg); + var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64; + if (key2.length > blocksize) { + key2 = hash2(key2); + } else if (key2.length < blocksize) { + key2 = Buffer2.concat([key2, ZEROS], blocksize); + } + var ipad = Buffer2.allocUnsafe(blocksize + sizes[alg]); + var opad = Buffer2.allocUnsafe(blocksize + sizes[alg]); + for (var i = 0; i < blocksize; i++) { + ipad[i] = key2[i] ^ 54; + opad[i] = key2[i] ^ 92; + } + var ipad1 = Buffer2.allocUnsafe(blocksize + saltLen + 4); + ipad.copy(ipad1, 0, 0, blocksize); + this.ipad1 = ipad1; + this.ipad2 = ipad; + this.opad = opad; + this.alg = alg; + this.blocksize = blocksize; + this.hash = hash2; + this.size = sizes[alg]; + } + Hmac.prototype.run = function(data2, ipad) { + data2.copy(ipad, this.blocksize); + var h = this.hash(ipad); + h.copy(this.opad, this.blocksize); + return this.hash(this.opad); + }; + function getDigest(alg) { + function shaFunc(data2) { + return sha2(alg).update(data2).digest(); + } + function rmd160Func(data2) { + return new RIPEMD160().update(data2).digest(); + } + if (alg === "rmd160" || alg === "ripemd160") return rmd160Func; + if (alg === "md5") return md52; + return shaFunc; + } + function pbkdf2(password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen); + password = toBuffer2(password, defaultEncoding, "Password"); + salt = toBuffer2(salt, defaultEncoding, "Salt"); + digest = digest || "sha1"; + var hmac2 = new Hmac(digest, password, salt.length); + var DK = Buffer2.allocUnsafe(keylen); + var block1 = Buffer2.allocUnsafe(salt.length + 4); + salt.copy(block1, 0, 0, salt.length); + var destPos = 0; + var hLen = sizes[digest]; + var l = Math.ceil(keylen / hLen); + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length); + var T = hmac2.run(block1, hmac2.ipad1); + var U = T; + for (var j = 1; j < iterations; j++) { + U = hmac2.run(U, hmac2.ipad2); + for (var k = 0; k < hLen; k++) T[k] ^= U[k]; + } + T.copy(DK, destPos); + destPos += hLen; + } + return DK; + } + syncBrowser = pbkdf2; + return syncBrowser; +} +var async; +var hasRequiredAsync; +function requireAsync() { + if (hasRequiredAsync) return async; + hasRequiredAsync = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var checkParameters = requirePrecondition(); + var defaultEncoding = requireDefaultEncoding(); + var sync = requireSyncBrowser(); + var toBuffer2 = requireToBuffer(); + var ZERO_BUF; + var subtle = commonjsGlobal.crypto && commonjsGlobal.crypto.subtle; + var toBrowser = { + sha: "SHA-1", + "sha-1": "SHA-1", + sha1: "SHA-1", + sha256: "SHA-256", + "sha-256": "SHA-256", + sha384: "SHA-384", + "sha-384": "SHA-384", + "sha-512": "SHA-512", + sha512: "SHA-512" + }; + var checks = []; + function checkNative(algo) { + if (commonjsGlobal.process && !commonjsGlobal.process.browser) { + return Promise.resolve(false); + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false); + } + if (checks[algo] !== void 0) { + return checks[algo]; + } + ZERO_BUF = ZERO_BUF || Buffer2.alloc(8); + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(function() { + return true; + }).catch(function() { + return false; + }); + checks[algo] = prom; + return prom; + } + var nextTick; + function getNextTick() { + if (nextTick) { + return nextTick; + } + if (commonjsGlobal.process && commonjsGlobal.process.nextTick) { + nextTick = commonjsGlobal.process.nextTick; + } else if (commonjsGlobal.queueMicrotask) { + nextTick = commonjsGlobal.queueMicrotask; + } else if (commonjsGlobal.setImmediate) { + nextTick = commonjsGlobal.setImmediate; + } else { + nextTick = commonjsGlobal.setTimeout; + } + return nextTick; + } + function browserPbkdf2(password, salt, iterations, length, algo) { + return subtle.importKey( + "raw", + password, + { name: "PBKDF2" }, + false, + ["deriveBits"] + ).then(function(key2) { + return subtle.deriveBits({ + name: "PBKDF2", + salt, + iterations, + hash: { + name: algo + } + }, key2, length << 3); + }).then(function(res) { + return Buffer2.from(res); + }); + } + function resolvePromise(promise, callback) { + promise.then(function(out) { + getNextTick()(function() { + callback(null, out); + }); + }, function(e) { + getNextTick()(function() { + callback(e); + }); + }); + } + async = function(password, salt, iterations, keylen, digest, callback) { + if (typeof digest === "function") { + callback = digest; + digest = void 0; + } + digest = digest || "sha1"; + var algo = toBrowser[digest.toLowerCase()]; + if (!algo || typeof commonjsGlobal.Promise !== "function") { + getNextTick()(function() { + var out; + try { + out = sync(password, salt, iterations, keylen, digest); + } catch (e) { + return callback(e); + } + callback(null, out); + }); + return; + } + checkParameters(iterations, keylen); + password = toBuffer2(password, defaultEncoding, "Password"); + salt = toBuffer2(salt, defaultEncoding, "Salt"); + if (typeof callback !== "function") throw new Error("No callback provided to pbkdf2"); + resolvePromise(checkNative(algo).then(function(resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo); + return sync(password, salt, iterations, keylen, digest); + }), callback); + }; + return async; +} +var hasRequiredBrowser$a; +function requireBrowser$a() { + if (hasRequiredBrowser$a) return browser$a; + hasRequiredBrowser$a = 1; + browser$a.pbkdf2 = requireAsync(); + browser$a.pbkdf2Sync = requireSyncBrowser(); + return browser$a; +} +var browser$9 = {}; +var des$1 = {}; +var utils$4 = {}; +var hasRequiredUtils$4; +function requireUtils$4() { + if (hasRequiredUtils$4) return utils$4; + hasRequiredUtils$4 = 1; + utils$4.readUInt32BE = function readUInt32BE(bytes, off) { + var res = bytes[0 + off] << 24 | bytes[1 + off] << 16 | bytes[2 + off] << 8 | bytes[3 + off]; + return res >>> 0; + }; + utils$4.writeUInt32BE = function writeUInt32BE(bytes, value, off) { + bytes[0 + off] = value >>> 24; + bytes[1 + off] = value >>> 16 & 255; + bytes[2 + off] = value >>> 8 & 255; + bytes[3 + off] = value & 255; + }; + utils$4.ip = function ip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + for (var i = 6; i >= 0; i -= 2) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= inR >>> j + i & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= inL >>> j + i & 1; + } + } + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= inR >>> j + i & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= inL >>> j + i & 1; + } + } + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; + }; + utils$4.rip = function rip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + for (var i = 0; i < 4; i++) { + for (var j = 24; j >= 0; j -= 8) { + outL <<= 1; + outL |= inR >>> j + i & 1; + outL <<= 1; + outL |= inL >>> j + i & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= inR >>> j + i & 1; + outR <<= 1; + outR |= inL >>> j + i & 1; + } + } + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; + }; + utils$4.pc1 = function pc1(inL, inR, out, off) { + var outL = 0; + var outR = 0; + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= inR >> j + i & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= inL >> j + i & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= inR >> j + i & 1; + } + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= inR >> j + i & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= inL >> j + i & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= inL >> j + i & 1; + } + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; + }; + utils$4.r28shl = function r28shl(num, shift) { + return num << shift & 268435455 | num >>> 28 - shift; + }; + var pc2table = [ + // inL => outL + 14, + 11, + 17, + 4, + 27, + 23, + 25, + 0, + 13, + 22, + 7, + 18, + 5, + 9, + 16, + 24, + 2, + 20, + 12, + 21, + 1, + 8, + 15, + 26, + // inR => outR + 15, + 4, + 25, + 19, + 9, + 1, + 26, + 16, + 5, + 11, + 23, + 8, + 12, + 7, + 17, + 0, + 22, + 3, + 10, + 14, + 6, + 20, + 27, + 24 + ]; + utils$4.pc2 = function pc2(inL, inR, out, off) { + var outL = 0; + var outR = 0; + var len = pc2table.length >>> 1; + for (var i = 0; i < len; i++) { + outL <<= 1; + outL |= inL >>> pc2table[i] & 1; + } + for (var i = len; i < pc2table.length; i++) { + outR <<= 1; + outR |= inR >>> pc2table[i] & 1; + } + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; + }; + utils$4.expand = function expand(r, out, off) { + var outL = 0; + var outR = 0; + outL = (r & 1) << 5 | r >>> 27; + for (var i = 23; i >= 15; i -= 4) { + outL <<= 6; + outL |= r >>> i & 63; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= r >>> i & 63; + outR <<= 6; + } + outR |= (r & 31) << 1 | r >>> 31; + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; + }; + var sTable = [ + 14, + 0, + 4, + 15, + 13, + 7, + 1, + 4, + 2, + 14, + 15, + 2, + 11, + 13, + 8, + 1, + 3, + 10, + 10, + 6, + 6, + 12, + 12, + 11, + 5, + 9, + 9, + 5, + 0, + 3, + 7, + 8, + 4, + 15, + 1, + 12, + 14, + 8, + 8, + 2, + 13, + 4, + 6, + 9, + 2, + 1, + 11, + 7, + 15, + 5, + 12, + 11, + 9, + 3, + 7, + 14, + 3, + 10, + 10, + 0, + 5, + 6, + 0, + 13, + 15, + 3, + 1, + 13, + 8, + 4, + 14, + 7, + 6, + 15, + 11, + 2, + 3, + 8, + 4, + 14, + 9, + 12, + 7, + 0, + 2, + 1, + 13, + 10, + 12, + 6, + 0, + 9, + 5, + 11, + 10, + 5, + 0, + 13, + 14, + 8, + 7, + 10, + 11, + 1, + 10, + 3, + 4, + 15, + 13, + 4, + 1, + 2, + 5, + 11, + 8, + 6, + 12, + 7, + 6, + 12, + 9, + 0, + 3, + 5, + 2, + 14, + 15, + 9, + 10, + 13, + 0, + 7, + 9, + 0, + 14, + 9, + 6, + 3, + 3, + 4, + 15, + 6, + 5, + 10, + 1, + 2, + 13, + 8, + 12, + 5, + 7, + 14, + 11, + 12, + 4, + 11, + 2, + 15, + 8, + 1, + 13, + 1, + 6, + 10, + 4, + 13, + 9, + 0, + 8, + 6, + 15, + 9, + 3, + 8, + 0, + 7, + 11, + 4, + 1, + 15, + 2, + 14, + 12, + 3, + 5, + 11, + 10, + 5, + 14, + 2, + 7, + 12, + 7, + 13, + 13, + 8, + 14, + 11, + 3, + 5, + 0, + 6, + 6, + 15, + 9, + 0, + 10, + 3, + 1, + 4, + 2, + 7, + 8, + 2, + 5, + 12, + 11, + 1, + 12, + 10, + 4, + 14, + 15, + 9, + 10, + 3, + 6, + 15, + 9, + 0, + 0, + 6, + 12, + 10, + 11, + 1, + 7, + 13, + 13, + 8, + 15, + 9, + 1, + 4, + 3, + 5, + 14, + 11, + 5, + 12, + 2, + 7, + 8, + 2, + 4, + 14, + 2, + 14, + 12, + 11, + 4, + 2, + 1, + 12, + 7, + 4, + 10, + 7, + 11, + 13, + 6, + 1, + 8, + 5, + 5, + 0, + 3, + 15, + 15, + 10, + 13, + 3, + 0, + 9, + 14, + 8, + 9, + 6, + 4, + 11, + 2, + 8, + 1, + 12, + 11, + 7, + 10, + 1, + 13, + 14, + 7, + 2, + 8, + 13, + 15, + 6, + 9, + 15, + 12, + 0, + 5, + 9, + 6, + 10, + 3, + 4, + 0, + 5, + 14, + 3, + 12, + 10, + 1, + 15, + 10, + 4, + 15, + 2, + 9, + 7, + 2, + 12, + 6, + 9, + 8, + 5, + 0, + 6, + 13, + 1, + 3, + 13, + 4, + 14, + 14, + 0, + 7, + 11, + 5, + 3, + 11, + 8, + 9, + 4, + 14, + 3, + 15, + 2, + 5, + 12, + 2, + 9, + 8, + 5, + 12, + 15, + 3, + 10, + 7, + 11, + 0, + 14, + 4, + 1, + 10, + 7, + 1, + 6, + 13, + 0, + 11, + 8, + 6, + 13, + 4, + 13, + 11, + 0, + 2, + 11, + 14, + 7, + 15, + 4, + 0, + 9, + 8, + 1, + 13, + 10, + 3, + 14, + 12, + 3, + 9, + 5, + 7, + 12, + 5, + 2, + 10, + 15, + 6, + 8, + 1, + 6, + 1, + 6, + 4, + 11, + 11, + 13, + 13, + 8, + 12, + 1, + 3, + 4, + 7, + 10, + 14, + 7, + 10, + 9, + 15, + 5, + 6, + 0, + 8, + 15, + 0, + 14, + 5, + 2, + 9, + 3, + 2, + 12, + 13, + 1, + 2, + 15, + 8, + 13, + 4, + 8, + 6, + 10, + 15, + 3, + 11, + 7, + 1, + 4, + 10, + 12, + 9, + 5, + 3, + 6, + 14, + 11, + 5, + 0, + 0, + 14, + 12, + 9, + 7, + 2, + 7, + 2, + 11, + 1, + 4, + 14, + 1, + 7, + 9, + 4, + 12, + 10, + 14, + 8, + 2, + 13, + 0, + 15, + 6, + 12, + 10, + 9, + 13, + 0, + 15, + 3, + 3, + 5, + 5, + 6, + 8, + 11 + ]; + utils$4.substitute = function substitute(inL, inR) { + var out = 0; + for (var i = 0; i < 4; i++) { + var b = inL >>> 18 - i * 6 & 63; + var sb = sTable[i * 64 + b]; + out <<= 4; + out |= sb; + } + for (var i = 0; i < 4; i++) { + var b = inR >>> 18 - i * 6 & 63; + var sb = sTable[4 * 64 + i * 64 + b]; + out <<= 4; + out |= sb; + } + return out >>> 0; + }; + var permuteTable = [ + 16, + 25, + 12, + 11, + 3, + 20, + 4, + 15, + 31, + 17, + 9, + 6, + 27, + 14, + 1, + 22, + 30, + 24, + 8, + 18, + 0, + 5, + 29, + 23, + 13, + 19, + 2, + 26, + 10, + 21, + 28, + 7 + ]; + utils$4.permute = function permute(num) { + var out = 0; + for (var i = 0; i < permuteTable.length; i++) { + out <<= 1; + out |= num >>> permuteTable[i] & 1; + } + return out >>> 0; + }; + utils$4.padSplit = function padSplit(num, size, group) { + var str = num.toString(2); + while (str.length < size) + str = "0" + str; + var out = []; + for (var i = 0; i < size; i += group) + out.push(str.slice(i, i + group)); + return out.join(" "); + }; + return utils$4; +} +var minimalisticAssert; +var hasRequiredMinimalisticAssert; +function requireMinimalisticAssert() { + if (hasRequiredMinimalisticAssert) return minimalisticAssert; + hasRequiredMinimalisticAssert = 1; + minimalisticAssert = assert2; + function assert2(val, msg) { + if (!val) + throw new Error(msg || "Assertion failed"); + } + assert2.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || "Assertion failed: " + l + " != " + r); + }; + return minimalisticAssert; +} +var cipher; +var hasRequiredCipher; +function requireCipher() { + if (hasRequiredCipher) return cipher; + hasRequiredCipher = 1; + var assert2 = requireMinimalisticAssert(); + function Cipher(options2) { + this.options = options2; + this.type = this.options.type; + this.blockSize = 8; + this._init(); + this.buffer = new Array(this.blockSize); + this.bufferOff = 0; + this.padding = options2.padding !== false; + } + cipher = Cipher; + Cipher.prototype._init = function _init() { + }; + Cipher.prototype.update = function update(data2) { + if (data2.length === 0) + return []; + if (this.type === "decrypt") + return this._updateDecrypt(data2); + else + return this._updateEncrypt(data2); + }; + Cipher.prototype._buffer = function _buffer(data2, off) { + var min2 = Math.min(this.buffer.length - this.bufferOff, data2.length - off); + for (var i = 0; i < min2; i++) + this.buffer[this.bufferOff + i] = data2[off + i]; + this.bufferOff += min2; + return min2; + }; + Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { + this._update(this.buffer, 0, out, off); + this.bufferOff = 0; + return this.blockSize; + }; + Cipher.prototype._updateEncrypt = function _updateEncrypt(data2) { + var inputOff = 0; + var outputOff = 0; + var count = (this.bufferOff + data2.length) / this.blockSize | 0; + var out = new Array(count * this.blockSize); + if (this.bufferOff !== 0) { + inputOff += this._buffer(data2, inputOff); + if (this.bufferOff === this.buffer.length) + outputOff += this._flushBuffer(out, outputOff); + } + var max2 = data2.length - (data2.length - inputOff) % this.blockSize; + for (; inputOff < max2; inputOff += this.blockSize) { + this._update(data2, inputOff, out, outputOff); + outputOff += this.blockSize; + } + for (; inputOff < data2.length; inputOff++, this.bufferOff++) + this.buffer[this.bufferOff] = data2[inputOff]; + return out; + }; + Cipher.prototype._updateDecrypt = function _updateDecrypt(data2) { + var inputOff = 0; + var outputOff = 0; + var count = Math.ceil((this.bufferOff + data2.length) / this.blockSize) - 1; + var out = new Array(count * this.blockSize); + for (; count > 0; count--) { + inputOff += this._buffer(data2, inputOff); + outputOff += this._flushBuffer(out, outputOff); + } + inputOff += this._buffer(data2, inputOff); + return out; + }; + Cipher.prototype.final = function final(buffer2) { + var first; + if (buffer2) + first = this.update(buffer2); + var last; + if (this.type === "encrypt") + last = this._finalEncrypt(); + else + last = this._finalDecrypt(); + if (first) + return first.concat(last); + else + return last; + }; + Cipher.prototype._pad = function _pad(buffer2, off) { + if (off === 0) + return false; + while (off < buffer2.length) + buffer2[off++] = 0; + return true; + }; + Cipher.prototype._finalEncrypt = function _finalEncrypt() { + if (!this._pad(this.buffer, this.bufferOff)) + return []; + var out = new Array(this.blockSize); + this._update(this.buffer, 0, out, 0); + return out; + }; + Cipher.prototype._unpad = function _unpad(buffer2) { + return buffer2; + }; + Cipher.prototype._finalDecrypt = function _finalDecrypt() { + assert2.equal(this.bufferOff, this.blockSize, "Not enough data to decrypt"); + var out = new Array(this.blockSize); + this._flushBuffer(out, 0); + return this._unpad(out); + }; + return cipher; +} +var des; +var hasRequiredDes$1; +function requireDes$1() { + if (hasRequiredDes$1) return des; + hasRequiredDes$1 = 1; + var assert2 = requireMinimalisticAssert(); + var inherits = requireInherits_browser$1(); + var utils2 = requireUtils$4(); + var Cipher = requireCipher(); + function DESState() { + this.tmp = new Array(2); + this.keys = null; + } + function DES(options2) { + Cipher.call(this, options2); + var state2 = new DESState(); + this._desState = state2; + this.deriveKeys(state2, options2.key); + } + inherits(DES, Cipher); + des = DES; + DES.create = function create(options2) { + return new DES(options2); + }; + var shiftTable = [ + 1, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 1 + ]; + DES.prototype.deriveKeys = function deriveKeys(state2, key2) { + state2.keys = new Array(16 * 2); + assert2.equal(key2.length, this.blockSize, "Invalid key length"); + var kL = utils2.readUInt32BE(key2, 0); + var kR = utils2.readUInt32BE(key2, 4); + utils2.pc1(kL, kR, state2.tmp, 0); + kL = state2.tmp[0]; + kR = state2.tmp[1]; + for (var i = 0; i < state2.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils2.r28shl(kL, shift); + kR = utils2.r28shl(kR, shift); + utils2.pc2(kL, kR, state2.keys, i); + } + }; + DES.prototype._update = function _update(inp, inOff, out, outOff) { + var state2 = this._desState; + var l = utils2.readUInt32BE(inp, inOff); + var r = utils2.readUInt32BE(inp, inOff + 4); + utils2.ip(l, r, state2.tmp, 0); + l = state2.tmp[0]; + r = state2.tmp[1]; + if (this.type === "encrypt") + this._encrypt(state2, l, r, state2.tmp, 0); + else + this._decrypt(state2, l, r, state2.tmp, 0); + l = state2.tmp[0]; + r = state2.tmp[1]; + utils2.writeUInt32BE(out, l, outOff); + utils2.writeUInt32BE(out, r, outOff + 4); + }; + DES.prototype._pad = function _pad(buffer2, off) { + if (this.padding === false) { + return false; + } + var value = buffer2.length - off; + for (var i = off; i < buffer2.length; i++) + buffer2[i] = value; + return true; + }; + DES.prototype._unpad = function _unpad(buffer2) { + if (this.padding === false) { + return buffer2; + } + var pad = buffer2[buffer2.length - 1]; + for (var i = buffer2.length - pad; i < buffer2.length; i++) + assert2.equal(buffer2[i], pad); + return buffer2.slice(0, buffer2.length - pad); + }; + DES.prototype._encrypt = function _encrypt(state2, lStart, rStart, out, off) { + var l = lStart; + var r = rStart; + for (var i = 0; i < state2.keys.length; i += 2) { + var keyL = state2.keys[i]; + var keyR = state2.keys[i + 1]; + utils2.expand(r, state2.tmp, 0); + keyL ^= state2.tmp[0]; + keyR ^= state2.tmp[1]; + var s = utils2.substitute(keyL, keyR); + var f = utils2.permute(s); + var t = r; + r = (l ^ f) >>> 0; + l = t; + } + utils2.rip(r, l, out, off); + }; + DES.prototype._decrypt = function _decrypt(state2, lStart, rStart, out, off) { + var l = rStart; + var r = lStart; + for (var i = state2.keys.length - 2; i >= 0; i -= 2) { + var keyL = state2.keys[i]; + var keyR = state2.keys[i + 1]; + utils2.expand(l, state2.tmp, 0); + keyL ^= state2.tmp[0]; + keyR ^= state2.tmp[1]; + var s = utils2.substitute(keyL, keyR); + var f = utils2.permute(s); + var t = l; + l = (r ^ f) >>> 0; + r = t; + } + utils2.rip(l, r, out, off); + }; + return des; +} +var cbc$1 = {}; +var hasRequiredCbc$1; +function requireCbc$1() { + if (hasRequiredCbc$1) return cbc$1; + hasRequiredCbc$1 = 1; + var assert2 = requireMinimalisticAssert(); + var inherits = requireInherits_browser$1(); + var proto = {}; + function CBCState(iv) { + assert2.equal(iv.length, 8, "Invalid IV length"); + this.iv = new Array(8); + for (var i = 0; i < this.iv.length; i++) + this.iv[i] = iv[i]; + } + function instantiate(Base) { + function CBC(options2) { + Base.call(this, options2); + this._cbcInit(); + } + inherits(CBC, Base); + var keys = Object.keys(proto); + for (var i = 0; i < keys.length; i++) { + var key2 = keys[i]; + CBC.prototype[key2] = proto[key2]; + } + CBC.create = function create(options2) { + return new CBC(options2); + }; + return CBC; + } + cbc$1.instantiate = instantiate; + proto._cbcInit = function _cbcInit() { + var state2 = new CBCState(this.options.iv); + this._cbcState = state2; + }; + proto._update = function _update(inp, inOff, out, outOff) { + var state2 = this._cbcState; + var superProto = this.constructor.super_.prototype; + var iv = state2.iv; + if (this.type === "encrypt") { + for (var i = 0; i < this.blockSize; i++) + iv[i] ^= inp[inOff + i]; + superProto._update.call(this, iv, 0, out, outOff); + for (var i = 0; i < this.blockSize; i++) + iv[i] = out[outOff + i]; + } else { + superProto._update.call(this, inp, inOff, out, outOff); + for (var i = 0; i < this.blockSize; i++) + out[outOff + i] ^= iv[i]; + for (var i = 0; i < this.blockSize; i++) + iv[i] = inp[inOff + i]; + } + }; + return cbc$1; +} +var ede; +var hasRequiredEde; +function requireEde() { + if (hasRequiredEde) return ede; + hasRequiredEde = 1; + var assert2 = requireMinimalisticAssert(); + var inherits = requireInherits_browser$1(); + var Cipher = requireCipher(); + var DES = requireDes$1(); + function EDEState(type2, key2) { + assert2.equal(key2.length, 24, "Invalid key length"); + var k1 = key2.slice(0, 8); + var k2 = key2.slice(8, 16); + var k3 = key2.slice(16, 24); + if (type2 === "encrypt") { + this.ciphers = [ + DES.create({ type: "encrypt", key: k1 }), + DES.create({ type: "decrypt", key: k2 }), + DES.create({ type: "encrypt", key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: "decrypt", key: k3 }), + DES.create({ type: "encrypt", key: k2 }), + DES.create({ type: "decrypt", key: k1 }) + ]; + } + } + function EDE(options2) { + Cipher.call(this, options2); + var state2 = new EDEState(this.type, this.options.key); + this._edeState = state2; + } + inherits(EDE, Cipher); + ede = EDE; + EDE.create = function create(options2) { + return new EDE(options2); + }; + EDE.prototype._update = function _update(inp, inOff, out, outOff) { + var state2 = this._edeState; + state2.ciphers[0]._update(inp, inOff, out, outOff); + state2.ciphers[1]._update(out, outOff, out, outOff); + state2.ciphers[2]._update(out, outOff, out, outOff); + }; + EDE.prototype._pad = DES.prototype._pad; + EDE.prototype._unpad = DES.prototype._unpad; + return ede; +} +var hasRequiredDes; +function requireDes() { + if (hasRequiredDes) return des$1; + hasRequiredDes = 1; + des$1.utils = requireUtils$4(); + des$1.Cipher = requireCipher(); + des$1.DES = requireDes$1(); + des$1.CBC = requireCbc$1(); + des$1.EDE = requireEde(); + return des$1; +} +var browserifyDes; +var hasRequiredBrowserifyDes; +function requireBrowserifyDes() { + if (hasRequiredBrowserifyDes) return browserifyDes; + hasRequiredBrowserifyDes = 1; + var CipherBase = requireCipherBase(); + var des2 = requireDes(); + var inherits = requireInherits_browser$1(); + var Buffer2 = requireSafeBuffer().Buffer; + var modes2 = { + "des-ede3-cbc": des2.CBC.instantiate(des2.EDE), + "des-ede3": des2.EDE, + "des-ede-cbc": des2.CBC.instantiate(des2.EDE), + "des-ede": des2.EDE, + "des-cbc": des2.CBC.instantiate(des2.DES), + "des-ecb": des2.DES + }; + modes2.des = modes2["des-cbc"]; + modes2.des3 = modes2["des-ede3-cbc"]; + browserifyDes = DES; + inherits(DES, CipherBase); + function DES(opts) { + CipherBase.call(this); + var modeName = opts.mode.toLowerCase(); + var mode = modes2[modeName]; + var type2; + if (opts.decrypt) { + type2 = "decrypt"; + } else { + type2 = "encrypt"; + } + var key2 = opts.key; + if (!Buffer2.isBuffer(key2)) { + key2 = Buffer2.from(key2); + } + if (modeName === "des-ede" || modeName === "des-ede-cbc") { + key2 = Buffer2.concat([key2, key2.slice(0, 8)]); + } + var iv = opts.iv; + if (!Buffer2.isBuffer(iv)) { + iv = Buffer2.from(iv); + } + this._des = mode.create({ + key: key2, + iv, + type: type2 + }); + } + DES.prototype._update = function(data2) { + return Buffer2.from(this._des.update(data2)); + }; + DES.prototype._final = function() { + return Buffer2.from(this._des.final()); + }; + return browserifyDes; +} +var browser$8 = {}; +var encrypter = {}; +var ecb = {}; +var hasRequiredEcb; +function requireEcb() { + if (hasRequiredEcb) return ecb; + hasRequiredEcb = 1; + ecb.encrypt = function(self2, block) { + return self2._cipher.encryptBlock(block); + }; + ecb.decrypt = function(self2, block) { + return self2._cipher.decryptBlock(block); + }; + return ecb; +} +var cbc = {}; +var bufferXor; +var hasRequiredBufferXor; +function requireBufferXor() { + if (hasRequiredBufferXor) return bufferXor; + hasRequiredBufferXor = 1; + bufferXor = function xor2(a, b) { + var length = Math.min(a.length, b.length); + var buffer2 = new Buffer(length); + for (var i = 0; i < length; ++i) { + buffer2[i] = a[i] ^ b[i]; + } + return buffer2; + }; + return bufferXor; +} +var hasRequiredCbc; +function requireCbc() { + if (hasRequiredCbc) return cbc; + hasRequiredCbc = 1; + var xor2 = requireBufferXor(); + cbc.encrypt = function(self2, block) { + var data2 = xor2(block, self2._prev); + self2._prev = self2._cipher.encryptBlock(data2); + return self2._prev; + }; + cbc.decrypt = function(self2, block) { + var pad = self2._prev; + self2._prev = block; + var out = self2._cipher.decryptBlock(block); + return xor2(out, pad); + }; + return cbc; +} +var cfb = {}; +var hasRequiredCfb; +function requireCfb() { + if (hasRequiredCfb) return cfb; + hasRequiredCfb = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var xor2 = requireBufferXor(); + function encryptStart(self2, data2, decrypt) { + var len = data2.length; + var out = xor2(data2, self2._cache); + self2._cache = self2._cache.slice(len); + self2._prev = Buffer2.concat([self2._prev, decrypt ? data2 : out]); + return out; + } + cfb.encrypt = function(self2, data2, decrypt) { + var out = Buffer2.allocUnsafe(0); + var len; + while (data2.length) { + if (self2._cache.length === 0) { + self2._cache = self2._cipher.encryptBlock(self2._prev); + self2._prev = Buffer2.allocUnsafe(0); + } + if (self2._cache.length <= data2.length) { + len = self2._cache.length; + out = Buffer2.concat([out, encryptStart(self2, data2.slice(0, len), decrypt)]); + data2 = data2.slice(len); + } else { + out = Buffer2.concat([out, encryptStart(self2, data2, decrypt)]); + break; + } + } + return out; + }; + return cfb; +} +var cfb8 = {}; +var hasRequiredCfb8; +function requireCfb8() { + if (hasRequiredCfb8) return cfb8; + hasRequiredCfb8 = 1; + var Buffer2 = requireSafeBuffer().Buffer; + function encryptByte(self2, byteParam, decrypt) { + var pad = self2._cipher.encryptBlock(self2._prev); + var out = pad[0] ^ byteParam; + self2._prev = Buffer2.concat([ + self2._prev.slice(1), + Buffer2.from([decrypt ? byteParam : out]) + ]); + return out; + } + cfb8.encrypt = function(self2, chunk, decrypt) { + var len = chunk.length; + var out = Buffer2.allocUnsafe(len); + var i = -1; + while (++i < len) { + out[i] = encryptByte(self2, chunk[i], decrypt); + } + return out; + }; + return cfb8; +} +var cfb1 = {}; +var hasRequiredCfb1; +function requireCfb1() { + if (hasRequiredCfb1) return cfb1; + hasRequiredCfb1 = 1; + var Buffer2 = requireSafeBuffer().Buffer; + function encryptByte(self2, byteParam, decrypt) { + var pad; + var i = -1; + var len = 8; + var out = 0; + var bit, value; + while (++i < len) { + pad = self2._cipher.encryptBlock(self2._prev); + bit = byteParam & 1 << 7 - i ? 128 : 0; + value = pad[0] ^ bit; + out += (value & 128) >> i % 8; + self2._prev = shiftIn(self2._prev, decrypt ? bit : value); + } + return out; + } + function shiftIn(buffer2, value) { + var len = buffer2.length; + var i = -1; + var out = Buffer2.allocUnsafe(buffer2.length); + buffer2 = Buffer2.concat([buffer2, Buffer2.from([value])]); + while (++i < len) { + out[i] = buffer2[i] << 1 | buffer2[i + 1] >> 7; + } + return out; + } + cfb1.encrypt = function(self2, chunk, decrypt) { + var len = chunk.length; + var out = Buffer2.allocUnsafe(len); + var i = -1; + while (++i < len) { + out[i] = encryptByte(self2, chunk[i], decrypt); + } + return out; + }; + return cfb1; +} +var ofb = {}; +var hasRequiredOfb; +function requireOfb() { + if (hasRequiredOfb) return ofb; + hasRequiredOfb = 1; + var xor2 = requireBufferXor(); + function getBlock(self2) { + self2._prev = self2._cipher.encryptBlock(self2._prev); + return self2._prev; + } + ofb.encrypt = function(self2, chunk) { + while (self2._cache.length < chunk.length) { + self2._cache = Buffer.concat([self2._cache, getBlock(self2)]); + } + var pad = self2._cache.slice(0, chunk.length); + self2._cache = self2._cache.slice(chunk.length); + return xor2(chunk, pad); + }; + return ofb; +} +var ctr = {}; +var incr32_1; +var hasRequiredIncr32; +function requireIncr32() { + if (hasRequiredIncr32) return incr32_1; + hasRequiredIncr32 = 1; + function incr32(iv) { + var len = iv.length; + var item; + while (len--) { + item = iv.readUInt8(len); + if (item === 255) { + iv.writeUInt8(0, len); + } else { + item++; + iv.writeUInt8(item, len); + break; + } + } + } + incr32_1 = incr32; + return incr32_1; +} +var hasRequiredCtr; +function requireCtr() { + if (hasRequiredCtr) return ctr; + hasRequiredCtr = 1; + var xor2 = requireBufferXor(); + var Buffer2 = requireSafeBuffer().Buffer; + var incr32 = requireIncr32(); + function getBlock(self2) { + var out = self2._cipher.encryptBlockRaw(self2._prev); + incr32(self2._prev); + return out; + } + var blockSize = 16; + ctr.encrypt = function(self2, chunk) { + var chunkNum = Math.ceil(chunk.length / blockSize); + var start = self2._cache.length; + self2._cache = Buffer2.concat([ + self2._cache, + Buffer2.allocUnsafe(chunkNum * blockSize) + ]); + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self2); + var offset2 = start + i * blockSize; + self2._cache.writeUInt32BE(out[0], offset2 + 0); + self2._cache.writeUInt32BE(out[1], offset2 + 4); + self2._cache.writeUInt32BE(out[2], offset2 + 8); + self2._cache.writeUInt32BE(out[3], offset2 + 12); + } + var pad = self2._cache.slice(0, chunk.length); + self2._cache = self2._cache.slice(chunk.length); + return xor2(chunk, pad); + }; + return ctr; +} +const aes128 = { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" }; +const aes192 = { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" }; +const aes256 = { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" }; +const require$$2 = { + "aes-128-ecb": { "cipher": "AES", "key": 128, "iv": 0, "mode": "ECB", "type": "block" }, + "aes-192-ecb": { "cipher": "AES", "key": 192, "iv": 0, "mode": "ECB", "type": "block" }, + "aes-256-ecb": { "cipher": "AES", "key": 256, "iv": 0, "mode": "ECB", "type": "block" }, + "aes-128-cbc": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" }, + "aes-192-cbc": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" }, + "aes-256-cbc": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" }, + aes128, + aes192, + aes256, + "aes-128-cfb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB", "type": "stream" }, + "aes-192-cfb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB", "type": "stream" }, + "aes-256-cfb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB", "type": "stream" }, + "aes-128-cfb8": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB8", "type": "stream" }, + "aes-192-cfb8": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB8", "type": "stream" }, + "aes-256-cfb8": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB8", "type": "stream" }, + "aes-128-cfb1": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB1", "type": "stream" }, + "aes-192-cfb1": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB1", "type": "stream" }, + "aes-256-cfb1": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB1", "type": "stream" }, + "aes-128-ofb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "OFB", "type": "stream" }, + "aes-192-ofb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "OFB", "type": "stream" }, + "aes-256-ofb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "OFB", "type": "stream" }, + "aes-128-ctr": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CTR", "type": "stream" }, + "aes-192-ctr": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CTR", "type": "stream" }, + "aes-256-ctr": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CTR", "type": "stream" }, + "aes-128-gcm": { "cipher": "AES", "key": 128, "iv": 12, "mode": "GCM", "type": "auth" }, + "aes-192-gcm": { "cipher": "AES", "key": 192, "iv": 12, "mode": "GCM", "type": "auth" }, + "aes-256-gcm": { "cipher": "AES", "key": 256, "iv": 12, "mode": "GCM", "type": "auth" } +}; +var modes_1; +var hasRequiredModes$1; +function requireModes$1() { + if (hasRequiredModes$1) return modes_1; + hasRequiredModes$1 = 1; + var modeModules = { + ECB: requireEcb(), + CBC: requireCbc(), + CFB: requireCfb(), + CFB8: requireCfb8(), + CFB1: requireCfb1(), + OFB: requireOfb(), + CTR: requireCtr(), + GCM: requireCtr() + }; + var modes2 = require$$2; + for (var key2 in modes2) { + modes2[key2].module = modeModules[modes2[key2].mode]; + } + modes_1 = modes2; + return modes_1; +} +var aes = {}; +var hasRequiredAes; +function requireAes() { + if (hasRequiredAes) return aes; + hasRequiredAes = 1; + var Buffer2 = requireSafeBuffer().Buffer; + function asUInt32Array(buf) { + if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf); + var len = buf.length / 4 | 0; + var out = new Array(len); + for (var i = 0; i < len; i++) { + out[i] = buf.readUInt32BE(i * 4); + } + return out; + } + function scrubVec(v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0; + } + } + function cryptBlock(M, keySchedule, SUB_MIX, SBOX, nRounds) { + var SUB_MIX0 = SUB_MIX[0]; + var SUB_MIX1 = SUB_MIX[1]; + var SUB_MIX2 = SUB_MIX[2]; + var SUB_MIX3 = SUB_MIX[3]; + var s0 = M[0] ^ keySchedule[0]; + var s1 = M[1] ^ keySchedule[1]; + var s2 = M[2] ^ keySchedule[2]; + var s3 = M[3] ^ keySchedule[3]; + var t0, t1, t2, t3; + var ksRow = 4; + for (var round2 = 1; round2 < nRounds; round2++) { + t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[s1 >>> 16 & 255] ^ SUB_MIX2[s2 >>> 8 & 255] ^ SUB_MIX3[s3 & 255] ^ keySchedule[ksRow++]; + t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[s2 >>> 16 & 255] ^ SUB_MIX2[s3 >>> 8 & 255] ^ SUB_MIX3[s0 & 255] ^ keySchedule[ksRow++]; + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[s3 >>> 16 & 255] ^ SUB_MIX2[s0 >>> 8 & 255] ^ SUB_MIX3[s1 & 255] ^ keySchedule[ksRow++]; + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[s0 >>> 16 & 255] ^ SUB_MIX2[s1 >>> 8 & 255] ^ SUB_MIX3[s2 & 255] ^ keySchedule[ksRow++]; + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + t0 = (SBOX[s0 >>> 24] << 24 | SBOX[s1 >>> 16 & 255] << 16 | SBOX[s2 >>> 8 & 255] << 8 | SBOX[s3 & 255]) ^ keySchedule[ksRow++]; + t1 = (SBOX[s1 >>> 24] << 24 | SBOX[s2 >>> 16 & 255] << 16 | SBOX[s3 >>> 8 & 255] << 8 | SBOX[s0 & 255]) ^ keySchedule[ksRow++]; + t2 = (SBOX[s2 >>> 24] << 24 | SBOX[s3 >>> 16 & 255] << 16 | SBOX[s0 >>> 8 & 255] << 8 | SBOX[s1 & 255]) ^ keySchedule[ksRow++]; + t3 = (SBOX[s3 >>> 24] << 24 | SBOX[s0 >>> 16 & 255] << 16 | SBOX[s1 >>> 8 & 255] << 8 | SBOX[s2 & 255]) ^ keySchedule[ksRow++]; + t0 = t0 >>> 0; + t1 = t1 >>> 0; + t2 = t2 >>> 0; + t3 = t3 >>> 0; + return [t0, t1, t2, t3]; + } + var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; + var G = function() { + var d = new Array(256); + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1; + } else { + d[j] = j << 1 ^ 283; + } + } + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX = [[], [], [], []]; + var INV_SUB_MIX = [[], [], [], []]; + var x = 0; + var xi = 0; + for (var i = 0; i < 256; ++i) { + var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; + sx = sx >>> 8 ^ sx & 255 ^ 99; + SBOX[x] = sx; + INV_SBOX[sx] = x; + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + var t = d[sx] * 257 ^ sx * 16843008; + SUB_MIX[0][x] = t << 24 | t >>> 8; + SUB_MIX[1][x] = t << 16 | t >>> 16; + SUB_MIX[2][x] = t << 8 | t >>> 24; + SUB_MIX[3][x] = t; + t = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008; + INV_SUB_MIX[0][sx] = t << 24 | t >>> 8; + INV_SUB_MIX[1][sx] = t << 16 | t >>> 16; + INV_SUB_MIX[2][sx] = t << 8 | t >>> 24; + INV_SUB_MIX[3][sx] = t; + if (x === 0) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + return { + SBOX, + INV_SBOX, + SUB_MIX, + INV_SUB_MIX + }; + }(); + function AES(key2) { + this._key = asUInt32Array(key2); + this._reset(); + } + AES.blockSize = 4 * 4; + AES.keySize = 256 / 8; + AES.prototype.blockSize = AES.blockSize; + AES.prototype.keySize = AES.keySize; + AES.prototype._reset = function() { + var keyWords = this._key; + var keySize = keyWords.length; + var nRounds = keySize + 6; + var ksRows = (nRounds + 1) * 4; + var keySchedule = []; + for (var k = 0; k < keySize; k++) { + keySchedule[k] = keyWords[k]; + } + for (k = keySize; k < ksRows; k++) { + var t = keySchedule[k - 1]; + if (k % keySize === 0) { + t = t << 8 | t >>> 24; + t = G.SBOX[t >>> 24] << 24 | G.SBOX[t >>> 16 & 255] << 16 | G.SBOX[t >>> 8 & 255] << 8 | G.SBOX[t & 255]; + t ^= RCON[k / keySize | 0] << 24; + } else if (keySize > 6 && k % keySize === 4) { + t = G.SBOX[t >>> 24] << 24 | G.SBOX[t >>> 16 & 255] << 16 | G.SBOX[t >>> 8 & 255] << 8 | G.SBOX[t & 255]; + } + keySchedule[k] = keySchedule[k - keySize] ^ t; + } + var invKeySchedule = []; + for (var ik = 0; ik < ksRows; ik++) { + var ksR = ksRows - ik; + var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]; + if (ik < 4 || ksR <= 4) { + invKeySchedule[ik] = tt; + } else { + invKeySchedule[ik] = G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[tt >>> 16 & 255]] ^ G.INV_SUB_MIX[2][G.SBOX[tt >>> 8 & 255]] ^ G.INV_SUB_MIX[3][G.SBOX[tt & 255]]; + } + } + this._nRounds = nRounds; + this._keySchedule = keySchedule; + this._invKeySchedule = invKeySchedule; + }; + AES.prototype.encryptBlockRaw = function(M) { + M = asUInt32Array(M); + return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds); + }; + AES.prototype.encryptBlock = function(M) { + var out = this.encryptBlockRaw(M); + var buf = Buffer2.allocUnsafe(16); + buf.writeUInt32BE(out[0], 0); + buf.writeUInt32BE(out[1], 4); + buf.writeUInt32BE(out[2], 8); + buf.writeUInt32BE(out[3], 12); + return buf; + }; + AES.prototype.decryptBlock = function(M) { + M = asUInt32Array(M); + var m1 = M[1]; + M[1] = M[3]; + M[3] = m1; + var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds); + var buf = Buffer2.allocUnsafe(16); + buf.writeUInt32BE(out[0], 0); + buf.writeUInt32BE(out[3], 4); + buf.writeUInt32BE(out[2], 8); + buf.writeUInt32BE(out[1], 12); + return buf; + }; + AES.prototype.scrub = function() { + scrubVec(this._keySchedule); + scrubVec(this._invKeySchedule); + scrubVec(this._key); + }; + aes.AES = AES; + return aes; +} +var ghash; +var hasRequiredGhash; +function requireGhash() { + if (hasRequiredGhash) return ghash; + hasRequiredGhash = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var ZEROES = Buffer2.alloc(16, 0); + function toArray(buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ]; + } + function fromArray(out) { + var buf = Buffer2.allocUnsafe(16); + buf.writeUInt32BE(out[0] >>> 0, 0); + buf.writeUInt32BE(out[1] >>> 0, 4); + buf.writeUInt32BE(out[2] >>> 0, 8); + buf.writeUInt32BE(out[3] >>> 0, 12); + return buf; + } + function GHASH(key2) { + this.h = key2; + this.state = Buffer2.alloc(16, 0); + this.cache = Buffer2.allocUnsafe(0); + } + GHASH.prototype.ghash = function(block) { + var i = -1; + while (++i < block.length) { + this.state[i] ^= block[i]; + } + this._multiply(); + }; + GHASH.prototype._multiply = function() { + var Vi = toArray(this.h); + var Zi = [0, 0, 0, 0]; + var j, xi, lsbVi; + var i = -1; + while (++i < 128) { + xi = (this.state[~~(i / 8)] & 1 << 7 - i % 8) !== 0; + if (xi) { + Zi[0] ^= Vi[0]; + Zi[1] ^= Vi[1]; + Zi[2] ^= Vi[2]; + Zi[3] ^= Vi[3]; + } + lsbVi = (Vi[3] & 1) !== 0; + for (j = 3; j > 0; j--) { + Vi[j] = Vi[j] >>> 1 | (Vi[j - 1] & 1) << 31; + } + Vi[0] = Vi[0] >>> 1; + if (lsbVi) { + Vi[0] = Vi[0] ^ 225 << 24; + } + } + this.state = fromArray(Zi); + }; + GHASH.prototype.update = function(buf) { + this.cache = Buffer2.concat([this.cache, buf]); + var chunk; + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + this.ghash(chunk); + } + }; + GHASH.prototype.final = function(abl, bl) { + if (this.cache.length) { + this.ghash(Buffer2.concat([this.cache, ZEROES], 16)); + } + this.ghash(fromArray([0, abl, 0, bl])); + return this.state; + }; + ghash = GHASH; + return ghash; +} +var authCipher; +var hasRequiredAuthCipher; +function requireAuthCipher() { + if (hasRequiredAuthCipher) return authCipher; + hasRequiredAuthCipher = 1; + var aes2 = requireAes(); + var Buffer2 = requireSafeBuffer().Buffer; + var Transform = requireCipherBase(); + var inherits = requireInherits_browser$1(); + var GHASH = requireGhash(); + var xor2 = requireBufferXor(); + var incr32 = requireIncr32(); + function xorTest(a, b) { + var out = 0; + if (a.length !== b.length) out++; + var len = Math.min(a.length, b.length); + for (var i = 0; i < len; ++i) { + out += a[i] ^ b[i]; + } + return out; + } + function calcIv(self2, iv, ck) { + if (iv.length === 12) { + self2._finID = Buffer2.concat([iv, Buffer2.from([0, 0, 0, 1])]); + return Buffer2.concat([iv, Buffer2.from([0, 0, 0, 2])]); + } + var ghash2 = new GHASH(ck); + var len = iv.length; + var toPad = len % 16; + ghash2.update(iv); + if (toPad) { + toPad = 16 - toPad; + ghash2.update(Buffer2.alloc(toPad, 0)); + } + ghash2.update(Buffer2.alloc(8, 0)); + var ivBits = len * 8; + var tail = Buffer2.alloc(8); + tail.writeUIntBE(ivBits, 0, 8); + ghash2.update(tail); + self2._finID = ghash2.state; + var out = Buffer2.from(self2._finID); + incr32(out); + return out; + } + function StreamCipher(mode, key2, iv, decrypt) { + Transform.call(this); + var h = Buffer2.alloc(4, 0); + this._cipher = new aes2.AES(key2); + var ck = this._cipher.encryptBlock(h); + this._ghash = new GHASH(ck); + iv = calcIv(this, iv, ck); + this._prev = Buffer2.from(iv); + this._cache = Buffer2.allocUnsafe(0); + this._secCache = Buffer2.allocUnsafe(0); + this._decrypt = decrypt; + this._alen = 0; + this._len = 0; + this._mode = mode; + this._authTag = null; + this._called = false; + } + inherits(StreamCipher, Transform); + StreamCipher.prototype._update = function(chunk) { + if (!this._called && this._alen) { + var rump = 16 - this._alen % 16; + if (rump < 16) { + rump = Buffer2.alloc(rump, 0); + this._ghash.update(rump); + } + } + this._called = true; + var out = this._mode.encrypt(this, chunk); + if (this._decrypt) { + this._ghash.update(chunk); + } else { + this._ghash.update(out); + } + this._len += chunk.length; + return out; + }; + StreamCipher.prototype._final = function() { + if (this._decrypt && !this._authTag) throw new Error("Unsupported state or unable to authenticate data"); + var tag = xor2(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)); + if (this._decrypt && xorTest(tag, this._authTag)) throw new Error("Unsupported state or unable to authenticate data"); + this._authTag = tag; + this._cipher.scrub(); + }; + StreamCipher.prototype.getAuthTag = function getAuthTag() { + if (this._decrypt || !Buffer2.isBuffer(this._authTag)) throw new Error("Attempting to get auth tag in unsupported state"); + return this._authTag; + }; + StreamCipher.prototype.setAuthTag = function setAuthTag(tag) { + if (!this._decrypt) throw new Error("Attempting to set auth tag in unsupported state"); + this._authTag = tag; + }; + StreamCipher.prototype.setAAD = function setAAD(buf) { + if (this._called) throw new Error("Attempting to set AAD in unsupported state"); + this._ghash.update(buf); + this._alen += buf.length; + }; + authCipher = StreamCipher; + return authCipher; +} +var streamCipher; +var hasRequiredStreamCipher; +function requireStreamCipher() { + if (hasRequiredStreamCipher) return streamCipher; + hasRequiredStreamCipher = 1; + var aes2 = requireAes(); + var Buffer2 = requireSafeBuffer().Buffer; + var Transform = requireCipherBase(); + var inherits = requireInherits_browser$1(); + function StreamCipher(mode, key2, iv, decrypt) { + Transform.call(this); + this._cipher = new aes2.AES(key2); + this._prev = Buffer2.from(iv); + this._cache = Buffer2.allocUnsafe(0); + this._secCache = Buffer2.allocUnsafe(0); + this._decrypt = decrypt; + this._mode = mode; + } + inherits(StreamCipher, Transform); + StreamCipher.prototype._update = function(chunk) { + return this._mode.encrypt(this, chunk, this._decrypt); + }; + StreamCipher.prototype._final = function() { + this._cipher.scrub(); + }; + streamCipher = StreamCipher; + return streamCipher; +} +var evp_bytestokey; +var hasRequiredEvp_bytestokey; +function requireEvp_bytestokey() { + if (hasRequiredEvp_bytestokey) return evp_bytestokey; + hasRequiredEvp_bytestokey = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var MD5 = requireMd5_js(); + function EVP_BytesToKey(password, salt, keyBits, ivLen) { + if (!Buffer2.isBuffer(password)) password = Buffer2.from(password, "binary"); + if (salt) { + if (!Buffer2.isBuffer(salt)) salt = Buffer2.from(salt, "binary"); + if (salt.length !== 8) throw new RangeError("salt should be Buffer with 8 byte length"); + } + var keyLen = keyBits / 8; + var key2 = Buffer2.alloc(keyLen); + var iv = Buffer2.alloc(ivLen || 0); + var tmp = Buffer2.alloc(0); + while (keyLen > 0 || ivLen > 0) { + var hash2 = new MD5(); + hash2.update(tmp); + hash2.update(password); + if (salt) hash2.update(salt); + tmp = hash2.digest(); + var used = 0; + if (keyLen > 0) { + var keyStart = key2.length - keyLen; + used = Math.min(keyLen, tmp.length); + tmp.copy(key2, keyStart, 0, used); + keyLen -= used; + } + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen; + var length = Math.min(ivLen, tmp.length - used); + tmp.copy(iv, ivStart, used, used + length); + ivLen -= length; + } + } + tmp.fill(0); + return { key: key2, iv }; + } + evp_bytestokey = EVP_BytesToKey; + return evp_bytestokey; +} +var hasRequiredEncrypter; +function requireEncrypter() { + if (hasRequiredEncrypter) return encrypter; + hasRequiredEncrypter = 1; + var MODES = requireModes$1(); + var AuthCipher = requireAuthCipher(); + var Buffer2 = requireSafeBuffer().Buffer; + var StreamCipher = requireStreamCipher(); + var Transform = requireCipherBase(); + var aes2 = requireAes(); + var ebtk = requireEvp_bytestokey(); + var inherits = requireInherits_browser$1(); + function Cipher(mode, key2, iv) { + Transform.call(this); + this._cache = new Splitter(); + this._cipher = new aes2.AES(key2); + this._prev = Buffer2.from(iv); + this._mode = mode; + this._autopadding = true; + } + inherits(Cipher, Transform); + Cipher.prototype._update = function(data2) { + this._cache.add(data2); + var chunk; + var thing; + var out = []; + while (chunk = this._cache.get()) { + thing = this._mode.encrypt(this, chunk); + out.push(thing); + } + return Buffer2.concat(out); + }; + var PADDING = Buffer2.alloc(16, 16); + Cipher.prototype._final = function() { + var chunk = this._cache.flush(); + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk); + this._cipher.scrub(); + return chunk; + } + if (!chunk.equals(PADDING)) { + this._cipher.scrub(); + throw new Error("data not multiple of block length"); + } + }; + Cipher.prototype.setAutoPadding = function(setTo) { + this._autopadding = !!setTo; + return this; + }; + function Splitter() { + this.cache = Buffer2.allocUnsafe(0); + } + Splitter.prototype.add = function(data2) { + this.cache = Buffer2.concat([this.cache, data2]); + }; + Splitter.prototype.get = function() { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + return out; + } + return null; + }; + Splitter.prototype.flush = function() { + var len = 16 - this.cache.length; + var padBuff = Buffer2.allocUnsafe(len); + var i = -1; + while (++i < len) { + padBuff.writeUInt8(len, i); + } + return Buffer2.concat([this.cache, padBuff]); + }; + function createCipheriv(suite, password, iv) { + var config = MODES[suite.toLowerCase()]; + if (!config) throw new TypeError("invalid suite type"); + if (typeof password === "string") password = Buffer2.from(password); + if (password.length !== config.key / 8) throw new TypeError("invalid key length " + password.length); + if (typeof iv === "string") iv = Buffer2.from(iv); + if (config.mode !== "GCM" && iv.length !== config.iv) throw new TypeError("invalid iv length " + iv.length); + if (config.type === "stream") { + return new StreamCipher(config.module, password, iv); + } else if (config.type === "auth") { + return new AuthCipher(config.module, password, iv); + } + return new Cipher(config.module, password, iv); + } + function createCipher(suite, password) { + var config = MODES[suite.toLowerCase()]; + if (!config) throw new TypeError("invalid suite type"); + var keys = ebtk(password, false, config.key, config.iv); + return createCipheriv(suite, keys.key, keys.iv); + } + encrypter.createCipheriv = createCipheriv; + encrypter.createCipher = createCipher; + return encrypter; +} +var decrypter = {}; +var hasRequiredDecrypter; +function requireDecrypter() { + if (hasRequiredDecrypter) return decrypter; + hasRequiredDecrypter = 1; + var AuthCipher = requireAuthCipher(); + var Buffer2 = requireSafeBuffer().Buffer; + var MODES = requireModes$1(); + var StreamCipher = requireStreamCipher(); + var Transform = requireCipherBase(); + var aes2 = requireAes(); + var ebtk = requireEvp_bytestokey(); + var inherits = requireInherits_browser$1(); + function Decipher(mode, key2, iv) { + Transform.call(this); + this._cache = new Splitter(); + this._last = void 0; + this._cipher = new aes2.AES(key2); + this._prev = Buffer2.from(iv); + this._mode = mode; + this._autopadding = true; + } + inherits(Decipher, Transform); + Decipher.prototype._update = function(data2) { + this._cache.add(data2); + var chunk; + var thing; + var out = []; + while (chunk = this._cache.get(this._autopadding)) { + thing = this._mode.decrypt(this, chunk); + out.push(thing); + } + return Buffer2.concat(out); + }; + Decipher.prototype._final = function() { + var chunk = this._cache.flush(); + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)); + } else if (chunk) { + throw new Error("data not multiple of block length"); + } + }; + Decipher.prototype.setAutoPadding = function(setTo) { + this._autopadding = !!setTo; + return this; + }; + function Splitter() { + this.cache = Buffer2.allocUnsafe(0); + } + Splitter.prototype.add = function(data2) { + this.cache = Buffer2.concat([this.cache, data2]); + }; + Splitter.prototype.get = function(autoPadding) { + var out; + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + return out; + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16); + this.cache = this.cache.slice(16); + return out; + } + } + return null; + }; + Splitter.prototype.flush = function() { + if (this.cache.length) return this.cache; + }; + function unpad(last) { + var padded = last[15]; + if (padded < 1 || padded > 16) { + throw new Error("unable to decrypt data"); + } + var i = -1; + while (++i < padded) { + if (last[i + (16 - padded)] !== padded) { + throw new Error("unable to decrypt data"); + } + } + if (padded === 16) return; + return last.slice(0, 16 - padded); + } + function createDecipheriv(suite, password, iv) { + var config = MODES[suite.toLowerCase()]; + if (!config) throw new TypeError("invalid suite type"); + if (typeof iv === "string") iv = Buffer2.from(iv); + if (config.mode !== "GCM" && iv.length !== config.iv) throw new TypeError("invalid iv length " + iv.length); + if (typeof password === "string") password = Buffer2.from(password); + if (password.length !== config.key / 8) throw new TypeError("invalid key length " + password.length); + if (config.type === "stream") { + return new StreamCipher(config.module, password, iv, true); + } else if (config.type === "auth") { + return new AuthCipher(config.module, password, iv, true); + } + return new Decipher(config.module, password, iv); + } + function createDecipher(suite, password) { + var config = MODES[suite.toLowerCase()]; + if (!config) throw new TypeError("invalid suite type"); + var keys = ebtk(password, false, config.key, config.iv); + return createDecipheriv(suite, keys.key, keys.iv); + } + decrypter.createDecipher = createDecipher; + decrypter.createDecipheriv = createDecipheriv; + return decrypter; +} +var hasRequiredBrowser$9; +function requireBrowser$9() { + if (hasRequiredBrowser$9) return browser$8; + hasRequiredBrowser$9 = 1; + var ciphers = requireEncrypter(); + var deciphers = requireDecrypter(); + var modes2 = require$$2; + function getCiphers() { + return Object.keys(modes2); + } + browser$8.createCipher = browser$8.Cipher = ciphers.createCipher; + browser$8.createCipheriv = browser$8.Cipheriv = ciphers.createCipheriv; + browser$8.createDecipher = browser$8.Decipher = deciphers.createDecipher; + browser$8.createDecipheriv = browser$8.Decipheriv = deciphers.createDecipheriv; + browser$8.listCiphers = browser$8.getCiphers = getCiphers; + return browser$8; +} +var modes = {}; +var hasRequiredModes; +function requireModes() { + if (hasRequiredModes) return modes; + hasRequiredModes = 1; + (function(exports) { + exports["des-ecb"] = { + key: 8, + iv: 0 + }; + exports["des-cbc"] = exports.des = { + key: 8, + iv: 8 + }; + exports["des-ede3-cbc"] = exports.des3 = { + key: 24, + iv: 8 + }; + exports["des-ede3"] = { + key: 24, + iv: 0 + }; + exports["des-ede-cbc"] = { + key: 16, + iv: 8 + }; + exports["des-ede"] = { + key: 16, + iv: 0 + }; + })(modes); + return modes; +} +var hasRequiredBrowser$8; +function requireBrowser$8() { + if (hasRequiredBrowser$8) return browser$9; + hasRequiredBrowser$8 = 1; + var DES = requireBrowserifyDes(); + var aes2 = requireBrowser$9(); + var aesModes = requireModes$1(); + var desModes = requireModes(); + var ebtk = requireEvp_bytestokey(); + function createCipher(suite, password) { + suite = suite.toLowerCase(); + var keyLen, ivLen; + if (aesModes[suite]) { + keyLen = aesModes[suite].key; + ivLen = aesModes[suite].iv; + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8; + ivLen = desModes[suite].iv; + } else { + throw new TypeError("invalid suite type"); + } + var keys = ebtk(password, false, keyLen, ivLen); + return createCipheriv(suite, keys.key, keys.iv); + } + function createDecipher(suite, password) { + suite = suite.toLowerCase(); + var keyLen, ivLen; + if (aesModes[suite]) { + keyLen = aesModes[suite].key; + ivLen = aesModes[suite].iv; + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8; + ivLen = desModes[suite].iv; + } else { + throw new TypeError("invalid suite type"); + } + var keys = ebtk(password, false, keyLen, ivLen); + return createDecipheriv(suite, keys.key, keys.iv); + } + function createCipheriv(suite, key2, iv) { + suite = suite.toLowerCase(); + if (aesModes[suite]) return aes2.createCipheriv(suite, key2, iv); + if (desModes[suite]) return new DES({ key: key2, iv, mode: suite }); + throw new TypeError("invalid suite type"); + } + function createDecipheriv(suite, key2, iv) { + suite = suite.toLowerCase(); + if (aesModes[suite]) return aes2.createDecipheriv(suite, key2, iv); + if (desModes[suite]) return new DES({ key: key2, iv, mode: suite, decrypt: true }); + throw new TypeError("invalid suite type"); + } + function getCiphers() { + return Object.keys(desModes).concat(aes2.getCiphers()); + } + browser$9.createCipher = browser$9.Cipher = createCipher; + browser$9.createCipheriv = browser$9.Cipheriv = createCipheriv; + browser$9.createDecipher = browser$9.Decipher = createDecipher; + browser$9.createDecipheriv = browser$9.Decipheriv = createDecipheriv; + browser$9.listCiphers = browser$9.getCiphers = getCiphers; + return browser$9; +} +var browser$7 = {}; +var bn$d = { exports: {} }; +var bn$c = bn$d.exports; +var hasRequiredBn$6; +function requireBn$6() { + if (hasRequiredBn$6) return bn$d.exports; + hasRequiredBn$6 = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + return c - 48 & 15; + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this.strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + r += c - 49 + 10; + } else if (c >= 17) { + r += c - 17 + 10; + } else { + r += c; + } + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this.strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + BN.prototype.inspect = function inspect() { + return (this.red ? ""; + }; + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16); + }; + BN.prototype.toBuffer = function toBuffer2(endian, length) { + assert2(typeof Buffer2 !== "undefined"); + return this.toArrayLike(Buffer2, endian, length); + }; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + this.strip(); + var littleEndian = endian === "le"; + var res = new ArrayType(reqLength); + var b, i; + var q = this.clone(); + if (!littleEndian) { + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[i] = b; + } + for (; i < reqLength; i++) { + res[i] = 0; + } + } + return res; + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = (num.words[off] & 1 << wbit) >>> wbit; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this.strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this.strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this.strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this.strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this.strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this.strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out.strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out.strip(); + } + function jumboMulTo(self2, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + function FFTM(x, y) { + this.x = x; + this.y = y; + } + FFTM.prototype.makeRBT = function makeRBT(N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + return t; + }; + FFTM.prototype.revBin = function revBin(x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << l - i - 1; + x >>= 1; + } + return rb; + }; + FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + FFTM.prototype.transform = function transform2(rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + for (var j = 0; j < s; j++) { + var re2 = rtws[p + j]; + var ie = itws[p + j]; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + rtws[p + j] = re2 + ro; + itws[p + j] = ie + io; + rtws[p + j + s] = re2 - ro; + itws[p + j + s] = ie - io; + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + FFTM.prototype.guessLen13b = function guessLen13b(n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + return 1 << i + 1 + odd; + }; + FFTM.prototype.conjugate = function conjugate(rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + t = iws[i]; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + FFTM.prototype.normalize13b = function normalize13b(ws2, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws2[2 * i + 1] / N) * 8192 + Math.round(ws2[2 * i] / N) + carry; + ws2[i] = w & 67108863; + if (w < 67108864) { + carry = 0; + } else { + carry = w / 67108864 | 0; + } + } + return ws2; + }; + FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws2[i] | 0); + rws[2 * i] = carry & 8191; + carry = carry >>> 13; + rws[2 * i + 1] = carry & 8191; + carry = carry >>> 13; + } + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + assert2(carry === 0); + assert2((carry & -8192) === 0); + }; + FFTM.prototype.stub = function stub(N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + return ph; + }; + FFTM.prototype.mulp = function mulp(x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + var rbt = this.makeRBT(N); + var _ = this.stub(N); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + var rmws = out.words; + rmws.length = N; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this.strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this.strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this.strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this.strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this.strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this.strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modn = function modn(num) { + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return acc; + }; + BN.prototype.idivn = function idivn(num) { + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + return this.strip(); + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this.strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn$c); + })(bn$d); + return bn$d.exports; +} +var bn$b = { exports: {} }; +var bn$a = bn$b.exports; +var hasRequiredBn$5; +function requireBn$5() { + if (hasRequiredBn$5) return bn$b.exports; + hasRequiredBn$5 = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + return c - 48 & 15; + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this.strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + r += c - 49 + 10; + } else if (c >= 17) { + r += c - 17 + 10; + } else { + r += c; + } + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this.strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + BN.prototype.inspect = function inspect() { + return (this.red ? ""; + }; + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16); + }; + BN.prototype.toBuffer = function toBuffer2(endian, length) { + assert2(typeof Buffer2 !== "undefined"); + return this.toArrayLike(Buffer2, endian, length); + }; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + this.strip(); + var littleEndian = endian === "le"; + var res = new ArrayType(reqLength); + var b, i; + var q = this.clone(); + if (!littleEndian) { + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[i] = b; + } + for (; i < reqLength; i++) { + res[i] = 0; + } + } + return res; + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = (num.words[off] & 1 << wbit) >>> wbit; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this.strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this.strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this.strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this.strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this.strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this.strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out.strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out.strip(); + } + function jumboMulTo(self2, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + function FFTM(x, y) { + this.x = x; + this.y = y; + } + FFTM.prototype.makeRBT = function makeRBT(N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + return t; + }; + FFTM.prototype.revBin = function revBin(x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << l - i - 1; + x >>= 1; + } + return rb; + }; + FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + FFTM.prototype.transform = function transform2(rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + for (var j = 0; j < s; j++) { + var re2 = rtws[p + j]; + var ie = itws[p + j]; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + rtws[p + j] = re2 + ro; + itws[p + j] = ie + io; + rtws[p + j + s] = re2 - ro; + itws[p + j + s] = ie - io; + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + FFTM.prototype.guessLen13b = function guessLen13b(n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + return 1 << i + 1 + odd; + }; + FFTM.prototype.conjugate = function conjugate(rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + t = iws[i]; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + FFTM.prototype.normalize13b = function normalize13b(ws2, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws2[2 * i + 1] / N) * 8192 + Math.round(ws2[2 * i] / N) + carry; + ws2[i] = w & 67108863; + if (w < 67108864) { + carry = 0; + } else { + carry = w / 67108864 | 0; + } + } + return ws2; + }; + FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws2[i] | 0); + rws[2 * i] = carry & 8191; + carry = carry >>> 13; + rws[2 * i + 1] = carry & 8191; + carry = carry >>> 13; + } + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + assert2(carry === 0); + assert2((carry & -8192) === 0); + }; + FFTM.prototype.stub = function stub(N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + return ph; + }; + FFTM.prototype.mulp = function mulp(x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + var rbt = this.makeRBT(N); + var _ = this.stub(N); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + var rmws = out.words; + rmws.length = N; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this.strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this.strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this.strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this.strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this.strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this.strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modn = function modn(num) { + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return acc; + }; + BN.prototype.idivn = function idivn(num) { + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + return this.strip(); + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this.strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn$a); + })(bn$b); + return bn$b.exports; +} +var brorand = { exports: {} }; +var hasRequiredBrorand; +function requireBrorand() { + if (hasRequiredBrorand) return brorand.exports; + hasRequiredBrorand = 1; + var r; + brorand.exports = function rand(len) { + if (!r) + r = new Rand(null); + return r.generate(len); + }; + function Rand(rand) { + this.rand = rand; + } + brorand.exports.Rand = Rand; + Rand.prototype.generate = function generate(len) { + return this._rand(len); + }; + Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; + if (typeof self === "object") { + if (self.crypto && self.crypto.getRandomValues) { + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + } else if (typeof window === "object") { + Rand.prototype._rand = function() { + throw new Error("Not implemented yet"); + }; + } + } else { + try { + var crypto2 = requireCryptoBrowserify(); + if (typeof crypto2.randomBytes !== "function") + throw new Error("Not supported"); + Rand.prototype._rand = function _rand(n) { + return crypto2.randomBytes(n); + }; + } catch (e) { + } + } + return brorand.exports; +} +var mr; +var hasRequiredMr; +function requireMr() { + if (hasRequiredMr) return mr; + hasRequiredMr = 1; + var bn2 = requireBn$5(); + var brorand2 = requireBrorand(); + function MillerRabin(rand) { + this.rand = rand || new brorand2.Rand(); + } + mr = MillerRabin; + MillerRabin.create = function create(rand) { + return new MillerRabin(rand); + }; + MillerRabin.prototype._randbelow = function _randbelow(n) { + var len = n.bitLength(); + var min_bytes = Math.ceil(len / 8); + do + var a = new bn2(this.rand.generate(min_bytes)); + while (a.cmp(n) >= 0); + return a; + }; + MillerRabin.prototype._randrange = function _randrange(start, stop) { + var size = stop.sub(start); + return start.add(this._randbelow(size)); + }; + MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn2.mont(n); + var rone = new bn2(1).toRed(red); + if (!k) + k = Math.max(1, len / 48 | 0); + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) { + } + var d = n.shrn(s); + var rn1 = n1.toRed(red); + var prime = true; + for (; k > 0; k--) { + var a = this._randrange(new bn2(2), n1); + if (cb) + cb(a); + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + for (var i = 1; i < s; i++) { + x = x.redSqr(); + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + if (i === s) + return false; + } + return prime; + }; + MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn2.mont(n); + var rone = new bn2(1).toRed(red); + if (!k) + k = Math.max(1, len / 48 | 0); + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) { + } + var d = n.shrn(s); + var rn1 = n1.toRed(red); + for (; k > 0; k--) { + var a = this._randrange(new bn2(2), n1); + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + for (var i = 1; i < s; i++) { + x = x.redSqr(); + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + return false; + }; + return mr; +} +var generatePrime; +var hasRequiredGeneratePrime; +function requireGeneratePrime() { + if (hasRequiredGeneratePrime) return generatePrime; + hasRequiredGeneratePrime = 1; + var randomBytes = requireBrowser$e(); + generatePrime = findPrime; + findPrime.simpleSieve = simpleSieve; + findPrime.fermatTest = fermatTest; + var BN = requireBn$6(); + var TWENTYFOUR = new BN(24); + var MillerRabin = requireMr(); + var millerRabin = new MillerRabin(); + var ONE = new BN(1); + var TWO = new BN(2); + var FIVE = new BN(5); + new BN(16); + new BN(8); + var TEN = new BN(10); + var THREE = new BN(3); + new BN(7); + var ELEVEN = new BN(11); + var FOUR = new BN(4); + new BN(12); + var primes = null; + function _getPrimes() { + if (primes !== null) + return primes; + var limit = 1048576; + var res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + for (var j = 0; j < i && res[j] <= sqrt; j++) + if (k % res[j] === 0) + break; + if (i !== j && res[j] <= sqrt) + continue; + res[i++] = k; + } + primes = res; + return res; + } + function simpleSieve(p) { + var primes2 = _getPrimes(); + for (var i = 0; i < primes2.length; i++) + if (p.modn(primes2[i]) === 0) { + if (p.cmpn(primes2[i]) === 0) { + return true; + } else { + return false; + } + } + return true; + } + function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; + } + function findPrime(bits, gen) { + if (bits < 16) { + if (gen === 2 || gen === 5) { + return new BN([140, 123]); + } else { + return new BN([140, 39]); + } + } + gen = new BN(gen); + var num, n2; + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && fermatTest(n2) && fermatTest(num) && millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + } + return generatePrime; +} +const modp1 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" }; +const modp2 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" }; +const modp5 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" }; +const modp14 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" }; +const modp15 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" }; +const modp16 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" }; +const modp17 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" }; +const modp18 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" }; +const require$$1$4 = { + modp1, + modp2, + modp5, + modp14, + modp15, + modp16, + modp17, + modp18 +}; +var dh; +var hasRequiredDh; +function requireDh() { + if (hasRequiredDh) return dh; + hasRequiredDh = 1; + var BN = requireBn$6(); + var MillerRabin = requireMr(); + var millerRabin = new MillerRabin(); + var TWENTYFOUR = new BN(24); + var ELEVEN = new BN(11); + var TEN = new BN(10); + var THREE = new BN(3); + var SEVEN = new BN(7); + var primes = requireGeneratePrime(); + var randomBytes = requireBrowser$e(); + dh = DH; + function setPublicKey(pub, enc) { + enc = enc || "utf8"; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; + } + function setPrivateKey(priv, enc) { + enc = enc || "utf8"; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; + } + var primeCache = {}; + function checkPrime(prime, generator) { + var gen = generator.toString("hex"); + var hex = [gen, prime.toString(16)].join("_"); + if (hex in primeCache) { + return primeCache[hex]; + } + var error2 = 0; + if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) { + error2 += 1; + if (gen === "02" || gen === "05") { + error2 += 8; + } else { + error2 += 4; + } + primeCache[hex] = error2; + return error2; + } + if (!millerRabin.test(prime.shrn(1))) { + error2 += 2; + } + var rem; + switch (gen) { + case "02": + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + error2 += 8; + } + break; + case "05": + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + error2 += 8; + } + break; + default: + error2 += 4; + } + primeCache[hex] = error2; + return error2; + } + function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = void 0; + this._priv = void 0; + this._primeCode = void 0; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } + } + Object.defineProperty(DH.prototype, "verifyError", { + enumerable: true, + get: function() { + if (typeof this._primeCode !== "number") { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } + }); + DH.prototype.generateKeys = function() { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); + return this.getPublicKey(); + }; + DH.prototype.computeSecret = function(other2) { + other2 = new BN(other2); + other2 = other2.toRed(this._prime); + var secret = other2.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + return out; + }; + DH.prototype.getPublicKey = function getPublicKey(enc) { + return formatReturnValue(this._pub, enc); + }; + DH.prototype.getPrivateKey = function getPrivateKey(enc) { + return formatReturnValue(this._priv, enc); + }; + DH.prototype.getPrime = function(enc) { + return formatReturnValue(this.__prime, enc); + }; + DH.prototype.getGenerator = function(enc) { + return formatReturnValue(this._gen, enc); + }; + DH.prototype.setGenerator = function(gen, enc) { + enc = enc || "utf8"; + if (!Buffer.isBuffer(gen)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; + }; + function formatReturnValue(bn2, enc) { + var buf = new Buffer(bn2.toArray()); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } + } + return dh; +} +var hasRequiredBrowser$7; +function requireBrowser$7() { + if (hasRequiredBrowser$7) return browser$7; + hasRequiredBrowser$7 = 1; + var generatePrime2 = requireGeneratePrime(); + var primes = require$$1$4; + var DH = requireDh(); + function getDiffieHellman(mod) { + var prime = new Buffer(primes[mod].prime, "hex"); + var gen = new Buffer(primes[mod].gen, "hex"); + return new DH(prime, gen); + } + var ENCODINGS = { + "binary": true, + "hex": true, + "base64": true + }; + function createDiffieHellman(prime, enc, generator, genc) { + if (Buffer.isBuffer(enc) || ENCODINGS[enc] === void 0) { + return createDiffieHellman(prime, "binary", enc, generator); + } + enc = enc || "binary"; + genc = genc || "binary"; + generator = generator || new Buffer([2]); + if (!Buffer.isBuffer(generator)) { + generator = new Buffer(generator, genc); + } + if (typeof prime === "number") { + return new DH(generatePrime2(prime, generator), generator, true); + } + if (!Buffer.isBuffer(prime)) { + prime = new Buffer(prime, enc); + } + return new DH(prime, generator, true); + } + browser$7.DiffieHellmanGroup = browser$7.createDiffieHellmanGroup = browser$7.getDiffieHellman = getDiffieHellman; + browser$7.createDiffieHellman = browser$7.DiffieHellman = createDiffieHellman; + return browser$7; +} +var readableBrowser$1 = { exports: {} }; +var streamBrowser$1; +var hasRequiredStreamBrowser$1; +function requireStreamBrowser$1() { + if (hasRequiredStreamBrowser$1) return streamBrowser$1; + hasRequiredStreamBrowser$1 = 1; + streamBrowser$1 = requireEvents().EventEmitter; + return streamBrowser$1; +} +var buffer_list$1; +var hasRequiredBuffer_list$1; +function requireBuffer_list$1() { + if (hasRequiredBuffer_list$1) return buffer_list$1; + hasRequiredBuffer_list$1 = 1; + function ownKeys2(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source2 = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys2(Object(source2), true).forEach(function(key2) { + _defineProperty2(target, key2, source2[key2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2)) : ownKeys2(Object(source2)).forEach(function(key2) { + Object.defineProperty(target, key2, Object.getOwnPropertyDescriptor(source2, key2)); + }); + } + return target; + } + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey2(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return typeof key2 === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return String(input); + } + var _require = requireBuffer$2(), Buffer2 = _require.Buffer; + var _require2 = require$$3, inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src2, target, offset2) { + Buffer2.prototype.copy.call(src2, target, offset2); + } + buffer_list$1 = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join2(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer2.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options2) { + return inspect(this, _objectSpread(_objectSpread({}, options2), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + return buffer_list$1; +} +var destroy_1$1; +var hasRequiredDestroy$1; +function requireDestroy$1() { + if (hasRequiredDestroy$1) return destroy_1$1; + hasRequiredDestroy$1 = 1; + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err2); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) return; + if (self2._readableState && !self2._readableState.emitClose) return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream2, err) { + var rState = stream2._readableState; + var wState = stream2._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream2.destroy(err); + else stream2.emit("error", err); + } + destroy_1$1 = { + destroy, + undestroy, + errorOrDestroy + }; + return destroy_1$1; +} +var errorsBrowser$1 = {}; +var hasRequiredErrorsBrowser$1; +function requireErrorsBrowser$1() { + if (hasRequiredErrorsBrowser$1) return errorsBrowser$1; + hasRequiredErrorsBrowser$1 = 1; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; + } + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /* @__PURE__ */ function(_Base) { + _inheritsLoose(NodeError2, _Base); + function NodeError2(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + return NodeError2; + }(Base); + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function(i) { + return String(i); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } + function startsWith(str, search, pos) { + return str.substr(0, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + var determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + var msg; + if (endsWith(name, " argument")) { + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } else { + var type2 = includes(name, ".") ? "property" : "argument"; + msg = 'The "'.concat(name, '" ').concat(type2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { + return "The " + name + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name) { + return "Cannot call " + name + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + errorsBrowser$1.codes = codes; + return errorsBrowser$1; +} +var state$1; +var hasRequiredState$1; +function requireState$1() { + if (hasRequiredState$1) return state$1; + hasRequiredState$1 = 1; + var ERR_INVALID_OPT_VALUE = requireErrorsBrowser$1().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options2, isDuplex, duplexKey) { + return options2.highWaterMark != null ? options2.highWaterMark : isDuplex ? options2[duplexKey] : null; + } + function getHighWaterMark(state2, options2, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options2, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + return state2.objectMode ? 16 : 16 * 1024; + } + state$1 = { + getHighWaterMark + }; + return state$1; +} +var _stream_writable$1; +var hasRequired_stream_writable$1; +function require_stream_writable$1() { + if (hasRequired_stream_writable$1) return _stream_writable$1; + hasRequired_stream_writable$1 = 1; + _stream_writable$1 = Writable; + function CorkedRequest(state2) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state2); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: requireBrowser$d() + }; + var Stream2 = requireStreamBrowser$1(); + var Buffer2 = requireBuffer$2().Buffer; + var OurUint8Array = (typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = requireDestroy$1(); + var _require = requireState$1(), getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrorsBrowser$1().codes, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + requireInherits_browser$1()(Writable, Stream2); + function nop() { + } + function WritableState(options2, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex$1(); + options2 = options2 || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof Duplex; + this.objectMode = !!options2.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options2.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options2, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options2.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options2.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream2, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options2.emitClose !== false; + this.autoDestroy = !!options2.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current2 = this.bufferedRequest; + var out = []; + while (current2) { + out.push(current2); + current2 = current2.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable(options2) { + Duplex = Duplex || require_stream_duplex$1(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options2); + this._writableState = new WritableState(options2, this, isDuplex); + this.writable = true; + if (options2) { + if (typeof options2.write === "function") this._write = options2.write; + if (typeof options2.writev === "function") this._writev = options2.writev; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + if (typeof options2.final === "function") this._final = options2.final; + } + Stream2.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream2, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + } + function validChunk(stream2, state2, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding2, cb) { + var state2 = this._writableState; + var ret = false; + var isBuf = !state2.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + if (isBuf) encoding2 = "buffer"; + else if (!encoding2) encoding2 = state2.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state2.ending) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state2, chunk, cb)) { + state2.pendingcb++; + ret = writeOrBuffer(this, state2, isBuf, chunk, encoding2, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state2 = this._writableState; + if (state2.corked) { + state2.corked--; + if (!state2.writing && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) clearBuffer(this, state2); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding2) { + if (typeof encoding2 === "string") encoding2 = encoding2.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding2 + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding2); + this._writableState.defaultEncoding = encoding2; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state2, chunk, encoding2) { + if (!state2.objectMode && state2.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding2); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream2, state2, isBuf, chunk, encoding2, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state2, chunk, encoding2); + if (chunk !== newChunk) { + isBuf = true; + encoding2 = "buffer"; + chunk = newChunk; + } + } + var len = state2.objectMode ? 1 : chunk.length; + state2.length += len; + var ret = state2.length < state2.highWaterMark; + if (!ret) state2.needDrain = true; + if (state2.writing || state2.corked) { + var last = state2.lastBufferedRequest; + state2.lastBufferedRequest = { + chunk, + encoding: encoding2, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state2.lastBufferedRequest; + } else { + state2.bufferedRequest = state2.lastBufferedRequest; + } + state2.bufferedRequestCount += 1; + } else { + doWrite(stream2, state2, false, len, chunk, encoding2, cb); + } + return ret; + } + function doWrite(stream2, state2, writev2, len, chunk, encoding2, cb) { + state2.writelen = len; + state2.writecb = cb; + state2.writing = true; + state2.sync = true; + if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev2) stream2._writev(chunk, state2.onwrite); + else stream2._write(chunk, encoding2, state2.onwrite); + state2.sync = false; + } + function onwriteError(stream2, state2, sync, er, cb) { + --state2.pendingcb; + if (sync) { + process.nextTick(cb, er); + process.nextTick(finishMaybe, stream2, state2); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + } else { + cb(er); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + finishMaybe(stream2, state2); + } + } + function onwriteStateUpdate(state2) { + state2.writing = false; + state2.writecb = null; + state2.length -= state2.writelen; + state2.writelen = 0; + } + function onwrite(stream2, er) { + var state2 = stream2._writableState; + var sync = state2.sync; + var cb = state2.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state2); + if (er) onwriteError(stream2, state2, sync, er, cb); + else { + var finished = needFinish(state2) || stream2.destroyed; + if (!finished && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) { + clearBuffer(stream2, state2); + } + if (sync) { + process.nextTick(afterWrite, stream2, state2, finished, cb); + } else { + afterWrite(stream2, state2, finished, cb); + } + } + } + function afterWrite(stream2, state2, finished, cb) { + if (!finished) onwriteDrain(stream2, state2); + state2.pendingcb--; + cb(); + finishMaybe(stream2, state2); + } + function onwriteDrain(stream2, state2) { + if (state2.length === 0 && state2.needDrain) { + state2.needDrain = false; + stream2.emit("drain"); + } + } + function clearBuffer(stream2, state2) { + state2.bufferProcessing = true; + var entry = state2.bufferedRequest; + if (stream2._writev && entry && entry.next) { + var l = state2.bufferedRequestCount; + var buffer2 = new Array(l); + var holder = state2.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer2[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer2.allBuffers = allBuffers; + doWrite(stream2, state2, true, state2.length, buffer2, "", holder.finish); + state2.pendingcb++; + state2.lastBufferedRequest = null; + if (holder.next) { + state2.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state2.corkedRequestsFree = new CorkedRequest(state2); + } + state2.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding2 = entry.encoding; + var cb = entry.callback; + var len = state2.objectMode ? 1 : chunk.length; + doWrite(stream2, state2, false, len, chunk, encoding2, cb); + entry = entry.next; + state2.bufferedRequestCount--; + if (state2.writing) { + break; + } + } + if (entry === null) state2.lastBufferedRequest = null; + } + state2.bufferedRequest = entry; + state2.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding2, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding2, cb) { + var state2 = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding2 = null; + } else if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding2); + if (state2.corked) { + state2.corked = 1; + this.uncork(); + } + if (!state2.ending) endWritable(this, state2, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function needFinish(state2) { + return state2.ending && state2.length === 0 && state2.bufferedRequest === null && !state2.finished && !state2.writing; + } + function callFinal(stream2, state2) { + stream2._final(function(err) { + state2.pendingcb--; + if (err) { + errorOrDestroy(stream2, err); + } + state2.prefinished = true; + stream2.emit("prefinish"); + finishMaybe(stream2, state2); + }); + } + function prefinish(stream2, state2) { + if (!state2.prefinished && !state2.finalCalled) { + if (typeof stream2._final === "function" && !state2.destroyed) { + state2.pendingcb++; + state2.finalCalled = true; + process.nextTick(callFinal, stream2, state2); + } else { + state2.prefinished = true; + stream2.emit("prefinish"); + } + } + } + function finishMaybe(stream2, state2) { + var need = needFinish(state2); + if (need) { + prefinish(stream2, state2); + if (state2.pendingcb === 0) { + state2.finished = true; + stream2.emit("finish"); + if (state2.autoDestroy) { + var rState = stream2._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream2.destroy(); + } + } + } + } + return need; + } + function endWritable(stream2, state2, cb) { + state2.ending = true; + finishMaybe(stream2, state2); + if (cb) { + if (state2.finished) process.nextTick(cb); + else stream2.once("finish", cb); + } + state2.ended = true; + stream2.writable = false; + } + function onCorkedFinish(corkReq, state2, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state2.pendingcb--; + cb(err); + entry = entry.next; + } + state2.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set2(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + return _stream_writable$1; +} +var _stream_duplex$1; +var hasRequired_stream_duplex$1; +function require_stream_duplex$1() { + if (hasRequired_stream_duplex$1) return _stream_duplex$1; + hasRequired_stream_duplex$1 = 1; + var objectKeys2 = Object.keys || function(obj) { + var keys2 = []; + for (var key2 in obj) keys2.push(key2); + return keys2; + }; + _stream_duplex$1 = Duplex; + var Readable = require_stream_readable$1(); + var Writable = require_stream_writable$1(); + requireInherits_browser$1()(Duplex, Readable); + { + var keys = objectKeys2(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options2) { + if (!(this instanceof Duplex)) return new Duplex(options2); + Readable.call(this, options2); + Writable.call(this, options2); + this.allowHalfOpen = true; + if (options2) { + if (options2.readable === false) this.readable = false; + if (options2.writable === false) this.writable = false; + if (options2.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) return; + process.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set2(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + return _stream_duplex$1; +} +var endOfStream$2; +var hasRequiredEndOfStream$2; +function requireEndOfStream$2() { + if (hasRequiredEndOfStream$2) return endOfStream$2; + hasRequiredEndOfStream$2 = 1; + var ERR_STREAM_PREMATURE_CLOSE = requireErrorsBrowser$1().codes.ERR_STREAM_PREMATURE_CLOSE; + function once2(callback) { + var called = false; + return function() { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop2() { + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function eos(stream2, opts, callback) { + if (typeof opts === "function") return eos(stream2, null, opts); + if (!opts) opts = {}; + callback = once2(callback || noop2); + var readable2 = opts.readable || opts.readable !== false && stream2.readable; + var writable2 = opts.writable || opts.writable !== false && stream2.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream2.writable) onfinish(); + }; + var writableEnded = stream2._writableState && stream2._writableState.finished; + var onfinish = function onfinish2() { + writable2 = false; + writableEnded = true; + if (!readable2) callback.call(stream2); + }; + var readableEnded = stream2._readableState && stream2._readableState.endEmitted; + var onend = function onend2() { + readable2 = false; + readableEnded = true; + if (!writable2) callback.call(stream2); + }; + var onerror = function onerror2(err) { + callback.call(stream2, err); + }; + var onclose = function onclose2() { + var err; + if (readable2 && !readableEnded) { + if (!stream2._readableState || !stream2._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + if (writable2 && !writableEnded) { + if (!stream2._writableState || !stream2._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + }; + var onrequest = function onrequest2() { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + stream2.on("abort", onclose); + if (stream2.req) onrequest(); + else stream2.on("request", onrequest); + } else if (writable2 && !stream2._writableState) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (opts.error !== false) stream2.on("error", onerror); + stream2.on("close", onclose); + return function() { + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.removeListener("close", onclose); + }; + } + endOfStream$2 = eos; + return endOfStream$2; +} +var async_iterator$1; +var hasRequiredAsync_iterator$1; +function requireAsync_iterator$1() { + if (hasRequiredAsync_iterator$1) return async_iterator$1; + hasRequiredAsync_iterator$1 = 1; + var _Object$setPrototypeO; + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return typeof key2 === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = requireEndOfStream$2(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data2 = iter[kStream].read(); + if (data2 !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data2, false)); + } + } + } + function onReadable(iter) { + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error2 = this[kError]; + if (error2 !== null) { + return Promise.reject(error2); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + process.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data2 = this[kStream].read(); + if (data2 !== null) { + return Promise.resolve(createIterResult(data2, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty2(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty2(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream2) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty2(_Object$create, kStream, { + value: stream2, + writable: true + }), _defineProperty2(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kEnded, { + value: stream2._readableState.endEmitted, + writable: true + }), _defineProperty2(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data2 = iterator[kStream].read(); + if (data2) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data2, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream2, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator[kLastReject]; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(void 0, true)); + } + iterator[kEnded] = true; + }); + stream2.on("readable", onReadable.bind(null, iterator)); + return iterator; + }; + async_iterator$1 = createReadableStreamAsyncIterator; + return async_iterator$1; +} +var fromBrowser$1; +var hasRequiredFromBrowser$1; +function requireFromBrowser$1() { + if (hasRequiredFromBrowser$1) return fromBrowser$1; + hasRequiredFromBrowser$1 = 1; + fromBrowser$1 = function() { + throw new Error("Readable.from is not available in the browser"); + }; + return fromBrowser$1; +} +var _stream_readable$1; +var hasRequired_stream_readable$1; +function require_stream_readable$1() { + if (hasRequired_stream_readable$1) return _stream_readable$1; + hasRequired_stream_readable$1 = 1; + _stream_readable$1 = Readable; + var Duplex; + Readable.ReadableState = ReadableState; + requireEvents().EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type2) { + return emitter.listeners(type2).length; + }; + var Stream2 = requireStreamBrowser$1(); + var Buffer2 = requireBuffer$2().Buffer; + var OurUint8Array = (typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = require$$3; + var debug2; + if (debugUtil && debugUtil.debuglog) { + debug2 = debugUtil.debuglog("stream"); + } else { + debug2 = function debug3() { + }; + } + var BufferList = requireBuffer_list$1(); + var destroyImpl = requireDestroy$1(); + var _require = requireState$1(), getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrorsBrowser$1().codes, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from2; + requireInherits_browser$1()(Readable, Stream2); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options2, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex$1(); + options2 = options2 || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof Duplex; + this.objectMode = !!options2.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options2.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options2, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options2.emitClose !== false; + this.autoDestroy = !!options2.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options2.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options2.encoding) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + this.decoder = new StringDecoder(options2.encoding); + this.encoding = options2.encoding; + } + } + function Readable(options2) { + Duplex = Duplex || require_stream_duplex$1(); + if (!(this instanceof Readable)) return new Readable(options2); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options2, this, isDuplex); + this.readable = true; + if (options2) { + if (typeof options2.read === "function") this._read = options2.read; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + } + Stream2.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set2(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype.push = function(chunk, encoding2) { + var state2 = this._readableState; + var skipChunkCheck; + if (!state2.objectMode) { + if (typeof chunk === "string") { + encoding2 = encoding2 || state2.defaultEncoding; + if (encoding2 !== state2.encoding) { + chunk = Buffer2.from(chunk, encoding2); + encoding2 = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding2, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream2, chunk, encoding2, addToFront, skipChunkCheck) { + debug2("readableAddChunk", chunk); + var state2 = stream2._readableState; + if (chunk === null) { + state2.reading = false; + onEofChunk(stream2, state2); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state2, chunk); + if (er) { + errorOrDestroy(stream2, er); + } else if (state2.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state2.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state2.endEmitted) errorOrDestroy(stream2, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream2, state2, chunk, true); + } else if (state2.ended) { + errorOrDestroy(stream2, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state2.destroyed) { + return false; + } else { + state2.reading = false; + if (state2.decoder && !encoding2) { + chunk = state2.decoder.write(chunk); + if (state2.objectMode || chunk.length !== 0) addChunk(stream2, state2, chunk, false); + else maybeReadMore(stream2, state2); + } else { + addChunk(stream2, state2, chunk, false); + } + } + } else if (!addToFront) { + state2.reading = false; + maybeReadMore(stream2, state2); + } + } + return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0); + } + function addChunk(stream2, state2, chunk, addToFront) { + if (state2.flowing && state2.length === 0 && !state2.sync) { + state2.awaitDrain = 0; + stream2.emit("data", chunk); + } else { + state2.length += state2.objectMode ? 1 : chunk.length; + if (addToFront) state2.buffer.unshift(chunk); + else state2.buffer.push(chunk); + if (state2.needReadable) emitReadable(stream2); + } + maybeReadMore(stream2, state2); + } + function chunkInvalid(state2, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + var decoder2 = new StringDecoder(enc); + this._readableState.decoder = decoder2; + this._readableState.encoding = this._readableState.decoder.encoding; + var p = this._readableState.buffer.head; + var content = ""; + while (p !== null) { + content += decoder2.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== "") this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state2) { + if (n <= 0 || state2.length === 0 && state2.ended) return 0; + if (state2.objectMode) return 1; + if (n !== n) { + if (state2.flowing && state2.length) return state2.buffer.head.data.length; + else return state2.length; + } + if (n > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n); + if (n <= state2.length) return n; + if (!state2.ended) { + state2.needReadable = true; + return 0; + } + return state2.length; + } + Readable.prototype.read = function(n) { + debug2("read", n); + n = parseInt(n, 10); + var state2 = this._readableState; + var nOrig = n; + if (n !== 0) state2.emittedReadable = false; + if (n === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) { + debug2("read: emitReadable", state2.length, state2.ended); + if (state2.length === 0 && state2.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state2); + if (n === 0 && state2.ended) { + if (state2.length === 0) endReadable(this); + return null; + } + var doRead = state2.needReadable; + debug2("need readable", doRead); + if (state2.length === 0 || state2.length - n < state2.highWaterMark) { + doRead = true; + debug2("length less than watermark", doRead); + } + if (state2.ended || state2.reading) { + doRead = false; + debug2("reading or ended", doRead); + } else if (doRead) { + debug2("do read"); + state2.reading = true; + state2.sync = true; + if (state2.length === 0) state2.needReadable = true; + this._read(state2.highWaterMark); + state2.sync = false; + if (!state2.reading) n = howMuchToRead(nOrig, state2); + } + var ret; + if (n > 0) ret = fromList(n, state2); + else ret = null; + if (ret === null) { + state2.needReadable = state2.length <= state2.highWaterMark; + n = 0; + } else { + state2.length -= n; + state2.awaitDrain = 0; + } + if (state2.length === 0) { + if (!state2.ended) state2.needReadable = true; + if (nOrig !== n && state2.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream2, state2) { + debug2("onEofChunk"); + if (state2.ended) return; + if (state2.decoder) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) { + state2.buffer.push(chunk); + state2.length += state2.objectMode ? 1 : chunk.length; + } + } + state2.ended = true; + if (state2.sync) { + emitReadable(stream2); + } else { + state2.needReadable = false; + if (!state2.emittedReadable) { + state2.emittedReadable = true; + emitReadable_(stream2); + } + } + } + function emitReadable(stream2) { + var state2 = stream2._readableState; + debug2("emitReadable", state2.needReadable, state2.emittedReadable); + state2.needReadable = false; + if (!state2.emittedReadable) { + debug2("emitReadable", state2.flowing); + state2.emittedReadable = true; + process.nextTick(emitReadable_, stream2); + } + } + function emitReadable_(stream2) { + var state2 = stream2._readableState; + debug2("emitReadable_", state2.destroyed, state2.length, state2.ended); + if (!state2.destroyed && (state2.length || state2.ended)) { + stream2.emit("readable"); + state2.emittedReadable = false; + } + state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark; + flow(stream2); + } + function maybeReadMore(stream2, state2) { + if (!state2.readingMore) { + state2.readingMore = true; + process.nextTick(maybeReadMore_, stream2, state2); + } + } + function maybeReadMore_(stream2, state2) { + while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) { + var len = state2.length; + debug2("maybeReadMore read 0"); + stream2.read(0); + if (len === state2.length) + break; + } + state2.readingMore = false; + } + Readable.prototype._read = function(n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src2 = this; + var state2 = this._readableState; + switch (state2.pipesCount) { + case 0: + state2.pipes = dest; + break; + case 1: + state2.pipes = [state2.pipes, dest]; + break; + default: + state2.pipes.push(dest); + break; + } + state2.pipesCount += 1; + debug2("pipe count=%d opts=%j", state2.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state2.endEmitted) process.nextTick(endFn); + else src2.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable2, unpipeInfo) { + debug2("onunpipe"); + if (readable2 === src2) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug2("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src2); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug2("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src2.removeListener("end", onend); + src2.removeListener("end", unpipe); + src2.removeListener("data", ondata); + cleanedUp = true; + if (state2.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src2.on("data", ondata); + function ondata(chunk) { + debug2("ondata"); + var ret = dest.write(chunk); + debug2("dest.write", ret); + if (ret === false) { + if ((state2.pipesCount === 1 && state2.pipes === dest || state2.pipesCount > 1 && indexOf(state2.pipes, dest) !== -1) && !cleanedUp) { + debug2("false write response, pause", state2.awaitDrain); + state2.awaitDrain++; + } + src2.pause(); + } + } + function onerror(er) { + debug2("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug2("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug2("unpipe"); + src2.unpipe(dest); + } + dest.emit("pipe", src2); + if (!state2.flowing) { + debug2("pipe resume"); + src2.resume(); + } + return dest; + }; + function pipeOnDrain(src2) { + return function pipeOnDrainFunctionResult() { + var state2 = src2._readableState; + debug2("pipeOnDrain", state2.awaitDrain); + if (state2.awaitDrain) state2.awaitDrain--; + if (state2.awaitDrain === 0 && EElistenerCount(src2, "data")) { + state2.flowing = true; + flow(src2); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state2 = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state2.pipesCount === 0) return this; + if (state2.pipesCount === 1) { + if (dest && dest !== state2.pipes) return this; + if (!dest) dest = state2.pipes; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state2.pipes; + var len = state2.pipesCount; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index2 = indexOf(state2.pipes, dest); + if (index2 === -1) return this; + state2.pipes.splice(index2, 1); + state2.pipesCount -= 1; + if (state2.pipesCount === 1) state2.pipes = state2.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream2.prototype.on.call(this, ev, fn); + var state2 = this._readableState; + if (ev === "data") { + state2.readableListening = this.listenerCount("readable") > 0; + if (state2.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state2.endEmitted && !state2.readableListening) { + state2.readableListening = state2.needReadable = true; + state2.flowing = false; + state2.emittedReadable = false; + debug2("on readable", state2.length, state2.reading); + if (state2.length) { + emitReadable(this); + } else if (!state2.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + var res = Stream2.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + process.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.removeAllListeners = function(ev) { + var res = Stream2.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state2 = self2._readableState; + state2.readableListening = self2.listenerCount("readable") > 0; + if (state2.resumeScheduled && !state2.paused) { + state2.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug2("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + var state2 = this._readableState; + if (!state2.flowing) { + debug2("resume"); + state2.flowing = !state2.readableListening; + resume(this, state2); + } + state2.paused = false; + return this; + }; + function resume(stream2, state2) { + if (!state2.resumeScheduled) { + state2.resumeScheduled = true; + process.nextTick(resume_, stream2, state2); + } + } + function resume_(stream2, state2) { + debug2("resume", state2.reading); + if (!state2.reading) { + stream2.read(0); + } + state2.resumeScheduled = false; + stream2.emit("resume"); + flow(stream2); + if (state2.flowing && !state2.reading) stream2.read(0); + } + Readable.prototype.pause = function() { + debug2("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug2("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream2) { + var state2 = stream2._readableState; + debug2("flow", state2.flowing); + while (state2.flowing && stream2.read() !== null) ; + } + Readable.prototype.wrap = function(stream2) { + var _this = this; + var state2 = this._readableState; + var paused = false; + stream2.on("end", function() { + debug2("wrapped end"); + if (state2.decoder && !state2.ended) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream2.on("data", function(chunk) { + debug2("wrapped data"); + if (state2.decoder) chunk = state2.decoder.write(chunk); + if (state2.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state2.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream2.pause(); + } + }); + for (var i in stream2) { + if (this[i] === void 0 && typeof stream2[i] === "function") { + this[i] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream2[method].apply(stream2, arguments); + }; + }(i); + } + } + for (var n = 0; n < kProxyEvents.length; n++) { + stream2.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + this._read = function(n2) { + debug2("wrapped _read", n2); + if (paused) { + paused = false; + stream2.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = requireAsync_iterator$1(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.flowing; + }, + set: function set2(state2) { + if (this._readableState) { + this._readableState.flowing = state2; + } + } + }); + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.length; + } + }); + function fromList(n, state2) { + if (state2.length === 0) return null; + var ret; + if (state2.objectMode) ret = state2.buffer.shift(); + else if (!n || n >= state2.length) { + if (state2.decoder) ret = state2.buffer.join(""); + else if (state2.buffer.length === 1) ret = state2.buffer.first(); + else ret = state2.buffer.concat(state2.length); + state2.buffer.clear(); + } else { + ret = state2.buffer.consume(n, state2.decoder); + } + return ret; + } + function endReadable(stream2) { + var state2 = stream2._readableState; + debug2("endReadable", state2.endEmitted); + if (!state2.endEmitted) { + state2.ended = true; + process.nextTick(endReadableNT, state2, stream2); + } + } + function endReadableNT(state2, stream2) { + debug2("endReadableNT", state2.endEmitted, state2.length); + if (!state2.endEmitted && state2.length === 0) { + state2.endEmitted = true; + stream2.readable = false; + stream2.emit("end"); + if (state2.autoDestroy) { + var wState = stream2._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream2.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable.from = function(iterable, opts) { + if (from2 === void 0) { + from2 = requireFromBrowser$1(); + } + return from2(Readable, iterable, opts); + }; + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + return _stream_readable$1; +} +var _stream_transform$1; +var hasRequired_stream_transform$1; +function require_stream_transform$1() { + if (hasRequired_stream_transform$1) return _stream_transform$1; + hasRequired_stream_transform$1 = 1; + _stream_transform$1 = Transform; + var _require$codes = requireErrorsBrowser$1().codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex$1(); + requireInherits_browser$1()(Transform, Duplex); + function afterTransform(er, data2) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data2 != null) + this.push(data2); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options2) { + if (!(this instanceof Transform)) return new Transform(options2); + Duplex.call(this, options2); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options2) { + if (typeof options2.transform === "function") this._transform = options2.transform; + if (typeof options2.flush === "function") this._flush = options2.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er, data2) { + done(_this, er, data2); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding2) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding2); + }; + Transform.prototype._transform = function(chunk, encoding2, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding2, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding2; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream2, er, data2) { + if (er) return stream2.emit("error", er); + if (data2 != null) + stream2.push(data2); + if (stream2._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream2._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream2.push(null); + } + return _stream_transform$1; +} +var _stream_passthrough$1; +var hasRequired_stream_passthrough$1; +function require_stream_passthrough$1() { + if (hasRequired_stream_passthrough$1) return _stream_passthrough$1; + hasRequired_stream_passthrough$1 = 1; + _stream_passthrough$1 = PassThrough; + var Transform = require_stream_transform$1(); + requireInherits_browser$1()(PassThrough, Transform); + function PassThrough(options2) { + if (!(this instanceof PassThrough)) return new PassThrough(options2); + Transform.call(this, options2); + } + PassThrough.prototype._transform = function(chunk, encoding2, cb) { + cb(null, chunk); + }; + return _stream_passthrough$1; +} +var pipeline_1$1; +var hasRequiredPipeline$1; +function requirePipeline$1() { + if (hasRequiredPipeline$1) return pipeline_1$1; + hasRequiredPipeline$1 = 1; + var eos; + function once2(callback) { + var called = false; + return function() { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = requireErrorsBrowser$1().codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop2(err) { + if (err) throw err; + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function destroyer(stream2, reading, writing, callback) { + callback = once2(callback); + var closed = false; + stream2.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = requireEndOfStream$2(); + eos(stream2, { + readable: reading, + writable: writing + }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isRequest(stream2)) return stream2.abort(); + if (typeof stream2.destroy === "function") return stream2.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe(from2, to) { + return from2.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop2; + if (typeof streams[streams.length - 1] !== "function") return noop2; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error2; + var destroys = streams.map(function(stream2, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream2, reading, writing, function(err) { + if (!error2) error2 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error2); + }); + }); + return streams.reduce(pipe); + } + pipeline_1$1 = pipeline; + return pipeline_1$1; +} +var hasRequiredReadableBrowser$1; +function requireReadableBrowser$1() { + if (hasRequiredReadableBrowser$1) return readableBrowser$1.exports; + hasRequiredReadableBrowser$1 = 1; + (function(module, exports) { + exports = module.exports = require_stream_readable$1(); + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = require_stream_writable$1(); + exports.Duplex = require_stream_duplex$1(); + exports.Transform = require_stream_transform$1(); + exports.PassThrough = require_stream_passthrough$1(); + exports.finished = requireEndOfStream$2(); + exports.pipeline = requirePipeline$1(); + })(readableBrowser$1, readableBrowser$1.exports); + return readableBrowser$1.exports; +} +var sign = { exports: {} }; +var bn$9 = { exports: {} }; +var bn$8 = bn$9.exports; +var hasRequiredBn$4; +function requireBn$4() { + if (hasRequiredBn$4) return bn$9.exports; + hasRequiredBn$4 = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this._strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 48 && c <= 57) { + return c - 48; + } else if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert2(false, "Invalid character in " + string2); + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this._strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + b = c - 49 + 10; + } else if (c >= 17) { + b = c - 17 + 10; + } else { + b = c; + } + assert2(c >= 0 && b < mul, "Invalid character"); + r += b; + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this._strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + function move(dest, src2) { + dest.words = src2.words; + dest.length = src2.length; + dest.negative = src2.negative; + dest.red = src2.red; + } + BN.prototype._move = function _move(dest) { + move(dest, this); + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype._strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") { + try { + BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; + } + } else { + BN.prototype.inspect = inspect; + } + function inspect() { + return (this.red ? ""; + } + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16, 2); + }; + if (Buffer2) { + BN.prototype.toBuffer = function toBuffer2(endian, length) { + return this.toArrayLike(Buffer2, endian, length); + }; + } + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + var allocate = function allocate2(ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); + } + return new ArrayType(size); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + this._strip(); + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + var res = allocate(ArrayType, reqLength); + var postfix = endian === "le" ? "LE" : "BE"; + this["_toArrayLike" + postfix](res, byteLength); + return res; + }; + BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { + var position = 0; + var carry = 0; + for (var i = 0, shift = 0; i < this.length; i++) { + var word = this.words[i] << shift | carry; + res[position++] = word & 255; + if (position < res.length) { + res[position++] = word >> 8 & 255; + } + if (position < res.length) { + res[position++] = word >> 16 & 255; + } + if (shift === 6) { + if (position < res.length) { + res[position++] = word >> 24 & 255; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + if (position < res.length) { + res[position++] = carry; + while (position < res.length) { + res[position++] = 0; + } + } + }; + BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { + var position = res.length - 1; + var carry = 0; + for (var i = 0, shift = 0; i < this.length; i++) { + var word = this.words[i] << shift | carry; + res[position--] = word & 255; + if (position >= 0) { + res[position--] = word >> 8 & 255; + } + if (position >= 0) { + res[position--] = word >> 16 & 255; + } + if (shift === 6) { + if (position >= 0) { + res[position--] = word >> 24 & 255; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + if (position >= 0) { + res[position--] = carry; + while (position >= 0) { + res[position--] = 0; + } + } + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = num.words[off] >>> wbit & 1; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this._strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this._strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this._strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this._strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this._strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this._strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out._strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out._strip(); + } + function jumboMulTo(self2, num, out) { + return bigMulTo(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return isNegNum ? this.ineg() : this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this._strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this._strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this._strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this._strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this._strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this._strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q._strip(); + } + a._strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modrn = function modrn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return isNegNum ? -acc : acc; + }; + BN.prototype.modn = function modn(num) { + return this.modrn(num); + }; + BN.prototype.idivn = function idivn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + this._strip(); + return isNegNum ? this.ineg() : this; + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this._strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn$8); + })(bn$9); + return bn$9.exports; +} +var browserifyRsa; +var hasRequiredBrowserifyRsa; +function requireBrowserifyRsa() { + if (hasRequiredBrowserifyRsa) return browserifyRsa; + hasRequiredBrowserifyRsa = 1; + var BN = requireBn$4(); + var randomBytes = requireBrowser$e(); + function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed(); + return { blinder, unblinder: r.invm(priv.modulus) }; + } + function getr(priv) { + var len = priv.modulus.byteLength(); + var r; + do { + r = new BN(randomBytes(len)); + } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)); + return r; + } + function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(BN.mont(priv.prime1)); + var c2 = blinded.toRed(BN.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1).fromRed(); + var m2 = c2.redPow(priv.exponent2).fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p).imul(q); + return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, "be", len); + } + crt.getr = getr; + browserifyRsa = crt; + return browserifyRsa; +} +var elliptic = {}; +const version$4 = "6.5.4"; +const require$$0$4 = { + version: version$4 +}; +var utils$3 = {}; +var bn$7 = { exports: {} }; +var bn$6 = bn$7.exports; +var hasRequiredBn$3; +function requireBn$3() { + if (hasRequiredBn$3) return bn$7.exports; + hasRequiredBn$3 = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + return c - 48 & 15; + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this.strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + r += c - 49 + 10; + } else if (c >= 17) { + r += c - 17 + 10; + } else { + r += c; + } + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this.strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + BN.prototype.inspect = function inspect() { + return (this.red ? ""; + }; + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16); + }; + BN.prototype.toBuffer = function toBuffer2(endian, length) { + assert2(typeof Buffer2 !== "undefined"); + return this.toArrayLike(Buffer2, endian, length); + }; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + this.strip(); + var littleEndian = endian === "le"; + var res = new ArrayType(reqLength); + var b, i; + var q = this.clone(); + if (!littleEndian) { + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[i] = b; + } + for (; i < reqLength; i++) { + res[i] = 0; + } + } + return res; + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = (num.words[off] & 1 << wbit) >>> wbit; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this.strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this.strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this.strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this.strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this.strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this.strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out.strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out.strip(); + } + function jumboMulTo(self2, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + function FFTM(x, y) { + this.x = x; + this.y = y; + } + FFTM.prototype.makeRBT = function makeRBT(N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + return t; + }; + FFTM.prototype.revBin = function revBin(x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << l - i - 1; + x >>= 1; + } + return rb; + }; + FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + FFTM.prototype.transform = function transform2(rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + for (var j = 0; j < s; j++) { + var re2 = rtws[p + j]; + var ie = itws[p + j]; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + rtws[p + j] = re2 + ro; + itws[p + j] = ie + io; + rtws[p + j + s] = re2 - ro; + itws[p + j + s] = ie - io; + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + FFTM.prototype.guessLen13b = function guessLen13b(n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + return 1 << i + 1 + odd; + }; + FFTM.prototype.conjugate = function conjugate(rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + t = iws[i]; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + FFTM.prototype.normalize13b = function normalize13b(ws2, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws2[2 * i + 1] / N) * 8192 + Math.round(ws2[2 * i] / N) + carry; + ws2[i] = w & 67108863; + if (w < 67108864) { + carry = 0; + } else { + carry = w / 67108864 | 0; + } + } + return ws2; + }; + FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws2[i] | 0); + rws[2 * i] = carry & 8191; + carry = carry >>> 13; + rws[2 * i + 1] = carry & 8191; + carry = carry >>> 13; + } + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + assert2(carry === 0); + assert2((carry & -8192) === 0); + }; + FFTM.prototype.stub = function stub(N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + return ph; + }; + FFTM.prototype.mulp = function mulp(x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + var rbt = this.makeRBT(N); + var _ = this.stub(N); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + var rmws = out.words; + rmws.length = N; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this.strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this.strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this.strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this.strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this.strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this.strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modn = function modn(num) { + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return acc; + }; + BN.prototype.idivn = function idivn(num) { + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + return this.strip(); + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this.strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn$6); + })(bn$7); + return bn$7.exports; +} +var utils$2 = {}; +var hasRequiredUtils$3; +function requireUtils$3() { + if (hasRequiredUtils$3) return utils$2; + hasRequiredUtils$3 = 1; + (function(exports) { + var utils2 = exports; + function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== "string") { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === "hex") { + msg = msg.replace(/[^a-z0-9]+/ig, ""); + if (msg.length % 2 !== 0) + msg = "0" + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 255; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; + } + utils2.toArray = toArray; + function zero2(word) { + if (word.length === 1) + return "0" + word; + else + return word; + } + utils2.zero2 = zero2; + function toHex(msg) { + var res = ""; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils2.toHex = toHex; + utils2.encode = function encode(arr, enc) { + if (enc === "hex") + return toHex(arr); + else + return arr; + }; + })(utils$2); + return utils$2; +} +var hasRequiredUtils$2; +function requireUtils$2() { + if (hasRequiredUtils$2) return utils$3; + hasRequiredUtils$2 = 1; + (function(exports) { + var utils2 = exports; + var BN = requireBn$3(); + var minAssert = requireMinimalisticAssert(); + var minUtils = requireUtils$3(); + utils2.assert = minAssert; + utils2.toArray = minUtils.toArray; + utils2.zero2 = minUtils.zero2; + utils2.toHex = minUtils.toHex; + utils2.encode = minUtils.encode; + function getNAF(num, w, bits) { + var naf = new Array(Math.max(num.bitLength(), bits) + 1); + naf.fill(0); + var ws2 = 1 << w + 1; + var k = num.clone(); + for (var i = 0; i < naf.length; i++) { + var z; + var mod = k.andln(ws2 - 1); + if (k.isOdd()) { + if (mod > (ws2 >> 1) - 1) + z = (ws2 >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf[i] = z; + k.iushrn(1); + } + return naf; + } + utils2.getNAF = getNAF; + function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + var m8; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + var m14 = k1.andln(3) + d1 & 3; + var m24 = k2.andln(3) + d2 & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + m8 = k1.andln(7) + d1 & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + m8 = k2.andln(7) + d2 & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + return jsf; + } + utils2.getJSF = getJSF; + function cachedProperty(obj, name, computer) { + var key2 = "_" + name; + obj.prototype[name] = function cachedProperty2() { + return this[key2] !== void 0 ? this[key2] : this[key2] = computer.call(this); + }; + } + utils2.cachedProperty = cachedProperty; + function parseBytes(bytes) { + return typeof bytes === "string" ? utils2.toArray(bytes, "hex") : bytes; + } + utils2.parseBytes = parseBytes; + function intFromLE(bytes) { + return new BN(bytes, "hex", "le"); + } + utils2.intFromLE = intFromLE; + })(utils$3); + return utils$3; +} +var curve = {}; +var base$2; +var hasRequiredBase$1; +function requireBase$1() { + if (hasRequiredBase$1) return base$2; + hasRequiredBase$1 = 1; + var BN = requireBn$3(); + var utils2 = requireUtils$2(); + var getNAF = utils2.getNAF; + var getJSF = utils2.getJSF; + var assert2 = utils2.assert; + function BaseCurve(type2, conf) { + this.type = type2; + this.p = new BN(conf.p, 16); + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + this._bitLength = this.n ? this.n.bitLength() : 0; + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } + } + base$2 = BaseCurve; + BaseCurve.prototype.point = function point() { + throw new Error("Not implemented"); + }; + BaseCurve.prototype.validate = function validate() { + throw new Error("Not implemented"); + }; + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert2(p.precomputed); + var doubles = p._getDoubles(); + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + var repr = []; + var j; + var nafW; + for (j = 0; j < naf.length; j += doubles.step) { + nafW = 0; + for (var l = j + doubles.step - 1; l >= j; l--) + nafW = (nafW << 1) + naf[l]; + repr.push(nafW); + } + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (j = 0; j < repr.length; j++) { + nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); + }; + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + var naf = getNAF(k, w, this._bitLength); + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + for (var l = 0; i >= 0 && naf[i] === 0; i--) + l++; + if (i >= 0) + l++; + acc = acc.dblp(l); + if (i < 0) + break; + var z = naf[i]; + assert2(z !== 0); + if (p.type === "affine") { + if (z > 0) + acc = acc.mixedAdd(wnd[z - 1 >> 1]); + else + acc = acc.mixedAdd(wnd[-z - 1 >> 1].neg()); + } else { + if (z > 0) + acc = acc.add(wnd[z - 1 >> 1]); + else + acc = acc.add(wnd[-z - 1 >> 1].neg()); + } + } + return p.type === "affine" ? acc.toP() : acc; + }; + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + var max2 = 0; + var i; + var j; + var p; + for (i = 0; i < len; i++) { + p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + for (i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); + naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); + max2 = Math.max(naf[a].length, max2); + max2 = Math.max(naf[b].length, max2); + continue; + } + var comb = [ + points[a], + /* 1 */ + null, + /* 3 */ + null, + /* 5 */ + points[b] + /* 7 */ + ]; + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + var index2 = [ + -3, + /* -1 -1 */ + -1, + /* -1 0 */ + -5, + /* -1 1 */ + -7, + /* 0 -1 */ + 0, + /* 0 0 */ + 7, + /* 0 1 */ + 5, + /* 1 -1 */ + 1, + /* 1 0 */ + 3 + /* 1 1 */ + ]; + var jsf = getJSF(coeffs[a], coeffs[b]); + max2 = Math.max(jsf[0].length, max2); + naf[a] = new Array(max2); + naf[b] = new Array(max2); + for (j = 0; j < max2; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + naf[a][j] = index2[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max2; i >= 0; i--) { + var k = 0; + while (i >= 0) { + var zero = true; + for (j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + for (j = 0; j < len; j++) { + var z = tmp[j]; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][z - 1 >> 1]; + else if (z < 0) + p = wnd[j][-z - 1 >> 1].neg(); + if (p.type === "affine") + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + for (i = 0; i < len; i++) + wnd[i] = null; + if (jacobianResult) + return acc; + else + return acc.toP(); + }; + function BasePoint(curve2, type2) { + this.curve = curve2; + this.type = type2; + this.precomputed = null; + } + BaseCurve.BasePoint = BasePoint; + BasePoint.prototype.eq = function eq() { + throw new Error("Not implemented"); + }; + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils2.toArray(bytes, enc); + var len = this.p.byteLength(); + if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len) { + if (bytes[0] === 6) + assert2(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 7) + assert2(bytes[bytes.length - 1] % 2 === 1); + var res = this.point( + bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len) + ); + return res; + } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 3); + } + throw new Error("Unknown point format"); + }; + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); + }; + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray("be", len); + if (compact) + return [this.getY().isEven() ? 2 : 3].concat(x); + return [4].concat(x, this.getY().toArray("be", len)); + }; + BasePoint.prototype.encode = function encode(enc, compact) { + return utils2.encode(this._encode(compact), enc); + }; + BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + return this; + }; + BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); + }; + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + var doubles = [this]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step, + points: doubles + }; + }; + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + var res = [this]; + var max2 = (1 << wnd) - 1; + var dbl = max2 === 1 ? null : this.dbl(); + for (var i = 1; i < max2; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd, + points: res + }; + }; + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; + return base$2; +} +var short; +var hasRequiredShort; +function requireShort() { + if (hasRequiredShort) return short; + hasRequiredShort = 1; + var utils2 = requireUtils$2(); + var BN = requireBn$3(); + var inherits = requireInherits_browser$1(); + var Base = requireBase$1(); + var assert2 = utils2.assert; + function ShortCurve(conf) { + Base.call(this, "short", conf); + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); + } + inherits(ShortCurve, Base); + short = ShortCurve; + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + return { + beta, + lambda, + basis + }; + }; + ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [l1, l2]; + }; + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + var a0; + var b0; + var a1; + var b1; + var a2; + var b2; + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; + }; + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1, k2 }; + }; + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error("invalid point"); + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + return this.point(x, y); + }; + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + var x = point.x; + var y = point.y; + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; + }; + ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; + }; + function Point(curve2, x, y, isRed) { + Base.BasePoint.call(this, curve2, "affine"); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } + } + inherits(Point, Base.BasePoint); + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); + }; + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); + }; + Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve2 = this.curve; + var endoMul = function(p) { + return curve2.point(p.x.redMul(curve2.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; + }; + Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [this.x, this.y]; + return [this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + }]; + }; + Point.fromJSON = function fromJSON(curve2, obj, red) { + if (typeof obj === "string") + obj = JSON.parse(obj); + var res = curve2.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + function obj2point(obj2) { + return curve2.point(obj2[0], obj2[1], red); + } + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [res].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [res].concat(pre.naf.points.map(obj2point)) + } + }; + return res; + }; + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ""; + return ""; + }; + Point.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + Point.prototype.add = function add(p) { + if (this.inf) + return p; + if (p.inf) + return this; + if (this.eq(p)) + return this.dbl(); + if (this.neg().eq(p)) + return this.curve.point(null, null); + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + var a = this.curve.a; + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + Point.prototype.getX = function getX() { + return this.x.fromRed(); + }; + Point.prototype.getY = function getY() { + return this.y.fromRed(); + }; + Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + if (this.isInfinity()) + return this; + else if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([this], [k]); + else + return this.curve._wnafMul(this, k); + }; + Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [this, p2]; + var coeffs = [k1, k2]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); + }; + Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [this, p2]; + var coeffs = [k1, k2]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); + }; + Point.prototype.eq = function eq(p) { + return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); + }; + Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; + }; + Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; + }; + function JPoint(curve2, x, y, z) { + Base.BasePoint.call(this, curve2, "jacobian"); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + } + inherits(JPoint, Base.BasePoint); + ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); + }; + JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + return this.curve.point(ax, ay); + }; + JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; + JPoint.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.mixedAdd = function mixedAdd(p) { + if (this.isInfinity()) + return p.toJ(); + if (p.isInfinity()) + return this; + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.dblp = function dblp(pow2) { + if (pow2 === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow2) + return this.dbl(); + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (i = 0; i < pow2; i++) + r = r.dbl(); + return r; + } + var a = this.curve.a; + var tinv = this.curve.tinv; + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + var jyd = jy.redAdd(jy); + for (i = 0; i < pow2; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow2) + jz4 = jz4.redMul(jyd4); + jx = nx; + jz = nz; + jyd = dny; + } + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); + }; + JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); + }; + JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + if (this.zOne) { + var xx = this.x.redSqr(); + var yy = this.y.redSqr(); + var yyyy = yy.redSqr(); + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + var m = xx.redAdd(xx).redIAdd(xx); + var t = m.redSqr().redISub(s).redISub(s); + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + nx = t; + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + nz = this.y.redAdd(this.y); + } else { + var a = this.x.redSqr(); + var b = this.y.redSqr(); + var c = b.redSqr(); + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + var e = a.redAdd(a).redIAdd(a); + var f = e.redSqr(); + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + nx = f.redISub(d).redISub(d); + ny = e.redMul(d.redISub(nx)).redISub(c8); + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + if (this.zOne) { + var xx = this.x.redSqr(); + var yy = this.y.redSqr(); + var yyyy = yy.redSqr(); + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + var t = m.redSqr().redISub(s).redISub(s); + nx = t; + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + nz = this.y.redAdd(this.y); + } else { + var delta = this.z.redSqr(); + var gamma = this.y.redSqr(); + var beta = this.x.redMul(gamma); + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + var xx = this.x.redSqr(); + var yy = this.y.redSqr(); + var zz = this.z.redSqr(); + var yyyy = yy.redSqr(); + var m = xx.redAdd(xx).redIAdd(xx); + var mm = m.redSqr(); + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + var ee = e.redSqr(); + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + return this.curve._wnafMul(this, k); + }; + JPoint.prototype.eq = function eq(p) { + if (p.type === "affine") + return this.eq(p.toJ()); + if (this === p) + return true; + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; + }; + JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (; ; ) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + }; + JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ""; + return ""; + }; + JPoint.prototype.isInfinity = function isInfinity() { + return this.z.cmpn(0) === 0; + }; + return short; +} +var mont; +var hasRequiredMont; +function requireMont() { + if (hasRequiredMont) return mont; + hasRequiredMont = 1; + var BN = requireBn$3(); + var inherits = requireInherits_browser$1(); + var Base = requireBase$1(); + var utils2 = requireUtils$2(); + function MontCurve(conf) { + Base.call(this, "mont", conf); + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits(MontCurve, Base); + mont = MontCurve; + MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + return y.redSqr().cmp(rhs) === 0; + }; + function Point(curve2, x, z) { + Base.BasePoint.call(this, curve2, "projective"); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } + } + inherits(Point, Base.BasePoint); + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils2.toArray(bytes, enc), 1); + }; + MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); + }; + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; + Point.prototype.precompute = function precompute() { + }; + Point.prototype._encode = function _encode() { + return this.getX().toArray("be", this.curve.p.byteLength()); + }; + Point.fromJSON = function fromJSON(curve2, obj) { + return new Point(curve2, obj[0], obj[1] || curve2.one); + }; + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ""; + return ""; + }; + Point.prototype.isInfinity = function isInfinity() { + return this.z.cmpn(0) === 0; + }; + Point.prototype.dbl = function dbl() { + var a = this.x.redAdd(this.z); + var aa = a.redSqr(); + var b = this.x.redSub(this.z); + var bb = b.redSqr(); + var c = aa.redSub(bb); + var nx = aa.redMul(bb); + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); + }; + Point.prototype.add = function add() { + throw new Error("Not supported on Montgomery curve"); + }; + Point.prototype.diffAdd = function diffAdd(p, diff3) { + var a = this.x.redAdd(this.z); + var b = this.x.redSub(this.z); + var c = p.x.redAdd(p.z); + var d = p.x.redSub(p.z); + var da = d.redMul(a); + var cb = c.redMul(b); + var nx = diff3.z.redMul(da.redAdd(cb).redSqr()); + var nz = diff3.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); + }; + Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; + var b = this.curve.point(null, null); + var c = this; + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + a = a.diffAdd(b, c); + b = b.dbl(); + } else { + b = a.diffAdd(b, c); + a = a.dbl(); + } + } + return b; + }; + Point.prototype.mulAdd = function mulAdd() { + throw new Error("Not supported on Montgomery curve"); + }; + Point.prototype.jumlAdd = function jumlAdd() { + throw new Error("Not supported on Montgomery curve"); + }; + Point.prototype.eq = function eq(other2) { + return this.getX().cmp(other2.getX()) === 0; + }; + Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); + }; + return mont; +} +var edwards; +var hasRequiredEdwards; +function requireEdwards() { + if (hasRequiredEdwards) return edwards; + hasRequiredEdwards = 1; + var utils2 = requireUtils$2(); + var BN = requireBn$3(); + var inherits = requireInherits_browser$1(); + var Base = requireBase$1(); + var assert2 = utils2.assert; + function EdwardsCurve(conf) { + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + Base.call(this, "edwards", conf); + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + assert2(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits(EdwardsCurve, Base); + edwards = EdwardsCurve; + EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); + }; + EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); + }; + EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); + }; + EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error("invalid point"); + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + return this.point(x, y); + }; + EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + var y2 = y.redSqr(); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); + var x2 = lhs.redMul(rhs.redInvm()); + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error("invalid point"); + else + return this.point(this.zero, y); + } + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error("invalid point"); + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); + return this.point(x, y); + }; + EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + point.normalize(); + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + return lhs.cmp(rhs) === 0; + }; + function Point(curve2, x, y, z, t) { + Base.BasePoint.call(this, curve2, "projective"); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } + } + inherits(Point, Base.BasePoint); + EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; + EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); + }; + Point.fromJSON = function fromJSON(curve2, obj) { + return new Point(curve2, obj[0], obj[1], obj[2]); + }; + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ""; + return ""; + }; + Point.prototype.isInfinity = function isInfinity() { + return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0); + }; + Point.prototype._extDbl = function _extDbl() { + var a = this.x.redSqr(); + var b = this.y.redSqr(); + var c = this.z.redSqr(); + c = c.redIAdd(c); + var d = this.curve._mulA(a); + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + var g = d.redAdd(b); + var f = g.redSub(c); + var h = d.redSub(b); + var nx = e.redMul(f); + var ny = g.redMul(h); + var nt = e.redMul(h); + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + Point.prototype._projDbl = function _projDbl() { + var b = this.x.redAdd(this.y).redSqr(); + var c = this.x.redSqr(); + var d = this.y.redSqr(); + var nx; + var ny; + var nz; + var e; + var h; + var j; + if (this.curve.twisted) { + e = this.curve._mulA(c); + var f = e.redAdd(d); + if (this.zOne) { + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + ny = f.redMul(e.redSub(d)); + nz = f.redSqr().redSub(f).redSub(f); + } else { + h = this.z.redSqr(); + j = f.redSub(h).redISub(h); + nx = b.redSub(c).redISub(d).redMul(j); + ny = f.redMul(e.redSub(d)); + nz = f.redMul(j); + } + } else { + e = c.redAdd(d); + h = this.curve._mulC(this.z).redSqr(); + j = e.redSub(h).redSub(h); + nx = this.curve._mulC(b.redISub(e)).redMul(j); + ny = this.curve._mulC(e).redMul(c.redISub(d)); + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); + }; + Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); + }; + Point.prototype._extAdd = function _extAdd(p) { + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + var c = this.t.redMul(this.curve.dd).redMul(p.t); + var d = this.z.redMul(p.z.redAdd(p.z)); + var e = b.redSub(a); + var f = d.redSub(c); + var g = d.redAdd(c); + var h = b.redAdd(a); + var nx = e.redMul(f); + var ny = g.redMul(h); + var nt = e.redMul(h); + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + Point.prototype._projAdd = function _projAdd(p) { + var a = this.z.redMul(p.z); + var b = a.redSqr(); + var c = this.x.redMul(p.x); + var d = this.y.redMul(p.y); + var e = this.curve.d.redMul(c).redMul(d); + var f = b.redSub(e); + var g = b.redAdd(e); + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + nz = f.redMul(g); + } else { + ny = a.redMul(g).redMul(d.redSub(c)); + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); + }; + Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); + }; + Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); + }; + Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, false); + }; + Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, true); + }; + Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; + }; + Point.prototype.neg = function neg() { + return this.curve.point( + this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg() + ); + }; + Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); + }; + Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); + }; + Point.prototype.eq = function eq(other2) { + return this === other2 || this.getX().cmp(other2.getX()) === 0 && this.getY().cmp(other2.getY()) === 0; + }; + Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (; ; ) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + }; + Point.prototype.toP = Point.prototype.normalize; + Point.prototype.mixedAdd = Point.prototype.add; + return edwards; +} +var hasRequiredCurve; +function requireCurve() { + if (hasRequiredCurve) return curve; + hasRequiredCurve = 1; + (function(exports) { + var curve2 = exports; + curve2.base = requireBase$1(); + curve2.short = requireShort(); + curve2.mont = requireMont(); + curve2.edwards = requireEdwards(); + })(curve); + return curve; +} +var curves = {}; +var hash = {}; +var utils$1 = {}; +var hasRequiredUtils$1; +function requireUtils$1() { + if (hasRequiredUtils$1) return utils$1; + hasRequiredUtils$1 = 1; + var assert2 = requireMinimalisticAssert(); + var inherits = requireInherits_browser$1(); + utils$1.inherits = inherits; + function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 64512) !== 55296) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 64512) === 56320; + } + function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === "string") { + if (!enc) { + var p = 0; + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } else if (c < 2048) { + res[p++] = c >> 6 | 192; + res[p++] = c & 63 | 128; + } else if (isSurrogatePair(msg, i)) { + c = 65536 + ((c & 1023) << 10) + (msg.charCodeAt(++i) & 1023); + res[p++] = c >> 18 | 240; + res[p++] = c >> 12 & 63 | 128; + res[p++] = c >> 6 & 63 | 128; + res[p++] = c & 63 | 128; + } else { + res[p++] = c >> 12 | 224; + res[p++] = c >> 6 & 63 | 128; + res[p++] = c & 63 | 128; + } + } + } else if (enc === "hex") { + msg = msg.replace(/[^a-z0-9]+/ig, ""); + if (msg.length % 2 !== 0) + msg = "0" + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; + } + utils$1.toArray = toArray; + function toHex(msg) { + var res = ""; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$1.toHex = toHex; + function htonl(w) { + var res = w >>> 24 | w >>> 8 & 65280 | w << 8 & 16711680 | (w & 255) << 24; + return res >>> 0; + } + utils$1.htonl = htonl; + function toHex32(msg, endian) { + var res = ""; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === "little") + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; + } + utils$1.toHex32 = toHex32; + function zero2(word) { + if (word.length === 1) + return "0" + word; + else + return word; + } + utils$1.zero2 = zero2; + function zero8(word) { + if (word.length === 7) + return "0" + word; + else if (word.length === 6) + return "00" + word; + else if (word.length === 5) + return "000" + word; + else if (word.length === 4) + return "0000" + word; + else if (word.length === 3) + return "00000" + word; + else if (word.length === 2) + return "000000" + word; + else if (word.length === 1) + return "0000000" + word; + else + return word; + } + utils$1.zero8 = zero8; + function join32(msg, start, end, endian) { + var len = end - start; + assert2(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === "big") + w = msg[k] << 24 | msg[k + 1] << 16 | msg[k + 2] << 8 | msg[k + 3]; + else + w = msg[k + 3] << 24 | msg[k + 2] << 16 | msg[k + 1] << 8 | msg[k]; + res[i] = w >>> 0; + } + return res; + } + utils$1.join32 = join32; + function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === "big") { + res[k] = m >>> 24; + res[k + 1] = m >>> 16 & 255; + res[k + 2] = m >>> 8 & 255; + res[k + 3] = m & 255; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = m >>> 16 & 255; + res[k + 1] = m >>> 8 & 255; + res[k] = m & 255; + } + } + return res; + } + utils$1.split32 = split32; + function rotr32(w, b) { + return w >>> b | w << 32 - b; + } + utils$1.rotr32 = rotr32; + function rotl32(w, b) { + return w << b | w >>> 32 - b; + } + utils$1.rotl32 = rotl32; + function sum32(a, b) { + return a + b >>> 0; + } + utils$1.sum32 = sum32; + function sum32_3(a, b, c) { + return a + b + c >>> 0; + } + utils$1.sum32_3 = sum32_3; + function sum32_4(a, b, c, d) { + return a + b + c + d >>> 0; + } + utils$1.sum32_4 = sum32_4; + function sum32_5(a, b, c, d, e) { + return a + b + c + d + e >>> 0; + } + utils$1.sum32_5 = sum32_5; + function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + var lo = al + bl >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; + } + utils$1.sum64 = sum64; + function sum64_hi(ah, al, bh, bl) { + var lo = al + bl >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$1.sum64_hi = sum64_hi; + function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$1.sum64_lo = sum64_lo; + function sum64_4_hi(ah, al, bh, bl, ch, cl, dh2, dl) { + var carry = 0; + var lo = al; + lo = lo + bl >>> 0; + carry += lo < al ? 1 : 0; + lo = lo + cl >>> 0; + carry += lo < cl ? 1 : 0; + lo = lo + dl >>> 0; + carry += lo < dl ? 1 : 0; + var hi = ah + bh + ch + dh2 + carry; + return hi >>> 0; + } + utils$1.sum64_4_hi = sum64_4_hi; + function sum64_4_lo(ah, al, bh, bl, ch, cl, dh2, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$1.sum64_4_lo = sum64_4_lo; + function sum64_5_hi(ah, al, bh, bl, ch, cl, dh2, dl, eh, el) { + var carry = 0; + var lo = al; + lo = lo + bl >>> 0; + carry += lo < al ? 1 : 0; + lo = lo + cl >>> 0; + carry += lo < cl ? 1 : 0; + lo = lo + dl >>> 0; + carry += lo < dl ? 1 : 0; + lo = lo + el >>> 0; + carry += lo < el ? 1 : 0; + var hi = ah + bh + ch + dh2 + eh + carry; + return hi >>> 0; + } + utils$1.sum64_5_hi = sum64_5_hi; + function sum64_5_lo(ah, al, bh, bl, ch, cl, dh2, dl, eh, el) { + var lo = al + bl + cl + dl + el; + return lo >>> 0; + } + utils$1.sum64_5_lo = sum64_5_lo; + function rotr64_hi(ah, al, num) { + var r = al << 32 - num | ah >>> num; + return r >>> 0; + } + utils$1.rotr64_hi = rotr64_hi; + function rotr64_lo(ah, al, num) { + var r = ah << 32 - num | al >>> num; + return r >>> 0; + } + utils$1.rotr64_lo = rotr64_lo; + function shr64_hi(ah, al, num) { + return ah >>> num; + } + utils$1.shr64_hi = shr64_hi; + function shr64_lo(ah, al, num) { + var r = ah << 32 - num | al >>> num; + return r >>> 0; + } + utils$1.shr64_lo = shr64_lo; + return utils$1; +} +var common$3 = {}; +var hasRequiredCommon$3; +function requireCommon$3() { + if (hasRequiredCommon$3) return common$3; + hasRequiredCommon$3 = 1; + var utils2 = requireUtils$1(); + var assert2 = requireMinimalisticAssert(); + function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = "big"; + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; + } + common$3.BlockHash = BlockHash; + BlockHash.prototype.update = function update(msg, enc) { + msg = utils2.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + if (this.pending.length >= this._delta8) { + msg = this.pending; + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + msg = utils2.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + return this; + }; + BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert2(this.pending === null); + return this._digest(enc); + }; + BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - (len + this.padLength) % bytes; + var res = new Array(k + this.padLength); + res[0] = 128; + for (var i = 1; i < k; i++) + res[i] = 0; + len <<= 3; + if (this.endian === "big") { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = len >>> 24 & 255; + res[i++] = len >>> 16 & 255; + res[i++] = len >>> 8 & 255; + res[i++] = len & 255; + } else { + res[i++] = len & 255; + res[i++] = len >>> 8 & 255; + res[i++] = len >>> 16 & 255; + res[i++] = len >>> 24 & 255; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + return res; + }; + return common$3; +} +var sha = {}; +var common$2 = {}; +var hasRequiredCommon$2; +function requireCommon$2() { + if (hasRequiredCommon$2) return common$2; + hasRequiredCommon$2 = 1; + var utils2 = requireUtils$1(); + var rotr32 = utils2.rotr32; + function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); + } + common$2.ft_1 = ft_1; + function ch32(x, y, z) { + return x & y ^ ~x & z; + } + common$2.ch32 = ch32; + function maj32(x, y, z) { + return x & y ^ x & z ^ y & z; + } + common$2.maj32 = maj32; + function p32(x, y, z) { + return x ^ y ^ z; + } + common$2.p32 = p32; + function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + common$2.s0_256 = s0_256; + function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + common$2.s1_256 = s1_256; + function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ x >>> 3; + } + common$2.g0_256 = g0_256; + function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ x >>> 10; + } + common$2.g1_256 = g1_256; + return common$2; +} +var _1; +var hasRequired_1; +function require_1() { + if (hasRequired_1) return _1; + hasRequired_1 = 1; + var utils2 = requireUtils$1(); + var common2 = requireCommon$3(); + var shaCommon = requireCommon$2(); + var rotl32 = utils2.rotl32; + var sum32 = utils2.sum32; + var sum32_5 = utils2.sum32_5; + var ft_1 = shaCommon.ft_1; + var BlockHash = common2.BlockHash; + var sha1_K = [ + 1518500249, + 1859775393, + 2400959708, + 3395469782 + ]; + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + BlockHash.call(this); + this.h = [ + 1732584193, + 4023233417, + 2562383102, + 271733878, + 3285377520 + ]; + this.W = new Array(80); + } + utils2.inherits(SHA1, BlockHash); + _1 = SHA1; + SHA1.blockSize = 512; + SHA1.outSize = 160; + SHA1.hmacStrength = 80; + SHA1.padLength = 64; + SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + }; + SHA1.prototype._digest = function digest(enc) { + if (enc === "hex") + return utils2.toHex32(this.h, "big"); + else + return utils2.split32(this.h, "big"); + }; + return _1; +} +var _256; +var hasRequired_256; +function require_256() { + if (hasRequired_256) return _256; + hasRequired_256 = 1; + var utils2 = requireUtils$1(); + var common2 = requireCommon$3(); + var shaCommon = requireCommon$2(); + var assert2 = requireMinimalisticAssert(); + var sum32 = utils2.sum32; + var sum32_4 = utils2.sum32_4; + var sum32_5 = utils2.sum32_5; + var ch32 = shaCommon.ch32; + var maj32 = shaCommon.maj32; + var s0_256 = shaCommon.s0_256; + var s1_256 = shaCommon.s1_256; + var g0_256 = shaCommon.g0_256; + var g1_256 = shaCommon.g1_256; + var BlockHash = common2.BlockHash; + var sha256_K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]; + function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + BlockHash.call(this); + this.h = [ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils2.inherits(SHA256, BlockHash); + _256 = SHA256; + SHA256.blockSize = 512; + SHA256.outSize = 256; + SHA256.hmacStrength = 192; + SHA256.padLength = 64; + SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + assert2(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); + }; + SHA256.prototype._digest = function digest(enc) { + if (enc === "hex") + return utils2.toHex32(this.h, "big"); + else + return utils2.split32(this.h, "big"); + }; + return _256; +} +var _224; +var hasRequired_224; +function require_224() { + if (hasRequired_224) return _224; + hasRequired_224 = 1; + var utils2 = requireUtils$1(); + var SHA256 = require_256(); + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + SHA256.call(this); + this.h = [ + 3238371032, + 914150663, + 812702999, + 4144912697, + 4290775857, + 1750603025, + 1694076839, + 3204075428 + ]; + } + utils2.inherits(SHA224, SHA256); + _224 = SHA224; + SHA224.blockSize = 512; + SHA224.outSize = 224; + SHA224.hmacStrength = 192; + SHA224.padLength = 64; + SHA224.prototype._digest = function digest(enc) { + if (enc === "hex") + return utils2.toHex32(this.h.slice(0, 7), "big"); + else + return utils2.split32(this.h.slice(0, 7), "big"); + }; + return _224; +} +var _512; +var hasRequired_512; +function require_512() { + if (hasRequired_512) return _512; + hasRequired_512 = 1; + var utils2 = requireUtils$1(); + var common2 = requireCommon$3(); + var assert2 = requireMinimalisticAssert(); + var rotr64_hi = utils2.rotr64_hi; + var rotr64_lo = utils2.rotr64_lo; + var shr64_hi = utils2.shr64_hi; + var shr64_lo = utils2.shr64_lo; + var sum64 = utils2.sum64; + var sum64_hi = utils2.sum64_hi; + var sum64_lo = utils2.sum64_lo; + var sum64_4_hi = utils2.sum64_4_hi; + var sum64_4_lo = utils2.sum64_4_lo; + var sum64_5_hi = utils2.sum64_5_hi; + var sum64_5_lo = utils2.sum64_5_lo; + var BlockHash = common2.BlockHash; + var sha512_K = [ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 + ]; + function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + BlockHash.call(this); + this.h = [ + 1779033703, + 4089235720, + 3144134277, + 2227873595, + 1013904242, + 4271175723, + 2773480762, + 1595750129, + 1359893119, + 2917565137, + 2600822924, + 725511199, + 528734635, + 4215389547, + 1541459225, + 327033209 + ]; + this.k = sha512_K; + this.W = new Array(160); + } + utils2.inherits(SHA512, BlockHash); + _512 = SHA512; + SHA512.blockSize = 1024; + SHA512.outSize = 512; + SHA512.hmacStrength = 192; + SHA512.padLength = 128; + SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; + var c3_lo = W[i - 31]; + W[i] = sum64_4_hi( + c0_hi, + c0_lo, + c1_hi, + c1_lo, + c2_hi, + c2_lo, + c3_hi, + c3_lo + ); + W[i + 1] = sum64_4_lo( + c0_hi, + c0_lo, + c1_hi, + c1_lo, + c2_hi, + c2_lo, + c3_hi, + c3_lo + ); + } + }; + SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + var W = this.W; + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh2 = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + assert2(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + var T1_hi = sum64_5_hi( + c0_hi, + c0_lo, + c1_hi, + c1_lo, + c2_hi, + c2_lo, + c3_hi, + c3_lo, + c4_hi, + c4_lo + ); + var T1_lo = sum64_5_lo( + c0_hi, + c0_lo, + c1_hi, + c1_lo, + c2_hi, + c2_lo, + c3_hi, + c3_lo, + c4_hi, + c4_lo + ); + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + eh = sum64_hi(dh2, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + dh2 = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh2, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); + }; + SHA512.prototype._digest = function digest(enc) { + if (enc === "hex") + return utils2.toHex32(this.h, "big"); + else + return utils2.split32(this.h, "big"); + }; + function ch64_hi(xh, xl, yh, yl, zh) { + var r = xh & yh ^ ~xh & zh; + if (r < 0) + r += 4294967296; + return r; + } + function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = xl & yl ^ ~xl & zl; + if (r < 0) + r += 4294967296; + return r; + } + function maj64_hi(xh, xl, yh, yl, zh) { + var r = xh & yh ^ xh & zh ^ yh & zh; + if (r < 0) + r += 4294967296; + return r; + } + function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = xl & yl ^ xl & zl ^ yl & zl; + if (r < 0) + r += 4294967296; + return r; + } + function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); + var c2_hi = rotr64_hi(xl, xh, 7); + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 4294967296; + return r; + } + function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); + var c2_lo = rotr64_lo(xl, xh, 7); + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 4294967296; + return r; + } + function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 4294967296; + return r; + } + function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 4294967296; + return r; + } + function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 4294967296; + return r; + } + function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 4294967296; + return r; + } + function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); + var c2_hi = shr64_hi(xh, xl, 6); + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 4294967296; + return r; + } + function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); + var c2_lo = shr64_lo(xh, xl, 6); + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 4294967296; + return r; + } + return _512; +} +var _384; +var hasRequired_384; +function require_384() { + if (hasRequired_384) return _384; + hasRequired_384 = 1; + var utils2 = requireUtils$1(); + var SHA512 = require_512(); + function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + SHA512.call(this); + this.h = [ + 3418070365, + 3238371032, + 1654270250, + 914150663, + 2438529370, + 812702999, + 355462360, + 4144912697, + 1731405415, + 4290775857, + 2394180231, + 1750603025, + 3675008525, + 1694076839, + 1203062813, + 3204075428 + ]; + } + utils2.inherits(SHA384, SHA512); + _384 = SHA384; + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + SHA384.prototype._digest = function digest(enc) { + if (enc === "hex") + return utils2.toHex32(this.h.slice(0, 12), "big"); + else + return utils2.split32(this.h.slice(0, 12), "big"); + }; + return _384; +} +var hasRequiredSha; +function requireSha() { + if (hasRequiredSha) return sha; + hasRequiredSha = 1; + sha.sha1 = require_1(); + sha.sha224 = require_224(); + sha.sha256 = require_256(); + sha.sha384 = require_384(); + sha.sha512 = require_512(); + return sha; +} +var ripemd = {}; +var hasRequiredRipemd; +function requireRipemd() { + if (hasRequiredRipemd) return ripemd; + hasRequiredRipemd = 1; + var utils2 = requireUtils$1(); + var common2 = requireCommon$3(); + var rotl32 = utils2.rotl32; + var sum32 = utils2.sum32; + var sum32_3 = utils2.sum32_3; + var sum32_4 = utils2.sum32_4; + var BlockHash = common2.BlockHash; + function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + BlockHash.call(this); + this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]; + this.endian = "little"; + } + utils2.inherits(RIPEMD160, BlockHash); + ripemd.ripemd160 = RIPEMD160; + RIPEMD160.blockSize = 512; + RIPEMD160.outSize = 160; + RIPEMD160.hmacStrength = 192; + RIPEMD160.padLength = 64; + RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j] + ), + E + ); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j] + ), + Eh + ); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; + }; + RIPEMD160.prototype._digest = function digest(enc) { + if (enc === "hex") + return utils2.toHex32(this.h, "little"); + else + return utils2.split32(this.h, "little"); + }; + function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return x & y | ~x & z; + else if (j <= 47) + return (x | ~y) ^ z; + else if (j <= 63) + return x & z | y & ~z; + else + return x ^ (y | ~z); + } + function K(j) { + if (j <= 15) + return 0; + else if (j <= 31) + return 1518500249; + else if (j <= 47) + return 1859775393; + else if (j <= 63) + return 2400959708; + else + return 2840853838; + } + function Kh(j) { + if (j <= 15) + return 1352829926; + else if (j <= 31) + return 1548603684; + else if (j <= 47) + return 1836072691; + else if (j <= 63) + return 2053994217; + else + return 0; + } + var r = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 7, + 4, + 13, + 1, + 10, + 6, + 15, + 3, + 12, + 0, + 9, + 5, + 2, + 14, + 11, + 8, + 3, + 10, + 14, + 4, + 9, + 15, + 8, + 1, + 2, + 7, + 0, + 6, + 13, + 11, + 5, + 12, + 1, + 9, + 11, + 10, + 0, + 8, + 12, + 4, + 13, + 3, + 7, + 15, + 14, + 5, + 6, + 2, + 4, + 0, + 5, + 9, + 7, + 12, + 2, + 10, + 14, + 1, + 3, + 8, + 11, + 6, + 15, + 13 + ]; + var rh = [ + 5, + 14, + 7, + 0, + 9, + 2, + 11, + 4, + 13, + 6, + 15, + 8, + 1, + 10, + 3, + 12, + 6, + 11, + 3, + 7, + 0, + 13, + 5, + 10, + 14, + 15, + 8, + 12, + 4, + 9, + 1, + 2, + 15, + 5, + 1, + 3, + 7, + 14, + 6, + 9, + 11, + 8, + 12, + 2, + 10, + 0, + 4, + 13, + 8, + 6, + 4, + 1, + 3, + 11, + 15, + 0, + 5, + 12, + 2, + 13, + 9, + 7, + 10, + 14, + 12, + 15, + 10, + 4, + 1, + 5, + 8, + 7, + 6, + 2, + 13, + 14, + 0, + 3, + 9, + 11 + ]; + var s = [ + 11, + 14, + 15, + 12, + 5, + 8, + 7, + 9, + 11, + 13, + 14, + 15, + 6, + 7, + 9, + 8, + 7, + 6, + 8, + 13, + 11, + 9, + 7, + 15, + 7, + 12, + 15, + 9, + 11, + 7, + 13, + 12, + 11, + 13, + 6, + 7, + 14, + 9, + 13, + 15, + 14, + 8, + 13, + 6, + 5, + 12, + 7, + 5, + 11, + 12, + 14, + 15, + 14, + 15, + 9, + 8, + 9, + 14, + 5, + 6, + 8, + 6, + 5, + 12, + 9, + 15, + 5, + 11, + 6, + 8, + 13, + 12, + 5, + 12, + 13, + 14, + 11, + 8, + 5, + 6 + ]; + var sh = [ + 8, + 9, + 9, + 11, + 13, + 15, + 15, + 5, + 7, + 7, + 8, + 11, + 14, + 14, + 12, + 6, + 9, + 13, + 15, + 7, + 12, + 8, + 9, + 11, + 7, + 7, + 12, + 7, + 6, + 15, + 13, + 11, + 9, + 7, + 15, + 11, + 8, + 6, + 6, + 14, + 12, + 13, + 5, + 14, + 13, + 13, + 7, + 5, + 15, + 5, + 8, + 11, + 14, + 14, + 6, + 14, + 6, + 9, + 12, + 9, + 12, + 5, + 15, + 8, + 8, + 5, + 12, + 9, + 12, + 5, + 14, + 6, + 8, + 13, + 6, + 5, + 15, + 13, + 11, + 11 + ]; + return ripemd; +} +var hmac; +var hasRequiredHmac; +function requireHmac() { + if (hasRequiredHmac) return hmac; + hasRequiredHmac = 1; + var utils2 = requireUtils$1(); + var assert2 = requireMinimalisticAssert(); + function Hmac(hash2, key2, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash2, key2, enc); + this.Hash = hash2; + this.blockSize = hash2.blockSize / 8; + this.outSize = hash2.outSize / 8; + this.inner = null; + this.outer = null; + this._init(utils2.toArray(key2, enc)); + } + hmac = Hmac; + Hmac.prototype._init = function init(key2) { + if (key2.length > this.blockSize) + key2 = new this.Hash().update(key2).digest(); + assert2(key2.length <= this.blockSize); + for (var i = key2.length; i < this.blockSize; i++) + key2.push(0); + for (i = 0; i < key2.length; i++) + key2[i] ^= 54; + this.inner = new this.Hash().update(key2); + for (i = 0; i < key2.length; i++) + key2[i] ^= 106; + this.outer = new this.Hash().update(key2); + }; + Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; + }; + Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); + }; + return hmac; +} +var hasRequiredHash; +function requireHash() { + if (hasRequiredHash) return hash; + hasRequiredHash = 1; + (function(exports) { + var hash2 = exports; + hash2.utils = requireUtils$1(); + hash2.common = requireCommon$3(); + hash2.sha = requireSha(); + hash2.ripemd = requireRipemd(); + hash2.hmac = requireHmac(); + hash2.sha1 = hash2.sha.sha1; + hash2.sha256 = hash2.sha.sha256; + hash2.sha224 = hash2.sha.sha224; + hash2.sha384 = hash2.sha.sha384; + hash2.sha512 = hash2.sha.sha512; + hash2.ripemd160 = hash2.ripemd.ripemd160; + })(hash); + return hash; +} +var secp256k1; +var hasRequiredSecp256k1; +function requireSecp256k1() { + if (hasRequiredSecp256k1) return secp256k1; + hasRequiredSecp256k1 = 1; + secp256k1 = { + doubles: { + step: 4, + points: [ + [ + "e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", + "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821" + ], + [ + "8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", + "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf" + ], + [ + "175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", + "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695" + ], + [ + "363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", + "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9" + ], + [ + "8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", + "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36" + ], + [ + "723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", + "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f" + ], + [ + "eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", + "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999" + ], + [ + "100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", + "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09" + ], + [ + "e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", + "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d" + ], + [ + "feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", + "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088" + ], + [ + "da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", + "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d" + ], + [ + "53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", + "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8" + ], + [ + "8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", + "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a" + ], + [ + "385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", + "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453" + ], + [ + "6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", + "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160" + ], + [ + "3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", + "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0" + ], + [ + "85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", + "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6" + ], + [ + "948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", + "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589" + ], + [ + "6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", + "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17" + ], + [ + "e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", + "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda" + ], + [ + "e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", + "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd" + ], + [ + "213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", + "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2" + ], + [ + "4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", + "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6" + ], + [ + "fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", + "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f" + ], + [ + "76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", + "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01" + ], + [ + "c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", + "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3" + ], + [ + "d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", + "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f" + ], + [ + "b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", + "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7" + ], + [ + "e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", + "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78" + ], + [ + "a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", + "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1" + ], + [ + "90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", + "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150" + ], + [ + "8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", + "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82" + ], + [ + "e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", + "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc" + ], + [ + "8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", + "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b" + ], + [ + "e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", + "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51" + ], + [ + "b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", + "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45" + ], + [ + "d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", + "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120" + ], + [ + "324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", + "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84" + ], + [ + "4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", + "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d" + ], + [ + "9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", + "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d" + ], + [ + "6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", + "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8" + ], + [ + "a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", + "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8" + ], + [ + "7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", + "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac" + ], + [ + "928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", + "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f" + ], + [ + "85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", + "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962" + ], + [ + "ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", + "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907" + ], + [ + "827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", + "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec" + ], + [ + "eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", + "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d" + ], + [ + "e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", + "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414" + ], + [ + "1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", + "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd" + ], + [ + "146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", + "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0" + ], + [ + "fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", + "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811" + ], + [ + "da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", + "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1" + ], + [ + "a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", + "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c" + ], + [ + "174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", + "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73" + ], + [ + "959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", + "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd" + ], + [ + "d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", + "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405" + ], + [ + "64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", + "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589" + ], + [ + "8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", + "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e" + ], + [ + "13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", + "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27" + ], + [ + "bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", + "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1" + ], + [ + "8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", + "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482" + ], + [ + "8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", + "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945" + ], + [ + "dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", + "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573" + ], + [ + "f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", + "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82" + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", + "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672" + ], + [ + "2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", + "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6" + ], + [ + "5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", + "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da" + ], + [ + "acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", + "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37" + ], + [ + "774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", + "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b" + ], + [ + "f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", + "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81" + ], + [ + "d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", + "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58" + ], + [ + "defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", + "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77" + ], + [ + "2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", + "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a" + ], + [ + "352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", + "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c" + ], + [ + "2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", + "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67" + ], + [ + "9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", + "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402" + ], + [ + "daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", + "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55" + ], + [ + "c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", + "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482" + ], + [ + "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", + "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82" + ], + [ + "1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", + "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396" + ], + [ + "605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", + "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49" + ], + [ + "62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", + "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf" + ], + [ + "80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", + "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a" + ], + [ + "7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", + "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7" + ], + [ + "d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", + "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933" + ], + [ + "49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", + "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a" + ], + [ + "77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", + "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6" + ], + [ + "f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", + "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37" + ], + [ + "463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", + "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e" + ], + [ + "f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", + "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6" + ], + [ + "caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", + "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476" + ], + [ + "2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", + "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40" + ], + [ + "7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", + "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61" + ], + [ + "754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", + "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683" + ], + [ + "e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", + "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5" + ], + [ + "186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", + "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b" + ], + [ + "df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", + "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417" + ], + [ + "5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", + "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868" + ], + [ + "290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", + "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a" + ], + [ + "af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", + "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6" + ], + [ + "766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", + "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996" + ], + [ + "59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", + "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e" + ], + [ + "f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", + "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d" + ], + [ + "7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", + "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2" + ], + [ + "948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", + "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e" + ], + [ + "7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", + "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437" + ], + [ + "3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", + "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311" + ], + [ + "d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", + "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4" + ], + [ + "1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", + "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575" + ], + [ + "733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", + "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d" + ], + [ + "15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", + "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d" + ], + [ + "a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", + "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629" + ], + [ + "e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", + "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06" + ], + [ + "311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", + "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374" + ], + [ + "34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", + "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee" + ], + [ + "f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", + "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1" + ], + [ + "d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", + "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b" + ], + [ + "32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", + "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661" + ], + [ + "7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", + "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6" + ], + [ + "ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", + "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e" + ], + [ + "16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", + "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d" + ], + [ + "eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", + "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc" + ], + [ + "78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", + "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4" + ], + [ + "494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", + "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c" + ], + [ + "a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", + "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b" + ], + [ + "c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", + "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913" + ], + [ + "841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", + "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154" + ], + [ + "5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", + "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865" + ], + [ + "36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", + "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc" + ], + [ + "336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", + "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224" + ], + [ + "8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", + "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e" + ], + [ + "1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", + "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6" + ], + [ + "85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", + "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511" + ], + [ + "29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", + "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b" + ], + [ + "a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", + "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2" + ], + [ + "4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5", + "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c" + ], + [ + "d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b", + "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3" + ], + [ + "ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4", + "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d" + ], + [ + "af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f", + "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700" + ], + [ + "e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889", + "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4" + ], + [ + "591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246", + "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196" + ], + [ + "11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984", + "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4" + ], + [ + "3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a", + "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257" + ], + [ + "cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030", + "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13" + ], + [ + "c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197", + "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096" + ], + [ + "c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593", + "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38" + ], + [ + "a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef", + "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f" + ], + [ + "347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38", + "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448" + ], + [ + "da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a", + "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a" + ], + [ + "c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111", + "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4" + ], + [ + "4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502", + "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437" + ], + [ + "3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea", + "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7" + ], + [ + "cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26", + "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d" + ], + [ + "b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986", + "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a" + ], + [ + "d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e", + "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54" + ], + [ + "48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4", + "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77" + ], + [ + "dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda", + "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517" + ], + [ + "6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859", + "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10" + ], + [ + "e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f", + "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125" + ], + [ + "eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c", + "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e" + ], + [ + "13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942", + "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1" + ], + [ + "ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a", + "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2" + ], + [ + "b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80", + "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423" + ], + [ + "ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d", + "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8" + ], + [ + "8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1", + "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758" + ], + [ + "52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63", + "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375" + ], + [ + "e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352", + "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d" + ], + [ + "7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193", + "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec" + ], + [ + "5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00", + "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0" + ], + [ + "32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58", + "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c" + ], + [ + "e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7", + "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4" + ], + [ + "8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8", + "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f" + ], + [ + "4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e", + "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649" + ], + [ + "3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d", + "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826" + ], + [ + "674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b", + "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5" + ], + [ + "d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f", + "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87" + ], + [ + "30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6", + "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b" + ], + [ + "be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297", + "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc" + ], + [ + "93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a", + "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c" + ], + [ + "b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c", + "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f" + ], + [ + "d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52", + "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a" + ], + [ + "d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb", + "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46" + ], + [ + "463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065", + "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f" + ], + [ + "7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917", + "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03" + ], + [ + "74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9", + "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08" + ], + [ + "30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3", + "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8" + ], + [ + "9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57", + "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373" + ], + [ + "176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66", + "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3" + ], + [ + "75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8", + "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8" + ], + [ + "809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721", + "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1" + ], + [ + "1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180", + "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9" + ] + ] + } + }; + return secp256k1; +} +var hasRequiredCurves; +function requireCurves() { + if (hasRequiredCurves) return curves; + hasRequiredCurves = 1; + (function(exports) { + var curves2 = exports; + var hash2 = requireHash(); + var curve2 = requireCurve(); + var utils2 = requireUtils$2(); + var assert2 = utils2.assert; + function PresetCurve(options2) { + if (options2.type === "short") + this.curve = new curve2.short(options2); + else if (options2.type === "edwards") + this.curve = new curve2.edwards(options2); + else + this.curve = new curve2.mont(options2); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options2.hash; + assert2(this.g.validate(), "Invalid curve"); + assert2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); + } + curves2.PresetCurve = PresetCurve; + function defineCurve(name, options2) { + Object.defineProperty(curves2, name, { + configurable: true, + enumerable: true, + get: function() { + var curve3 = new PresetCurve(options2); + Object.defineProperty(curves2, name, { + configurable: true, + enumerable: true, + value: curve3 + }); + return curve3; + } + }); + } + defineCurve("p192", { + type: "short", + prime: "p192", + p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", + a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", + b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", + n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", + hash: hash2.sha256, + gRed: false, + g: [ + "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", + "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811" + ] + }); + defineCurve("p224", { + type: "short", + prime: "p224", + p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", + a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", + b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", + n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", + hash: hash2.sha256, + gRed: false, + g: [ + "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", + "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34" + ] + }); + defineCurve("p256", { + type: "short", + prime: null, + p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", + a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", + b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", + n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", + hash: hash2.sha256, + gRed: false, + g: [ + "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", + "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5" + ] + }); + defineCurve("p384", { + type: "short", + prime: null, + p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", + a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", + b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", + n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", + hash: hash2.sha384, + gRed: false, + g: [ + "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", + "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f" + ] + }); + defineCurve("p521", { + type: "short", + prime: null, + p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", + a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", + b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", + n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", + hash: hash2.sha512, + gRed: false, + g: [ + "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", + "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650" + ] + }); + defineCurve("curve25519", { + type: "mont", + prime: "p25519", + p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", + a: "76d06", + b: "1", + n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", + hash: hash2.sha256, + gRed: false, + g: [ + "9" + ] + }); + defineCurve("ed25519", { + type: "edwards", + prime: "p25519", + p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", + a: "-1", + c: "1", + // -121665 * (121666^(-1)) (mod P) + d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", + n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", + hash: hash2.sha256, + gRed: false, + g: [ + "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", + // 4/5 + "6666666666666666666666666666666666666666666666666666666666666658" + ] + }); + var pre; + try { + pre = requireSecp256k1(); + } catch (e) { + pre = void 0; + } + defineCurve("secp256k1", { + type: "short", + prime: "k256", + p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", + a: "0", + b: "7", + n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", + h: "1", + hash: hash2.sha256, + // Precomputed endomorphism + beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", + lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", + basis: [ + { + a: "3086d221a7d46bcde86c90e49284eb15", + b: "-e4437ed6010e88286f547fa90abfe4c3" + }, + { + a: "114ca50f7a8e2f3f657c1108d9d44cfd8", + b: "3086d221a7d46bcde86c90e49284eb15" + } + ], + gRed: false, + g: [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", + pre + ] + }); + })(curves); + return curves; +} +var hmacDrbg; +var hasRequiredHmacDrbg; +function requireHmacDrbg() { + if (hasRequiredHmacDrbg) return hmacDrbg; + hasRequiredHmacDrbg = 1; + var hash2 = requireHash(); + var utils2 = requireUtils$3(); + var assert2 = requireMinimalisticAssert(); + function HmacDRBG(options2) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options2); + this.hash = options2.hash; + this.predResist = !!options2.predResist; + this.outLen = this.hash.outSize; + this.minEntropy = options2.minEntropy || this.hash.hmacStrength; + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + var entropy = utils2.toArray(options2.entropy, options2.entropyEnc || "hex"); + var nonce = utils2.toArray(options2.nonce, options2.nonceEnc || "hex"); + var pers = utils2.toArray(options2.pers, options2.persEnc || "hex"); + assert2( + entropy.length >= this.minEntropy / 8, + "Not enough entropy. Minimum is: " + this.minEntropy + " bits" + ); + this._init(entropy, nonce, pers); + } + hmacDrbg = HmacDRBG; + HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0; + this.V[i] = 1; + } + this._update(seed); + this._reseed = 1; + this.reseedInterval = 281474976710656; + }; + HmacDRBG.prototype._hmac = function hmac2() { + return new hash2.hmac(this.hash, this.K); + }; + HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac().update(this.V).update([0]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + this.K = this._hmac().update(this.V).update([1]).update(seed).digest(); + this.V = this._hmac().update(this.V).digest(); + }; + HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + if (typeof entropyEnc !== "string") { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + entropy = utils2.toArray(entropy, entropyEnc); + add = utils2.toArray(add, addEnc); + assert2( + entropy.length >= this.minEntropy / 8, + "Not enough entropy. Minimum is: " + this.minEntropy + " bits" + ); + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error("Reseed is required"); + if (typeof enc !== "string") { + addEnc = add; + add = enc; + enc = null; + } + if (add) { + add = utils2.toArray(add, addEnc || "hex"); + this._update(add); + } + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils2.encode(res, enc); + }; + return hmacDrbg; +} +var key$1; +var hasRequiredKey$1; +function requireKey$1() { + if (hasRequiredKey$1) return key$1; + hasRequiredKey$1 = 1; + var BN = requireBn$3(); + var utils2 = requireUtils$2(); + var assert2 = utils2.assert; + function KeyPair(ec2, options2) { + this.ec = ec2; + this.priv = null; + this.pub = null; + if (options2.priv) + this._importPrivate(options2.priv, options2.privEnc); + if (options2.pub) + this._importPublic(options2.pub, options2.pubEnc); + } + key$1 = KeyPair; + KeyPair.fromPublic = function fromPublic(ec2, pub, enc) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(ec2, { + pub, + pubEnc: enc + }); + }; + KeyPair.fromPrivate = function fromPrivate(ec2, priv, enc) { + if (priv instanceof KeyPair) + return priv; + return new KeyPair(ec2, { + priv, + privEnc: enc + }); + }; + KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + if (pub.isInfinity()) + return { result: false, reason: "Invalid public key" }; + if (!pub.validate()) + return { result: false, reason: "Public key is not a point" }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: "Public key * N != O" }; + return { result: true, reason: null }; + }; + KeyPair.prototype.getPublic = function getPublic(compact, enc) { + if (typeof compact === "string") { + enc = compact; + compact = null; + } + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + if (!enc) + return this.pub; + return this.pub.encode(enc, compact); + }; + KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === "hex") + return this.priv.toString(16, 2); + else + return this.priv; + }; + KeyPair.prototype._importPrivate = function _importPrivate(key2, enc) { + this.priv = new BN(key2, enc || 16); + this.priv = this.priv.umod(this.ec.curve.n); + }; + KeyPair.prototype._importPublic = function _importPublic(key2, enc) { + if (key2.x || key2.y) { + if (this.ec.curve.type === "mont") { + assert2(key2.x, "Need x coordinate"); + } else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") { + assert2(key2.x && key2.y, "Need both x and y coordinate"); + } + this.pub = this.ec.curve.point(key2.x, key2.y); + return; + } + this.pub = this.ec.curve.decodePoint(key2, enc); + }; + KeyPair.prototype.derive = function derive(pub) { + if (!pub.validate()) { + assert2(pub.validate(), "public point not validated"); + } + return pub.mul(this.priv).getX(); + }; + KeyPair.prototype.sign = function sign2(msg, enc, options2) { + return this.ec.sign(msg, this, enc, options2); + }; + KeyPair.prototype.verify = function verify(msg, signature2) { + return this.ec.verify(msg, signature2, this); + }; + KeyPair.prototype.inspect = function inspect() { + return ""; + }; + return key$1; +} +var signature$1; +var hasRequiredSignature$1; +function requireSignature$1() { + if (hasRequiredSignature$1) return signature$1; + hasRequiredSignature$1 = 1; + var BN = requireBn$3(); + var utils2 = requireUtils$2(); + var assert2 = utils2.assert; + function Signature(options2, enc) { + if (options2 instanceof Signature) + return options2; + if (this._importDER(options2, enc)) + return; + assert2(options2.r && options2.s, "Signature without r or s"); + this.r = new BN(options2.r, 16); + this.s = new BN(options2.s, 16); + if (options2.recoveryParam === void 0) + this.recoveryParam = null; + else + this.recoveryParam = options2.recoveryParam; + } + signature$1 = Signature; + function Position3() { + this.place = 0; + } + function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 128)) { + return initial; + } + var octetLen = initial & 15; + if (octetLen === 0 || octetLen > 4) { + return false; + } + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + val >>>= 0; + } + if (val <= 127) { + return false; + } + p.place = off; + return val; + } + function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 128) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); + } + Signature.prototype._importDER = function _importDER(data2, enc) { + data2 = utils2.toArray(data2, enc); + var p = new Position3(); + if (data2[p.place++] !== 48) { + return false; + } + var len = getLength(data2, p); + if (len === false) { + return false; + } + if (len + p.place !== data2.length) { + return false; + } + if (data2[p.place++] !== 2) { + return false; + } + var rlen = getLength(data2, p); + if (rlen === false) { + return false; + } + var r = data2.slice(p.place, rlen + p.place); + p.place += rlen; + if (data2[p.place++] !== 2) { + return false; + } + var slen = getLength(data2, p); + if (slen === false) { + return false; + } + if (data2.length !== slen + p.place) { + return false; + } + var s = data2.slice(p.place, slen + p.place); + if (r[0] === 0) { + if (r[1] & 128) { + r = r.slice(1); + } else { + return false; + } + } + if (s[0] === 0) { + if (s[1] & 128) { + s = s.slice(1); + } else { + return false; + } + } + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + return true; + }; + function constructLength(arr, len) { + if (len < 128) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 128); + while (--octets) { + arr.push(len >>> (octets << 3) & 255); + } + arr.push(len); + } + Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + if (r[0] & 128) + r = [0].concat(r); + if (s[0] & 128) + s = [0].concat(s); + r = rmPadding(r); + s = rmPadding(s); + while (!s[0] && !(s[1] & 128)) { + s = s.slice(1); + } + var arr = [2]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(2); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [48]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils2.encode(res, enc); + }; + return signature$1; +} +var ec; +var hasRequiredEc; +function requireEc() { + if (hasRequiredEc) return ec; + hasRequiredEc = 1; + var BN = requireBn$3(); + var HmacDRBG = requireHmacDrbg(); + var utils2 = requireUtils$2(); + var curves2 = requireCurves(); + var rand = requireBrorand(); + var assert2 = utils2.assert; + var KeyPair = requireKey$1(); + var Signature = requireSignature$1(); + function EC(options2) { + if (!(this instanceof EC)) + return new EC(options2); + if (typeof options2 === "string") { + assert2( + Object.prototype.hasOwnProperty.call(curves2, options2), + "Unknown curve " + options2 + ); + options2 = curves2[options2]; + } + if (options2 instanceof curves2.PresetCurve) + options2 = { curve: options2 }; + this.curve = options2.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + this.g = options2.curve.g; + this.g.precompute(options2.curve.n.bitLength() + 1); + this.hash = options2.hash || options2.curve.hash; + } + ec = EC; + EC.prototype.keyPair = function keyPair(options2) { + return new KeyPair(this, options2); + }; + EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); + }; + EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); + }; + EC.prototype.genKeyPair = function genKeyPair(options2) { + if (!options2) + options2 = {}; + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options2.pers, + persEnc: options2.persEnc || "utf8", + entropy: options2.entropy || rand(this.hash.hmacStrength), + entropyEnc: options2.entropy && options2.entropyEnc || "utf8", + nonce: this.n.toArray() + }); + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + for (; ; ) { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + priv.iaddn(1); + return this.keyFromPrivate(priv); + } + }; + EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; + }; + EC.prototype.sign = function sign2(msg, key2, enc, options2) { + if (typeof enc === "object") { + options2 = enc; + enc = null; + } + if (!options2) + options2 = {}; + key2 = this.keyFromPrivate(key2, enc); + msg = this._truncateToN(new BN(msg, 16)); + var bytes = this.n.byteLength(); + var bkey = key2.getPrivate().toArray("be", bytes); + var nonce = msg.toArray("be", bytes); + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce, + pers: options2.pers, + persEnc: options2.persEnc || "utf8" + }); + var ns1 = this.n.sub(new BN(1)); + for (var iter = 0; ; iter++) { + var k = options2.k ? options2.k(iter) : new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + var s = k.invm(this.n).mul(r.mul(key2.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); + if (options2.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + return new Signature({ r, s, recoveryParam }); + } + }; + EC.prototype.verify = function verify(msg, signature2, key2, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key2 = this.keyFromPublic(key2, enc); + signature2 = new Signature(signature2, "hex"); + var r = signature2.r; + var s = signature2.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + var p; + if (!this.curve._maxwellTrick) { + p = this.g.mulAdd(u1, key2.getPublic(), u2); + if (p.isInfinity()) + return false; + return p.getX().umod(this.n).cmp(r) === 0; + } + p = this.g.jmulAdd(u1, key2.getPublic(), u2); + if (p.isInfinity()) + return false; + return p.eqXToP(r); + }; + EC.prototype.recoverPubKey = function(msg, signature2, j, enc) { + assert2((3 & j) === j, "The recovery param is more than two bits"); + signature2 = new Signature(signature2, enc); + var n = this.n; + var e = new BN(msg); + var r = signature2.r; + var s = signature2.s; + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error("Unable to find sencond key candinate"); + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + var rInv = signature2.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + return this.g.mulAdd(s1, r, s2); + }; + EC.prototype.getKeyRecoveryParam = function(e, signature2, Q, enc) { + signature2 = new Signature(signature2, enc); + if (signature2.recoveryParam !== null) + return signature2.recoveryParam; + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature2, i); + } catch (e2) { + continue; + } + if (Qprime.eq(Q)) + return i; + } + throw new Error("Unable to find valid recovery factor"); + }; + return ec; +} +var key; +var hasRequiredKey; +function requireKey() { + if (hasRequiredKey) return key; + hasRequiredKey = 1; + var utils2 = requireUtils$2(); + var assert2 = utils2.assert; + var parseBytes = utils2.parseBytes; + var cachedProperty = utils2.cachedProperty; + function KeyPair(eddsa2, params) { + this.eddsa = eddsa2; + this._secret = parseBytes(params.secret); + if (eddsa2.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); + } + KeyPair.fromPublic = function fromPublic(eddsa2, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa2, { pub }); + }; + KeyPair.fromSecret = function fromSecret(eddsa2, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa2, { secret }); + }; + KeyPair.prototype.secret = function secret() { + return this._secret; + }; + cachedProperty(KeyPair, "pubBytes", function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + cachedProperty(KeyPair, "pub", function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + cachedProperty(KeyPair, "privBytes", function privBytes() { + var eddsa2 = this.eddsa; + var hash2 = this.hash(); + var lastIx = eddsa2.encodingLength - 1; + var a = hash2.slice(0, eddsa2.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + return a; + }); + cachedProperty(KeyPair, "priv", function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + cachedProperty(KeyPair, "hash", function hash2() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + cachedProperty(KeyPair, "messagePrefix", function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + KeyPair.prototype.sign = function sign2(message) { + assert2(this._secret, "KeyPair can only verify"); + return this.eddsa.sign(message, this); + }; + KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + KeyPair.prototype.getSecret = function getSecret(enc) { + assert2(this._secret, "KeyPair is public only"); + return utils2.encode(this.secret(), enc); + }; + KeyPair.prototype.getPublic = function getPublic(enc) { + return utils2.encode(this.pubBytes(), enc); + }; + key = KeyPair; + return key; +} +var signature; +var hasRequiredSignature; +function requireSignature() { + if (hasRequiredSignature) return signature; + hasRequiredSignature = 1; + var BN = requireBn$3(); + var utils2 = requireUtils$2(); + var assert2 = utils2.assert; + var cachedProperty = utils2.cachedProperty; + var parseBytes = utils2.parseBytes; + function Signature(eddsa2, sig) { + this.eddsa = eddsa2; + if (typeof sig !== "object") + sig = parseBytes(sig); + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa2.encodingLength), + S: sig.slice(eddsa2.encodingLength) + }; + } + assert2(sig.R && sig.S, "Signature without R or S"); + if (eddsa2.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; + } + cachedProperty(Signature, "S", function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + cachedProperty(Signature, "R", function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + cachedProperty(Signature, "Rencoded", function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + cachedProperty(Signature, "Sencoded", function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + Signature.prototype.toHex = function toHex() { + return utils2.encode(this.toBytes(), "hex").toUpperCase(); + }; + signature = Signature; + return signature; +} +var eddsa; +var hasRequiredEddsa; +function requireEddsa() { + if (hasRequiredEddsa) return eddsa; + hasRequiredEddsa = 1; + var hash2 = requireHash(); + var curves2 = requireCurves(); + var utils2 = requireUtils$2(); + var assert2 = utils2.assert; + var parseBytes = utils2.parseBytes; + var KeyPair = requireKey(); + var Signature = requireSignature(); + function EDDSA(curve2) { + assert2(curve2 === "ed25519", "only tested with ed25519 so far"); + if (!(this instanceof EDDSA)) + return new EDDSA(curve2); + curve2 = curves2[curve2].curve; + this.curve = curve2; + this.g = curve2.g; + this.g.precompute(curve2.n.bitLength() + 1); + this.pointClass = curve2.point().constructor; + this.encodingLength = Math.ceil(curve2.n.bitLength() / 8); + this.hash = hash2.sha512; + } + eddsa = EDDSA; + EDDSA.prototype.sign = function sign2(message, secret) { + message = parseBytes(message); + var key2 = this.keyFromSecret(secret); + var r = this.hashInt(key2.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key2.pubBytes(), message).mul(key2.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R, S, Rencoded }); + }; + EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key2 = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key2.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key2.pub().mul(h)); + return RplusAh.eq(SG); + }; + EDDSA.prototype.hashInt = function hashInt() { + var hash3 = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash3.update(arguments[i]); + return utils2.intFromLE(hash3.digest()).umod(this.curve.n); + }; + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); + }; + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); + }; + EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); + }; + EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray("le", this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 128 : 0; + return enc; + }; + EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils2.parseBytes(bytes); + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & -129); + var xIsOdd = (bytes[lastIx] & 128) !== 0; + var y = utils2.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); + }; + EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray("le", this.encodingLength); + }; + EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils2.intFromLE(bytes); + }; + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + return eddsa; +} +var hasRequiredElliptic; +function requireElliptic() { + if (hasRequiredElliptic) return elliptic; + hasRequiredElliptic = 1; + (function(exports) { + var elliptic2 = exports; + elliptic2.version = require$$0$4.version; + elliptic2.utils = requireUtils$2(); + elliptic2.rand = requireBrorand(); + elliptic2.curve = requireCurve(); + elliptic2.curves = requireCurves(); + elliptic2.ec = requireEc(); + elliptic2.eddsa = requireEddsa(); + })(elliptic); + return elliptic; +} +var asn1$1 = {}; +var asn1 = {}; +var bn$5 = { exports: {} }; +var bn$4 = bn$5.exports; +var hasRequiredBn$2; +function requireBn$2() { + if (hasRequiredBn$2) return bn$5.exports; + hasRequiredBn$2 = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + return c - 48 & 15; + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this.strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + r += c - 49 + 10; + } else if (c >= 17) { + r += c - 17 + 10; + } else { + r += c; + } + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this.strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + BN.prototype.inspect = function inspect() { + return (this.red ? ""; + }; + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16); + }; + BN.prototype.toBuffer = function toBuffer2(endian, length) { + assert2(typeof Buffer2 !== "undefined"); + return this.toArrayLike(Buffer2, endian, length); + }; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + this.strip(); + var littleEndian = endian === "le"; + var res = new ArrayType(reqLength); + var b, i; + var q = this.clone(); + if (!littleEndian) { + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[i] = b; + } + for (; i < reqLength; i++) { + res[i] = 0; + } + } + return res; + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = (num.words[off] & 1 << wbit) >>> wbit; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this.strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this.strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this.strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this.strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this.strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this.strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out.strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out.strip(); + } + function jumboMulTo(self2, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + function FFTM(x, y) { + this.x = x; + this.y = y; + } + FFTM.prototype.makeRBT = function makeRBT(N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + return t; + }; + FFTM.prototype.revBin = function revBin(x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << l - i - 1; + x >>= 1; + } + return rb; + }; + FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + FFTM.prototype.transform = function transform2(rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + for (var j = 0; j < s; j++) { + var re2 = rtws[p + j]; + var ie = itws[p + j]; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + rtws[p + j] = re2 + ro; + itws[p + j] = ie + io; + rtws[p + j + s] = re2 - ro; + itws[p + j + s] = ie - io; + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + FFTM.prototype.guessLen13b = function guessLen13b(n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + return 1 << i + 1 + odd; + }; + FFTM.prototype.conjugate = function conjugate(rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + t = iws[i]; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + FFTM.prototype.normalize13b = function normalize13b(ws2, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws2[2 * i + 1] / N) * 8192 + Math.round(ws2[2 * i] / N) + carry; + ws2[i] = w & 67108863; + if (w < 67108864) { + carry = 0; + } else { + carry = w / 67108864 | 0; + } + } + return ws2; + }; + FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws2[i] | 0); + rws[2 * i] = carry & 8191; + carry = carry >>> 13; + rws[2 * i + 1] = carry & 8191; + carry = carry >>> 13; + } + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + assert2(carry === 0); + assert2((carry & -8192) === 0); + }; + FFTM.prototype.stub = function stub(N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + return ph; + }; + FFTM.prototype.mulp = function mulp(x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + var rbt = this.makeRBT(N); + var _ = this.stub(N); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + var rmws = out.words; + rmws.length = N; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this.strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this.strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this.strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this.strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this.strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this.strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modn = function modn(num) { + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return acc; + }; + BN.prototype.idivn = function idivn(num) { + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + return this.strip(); + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this.strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn$4); + })(bn$5); + return bn$5.exports; +} +var api = {}; +var encoders = {}; +var safer_1; +var hasRequiredSafer; +function requireSafer() { + if (hasRequiredSafer) return safer_1; + hasRequiredSafer = 1; + var buffer2 = requireBuffer$2(); + var Buffer2 = buffer2.Buffer; + var safer = {}; + var key2; + for (key2 in buffer2) { + if (!buffer2.hasOwnProperty(key2)) continue; + if (key2 === "SlowBuffer" || key2 === "Buffer") continue; + safer[key2] = buffer2[key2]; + } + var Safer = safer.Buffer = {}; + for (key2 in Buffer2) { + if (!Buffer2.hasOwnProperty(key2)) continue; + if (key2 === "allocUnsafe" || key2 === "allocUnsafeSlow") continue; + Safer[key2] = Buffer2[key2]; + } + safer.Buffer.prototype = Buffer2.prototype; + if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function(value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); + } + if (value && typeof value.length === "undefined") { + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); + } + return Buffer2(value, encodingOrOffset, length); + }; + } + if (!Safer.alloc) { + Safer.alloc = function(size, fill, encoding2) { + if (typeof size !== "number") { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size); + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + var buf = Buffer2(size); + if (!fill || fill.length === 0) { + buf.fill(0); + } else if (typeof encoding2 === "string") { + buf.fill(fill, encoding2); + } else { + buf.fill(fill); + } + return buf; + }; + } + if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding("buffer").kStringMaxLength; + } catch (e) { + } + } + if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + }; + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; + } + } + safer_1 = safer; + return safer_1; +} +var reporter = {}; +var hasRequiredReporter; +function requireReporter() { + if (hasRequiredReporter) return reporter; + hasRequiredReporter = 1; + const inherits = requireInherits_browser$1(); + function Reporter(options2) { + this._reporterState = { + obj: null, + path: [], + options: options2 || {}, + errors: [] + }; + } + reporter.Reporter = Reporter; + Reporter.prototype.isError = function isError2(obj) { + return obj instanceof ReporterError; + }; + Reporter.prototype.save = function save() { + const state2 = this._reporterState; + return { obj: state2.obj, pathLen: state2.path.length }; + }; + Reporter.prototype.restore = function restore(data2) { + const state2 = this._reporterState; + state2.obj = data2.obj; + state2.path = state2.path.slice(0, data2.pathLen); + }; + Reporter.prototype.enterKey = function enterKey(key2) { + return this._reporterState.path.push(key2); + }; + Reporter.prototype.exitKey = function exitKey(index2) { + const state2 = this._reporterState; + state2.path = state2.path.slice(0, index2 - 1); + }; + Reporter.prototype.leaveKey = function leaveKey(index2, key2, value) { + const state2 = this._reporterState; + this.exitKey(index2); + if (state2.obj !== null) + state2.obj[key2] = value; + }; + Reporter.prototype.path = function path2() { + return this._reporterState.path.join("/"); + }; + Reporter.prototype.enterObject = function enterObject() { + const state2 = this._reporterState; + const prev = state2.obj; + state2.obj = {}; + return prev; + }; + Reporter.prototype.leaveObject = function leaveObject(prev) { + const state2 = this._reporterState; + const now = state2.obj; + state2.obj = prev; + return now; + }; + Reporter.prototype.error = function error2(msg) { + let err; + const state2 = this._reporterState; + const inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state2.path.map(function(elem) { + return "[" + JSON.stringify(elem) + "]"; + }).join(""), msg.message || msg, msg.stack); + } + if (!state2.options.partial) + throw err; + if (!inherited) + state2.errors.push(err); + return err; + }; + Reporter.prototype.wrapResult = function wrapResult(result) { + const state2 = this._reporterState; + if (!state2.options.partial) + return result; + return { + result: this.isError(result) ? null : result, + errors: state2.errors + }; + }; + function ReporterError(path2, msg) { + this.path = path2; + this.rethrow(msg); + } + inherits(ReporterError, Error); + ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + " at: " + (this.path || "(shallow)"); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + if (!this.stack) { + try { + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; + }; + return reporter; +} +var buffer = {}; +var hasRequiredBuffer; +function requireBuffer() { + if (hasRequiredBuffer) return buffer; + hasRequiredBuffer = 1; + const inherits = requireInherits_browser$1(); + const Reporter = requireReporter().Reporter; + const Buffer2 = requireSafer().Buffer; + function DecoderBuffer(base2, options2) { + Reporter.call(this, options2); + if (!Buffer2.isBuffer(base2)) { + this.error("Input not Buffer"); + return; + } + this.base = base2; + this.offset = 0; + this.length = base2.length; + } + inherits(DecoderBuffer, Reporter); + buffer.DecoderBuffer = DecoderBuffer; + DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data2) { + if (data2 instanceof DecoderBuffer) { + return true; + } + const isCompatible = typeof data2 === "object" && Buffer2.isBuffer(data2.base) && data2.constructor.name === "DecoderBuffer" && typeof data2.offset === "number" && typeof data2.length === "number" && typeof data2.save === "function" && typeof data2.restore === "function" && typeof data2.isEmpty === "function" && typeof data2.readUInt8 === "function" && typeof data2.skip === "function" && typeof data2.raw === "function"; + return isCompatible; + }; + DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; + }; + DecoderBuffer.prototype.restore = function restore(save) { + const res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + return res; + }; + DecoderBuffer.prototype.isEmpty = function isEmpty2() { + return this.offset === this.length; + }; + DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || "DecoderBuffer overrun"); + }; + DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || "DecoderBuffer overrun"); + const res = new DecoderBuffer(this.base); + res._reporterState = this._reporterState; + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; + }; + DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); + }; + function EncoderBuffer(value, reporter2) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!EncoderBuffer.isEncoderBuffer(item)) + item = new EncoderBuffer(item, reporter2); + this.length += item.length; + return item; + }, this); + } else if (typeof value === "number") { + if (!(0 <= value && value <= 255)) + return reporter2.error("non-byte EncoderBuffer value"); + this.value = value; + this.length = 1; + } else if (typeof value === "string") { + this.value = value; + this.length = Buffer2.byteLength(value); + } else if (Buffer2.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter2.error("Unsupported type: " + typeof value); + } + } + buffer.EncoderBuffer = EncoderBuffer; + EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data2) { + if (data2 instanceof EncoderBuffer) { + return true; + } + const isCompatible = typeof data2 === "object" && data2.constructor.name === "EncoderBuffer" && typeof data2.length === "number" && typeof data2.join === "function"; + return isCompatible; + }; + EncoderBuffer.prototype.join = function join2(out, offset2) { + if (!out) + out = Buffer2.alloc(this.length); + if (!offset2) + offset2 = 0; + if (this.length === 0) + return out; + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset2); + offset2 += item.length; + }); + } else { + if (typeof this.value === "number") + out[offset2] = this.value; + else if (typeof this.value === "string") + out.write(this.value, offset2); + else if (Buffer2.isBuffer(this.value)) + this.value.copy(out, offset2); + offset2 += this.length; + } + return out; + }; + return buffer; +} +var node; +var hasRequiredNode; +function requireNode() { + if (hasRequiredNode) return node; + hasRequiredNode = 1; + const Reporter = requireReporter().Reporter; + const EncoderBuffer = requireBuffer().EncoderBuffer; + const DecoderBuffer = requireBuffer().DecoderBuffer; + const assert2 = requireMinimalisticAssert(); + const tags = [ + "seq", + "seqof", + "set", + "setof", + "objid", + "bool", + "gentime", + "utctime", + "null_", + "enum", + "int", + "objDesc", + "bitstr", + "bmpstr", + "charstr", + "genstr", + "graphstr", + "ia5str", + "iso646str", + "numstr", + "octstr", + "printstr", + "t61str", + "unistr", + "utf8str", + "videostr" + ]; + const methods = [ + "key", + "obj", + "use", + "optional", + "explicit", + "implicit", + "def", + "choice", + "any", + "contains" + ].concat(tags); + const overrided = [ + "_peekTag", + "_decodeTag", + "_use", + "_decodeStr", + "_decodeObjid", + "_decodeTime", + "_decodeNull", + "_decodeInt", + "_decodeBool", + "_decodeList", + "_encodeComposite", + "_encodeStr", + "_encodeObjid", + "_encodeTime", + "_encodeNull", + "_encodeInt", + "_encodeBool" + ]; + function Node3(enc, parent, name) { + const state2 = {}; + this._baseState = state2; + state2.name = name; + state2.enc = enc; + state2.parent = parent || null; + state2.children = null; + state2.tag = null; + state2.args = null; + state2.reverseArgs = null; + state2.choice = null; + state2.optional = false; + state2.any = false; + state2.obj = false; + state2.use = null; + state2.useDecoder = null; + state2.key = null; + state2["default"] = null; + state2.explicit = null; + state2.implicit = null; + state2.contains = null; + if (!state2.parent) { + state2.children = []; + this._wrap(); + } + } + node = Node3; + const stateProps = [ + "enc", + "parent", + "children", + "tag", + "args", + "reverseArgs", + "choice", + "optional", + "any", + "obj", + "use", + "alteredUse", + "key", + "default", + "explicit", + "implicit", + "contains" + ]; + Node3.prototype.clone = function clone() { + const state2 = this._baseState; + const cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state2[prop]; + }); + const res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; + }; + Node3.prototype._wrap = function wrap() { + const state2 = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + const clone = new this.constructor(this); + state2.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); + }; + Node3.prototype._init = function init(body) { + const state2 = this._baseState; + assert2(state2.parent === null); + body.call(this); + state2.children = state2.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert2.equal(state2.children.length, 1, "Root node can have only one child"); + }; + Node3.prototype._useArgs = function useArgs(args) { + const state2 = this._baseState; + const children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + if (children.length !== 0) { + assert2(state2.children === null); + state2.children = children; + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert2(state2.args === null); + state2.args = args; + state2.reverseArgs = args.map(function(arg) { + if (typeof arg !== "object" || arg.constructor !== Object) + return arg; + const res = {}; + Object.keys(arg).forEach(function(key2) { + if (key2 == (key2 | 0)) + key2 |= 0; + const value = arg[key2]; + res[value] = key2; + }); + return res; + }); + } + }; + overrided.forEach(function(method) { + Node3.prototype[method] = function _overrided() { + const state2 = this._baseState; + throw new Error(method + " not implemented for encoding: " + state2.enc); + }; + }); + tags.forEach(function(tag) { + Node3.prototype[tag] = function _tagMethod() { + const state2 = this._baseState; + const args = Array.prototype.slice.call(arguments); + assert2(state2.tag === null); + state2.tag = tag; + this._useArgs(args); + return this; + }; + }); + Node3.prototype.use = function use(item) { + assert2(item); + const state2 = this._baseState; + assert2(state2.use === null); + state2.use = item; + return this; + }; + Node3.prototype.optional = function optional() { + const state2 = this._baseState; + state2.optional = true; + return this; + }; + Node3.prototype.def = function def(val) { + const state2 = this._baseState; + assert2(state2["default"] === null); + state2["default"] = val; + state2.optional = true; + return this; + }; + Node3.prototype.explicit = function explicit(num) { + const state2 = this._baseState; + assert2(state2.explicit === null && state2.implicit === null); + state2.explicit = num; + return this; + }; + Node3.prototype.implicit = function implicit(num) { + const state2 = this._baseState; + assert2(state2.explicit === null && state2.implicit === null); + state2.implicit = num; + return this; + }; + Node3.prototype.obj = function obj() { + const state2 = this._baseState; + const args = Array.prototype.slice.call(arguments); + state2.obj = true; + if (args.length !== 0) + this._useArgs(args); + return this; + }; + Node3.prototype.key = function key2(newKey) { + const state2 = this._baseState; + assert2(state2.key === null); + state2.key = newKey; + return this; + }; + Node3.prototype.any = function any() { + const state2 = this._baseState; + state2.any = true; + return this; + }; + Node3.prototype.choice = function choice(obj) { + const state2 = this._baseState; + assert2(state2.choice === null); + state2.choice = obj; + this._useArgs(Object.keys(obj).map(function(key2) { + return obj[key2]; + })); + return this; + }; + Node3.prototype.contains = function contains(item) { + const state2 = this._baseState; + assert2(state2.use === null); + state2.contains = item; + return this; + }; + Node3.prototype._decode = function decode(input, options2) { + const state2 = this._baseState; + if (state2.parent === null) + return input.wrapResult(state2.children[0]._decode(input, options2)); + let result = state2["default"]; + let present = true; + let prevKey = null; + if (state2.key !== null) + prevKey = input.enterKey(state2.key); + if (state2.optional) { + let tag = null; + if (state2.explicit !== null) + tag = state2.explicit; + else if (state2.implicit !== null) + tag = state2.implicit; + else if (state2.tag !== null) + tag = state2.tag; + if (tag === null && !state2.any) { + const save = input.save(); + try { + if (state2.choice === null) + this._decodeGeneric(state2.tag, input, options2); + else + this._decodeChoice(input, options2); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state2.any); + if (input.isError(present)) + return present; + } + } + let prevObj; + if (state2.obj && present) + prevObj = input.enterObject(); + if (present) { + if (state2.explicit !== null) { + const explicit = this._decodeTag(input, state2.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + const start = input.offset; + if (state2.use === null && state2.choice === null) { + let save; + if (state2.any) + save = input.save(); + const body = this._decodeTag( + input, + state2.implicit !== null ? state2.implicit : state2.tag, + state2.any + ); + if (input.isError(body)) + return body; + if (state2.any) + result = input.raw(save); + else + input = body; + } + if (options2 && options2.track && state2.tag !== null) + options2.track(input.path(), start, input.length, "tagged"); + if (options2 && options2.track && state2.tag !== null) + options2.track(input.path(), input.offset, input.length, "content"); + if (state2.any) ; + else if (state2.choice === null) { + result = this._decodeGeneric(state2.tag, input, options2); + } else { + result = this._decodeChoice(input, options2); + } + if (input.isError(result)) + return result; + if (!state2.any && state2.choice === null && state2.children !== null) { + state2.children.forEach(function decodeChildren(child) { + child._decode(input, options2); + }); + } + if (state2.contains && (state2.tag === "octstr" || state2.tag === "bitstr")) { + const data2 = new DecoderBuffer(result); + result = this._getUse(state2.contains, input._reporterState.obj)._decode(data2, options2); + } + } + if (state2.obj && present) + result = input.leaveObject(prevObj); + if (state2.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state2.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); + return result; + }; + Node3.prototype._decodeGeneric = function decodeGeneric(tag, input, options2) { + const state2 = this._baseState; + if (tag === "seq" || tag === "set") + return null; + if (tag === "seqof" || tag === "setof") + return this._decodeList(input, tag, state2.args[0], options2); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options2); + else if (tag === "objid" && state2.args) + return this._decodeObjid(input, state2.args[0], state2.args[1], options2); + else if (tag === "objid") + return this._decodeObjid(input, null, null, options2); + else if (tag === "gentime" || tag === "utctime") + return this._decodeTime(input, tag, options2); + else if (tag === "null_") + return this._decodeNull(input, options2); + else if (tag === "bool") + return this._decodeBool(input, options2); + else if (tag === "objDesc") + return this._decodeStr(input, tag, options2); + else if (tag === "int" || tag === "enum") + return this._decodeInt(input, state2.args && state2.args[0], options2); + if (state2.use !== null) { + return this._getUse(state2.use, input._reporterState.obj)._decode(input, options2); + } else { + return input.error("unknown tag: " + tag); + } + }; + Node3.prototype._getUse = function _getUse(entity, obj) { + const state2 = this._baseState; + state2.useDecoder = this._use(entity, obj); + assert2(state2.useDecoder._baseState.parent === null); + state2.useDecoder = state2.useDecoder._baseState.children[0]; + if (state2.implicit !== state2.useDecoder._baseState.implicit) { + state2.useDecoder = state2.useDecoder.clone(); + state2.useDecoder._baseState.implicit = state2.implicit; + } + return state2.useDecoder; + }; + Node3.prototype._decodeChoice = function decodeChoice(input, options2) { + const state2 = this._baseState; + let result = null; + let match = false; + Object.keys(state2.choice).some(function(key2) { + const save = input.save(); + const node2 = state2.choice[key2]; + try { + const value = node2._decode(input, options2); + if (input.isError(value)) + return false; + result = { type: key2, value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + if (!match) + return input.error("Choice not matched"); + return result; + }; + Node3.prototype._createEncoderBuffer = function createEncoderBuffer(data2) { + return new EncoderBuffer(data2, this.reporter); + }; + Node3.prototype._encode = function encode(data2, reporter2, parent) { + const state2 = this._baseState; + if (state2["default"] !== null && state2["default"] === data2) + return; + const result = this._encodeValue(data2, reporter2, parent); + if (result === void 0) + return; + if (this._skipDefault(result, reporter2, parent)) + return; + return result; + }; + Node3.prototype._encodeValue = function encode(data2, reporter2, parent) { + const state2 = this._baseState; + if (state2.parent === null) + return state2.children[0]._encode(data2, reporter2 || new Reporter()); + let result = null; + this.reporter = reporter2; + if (state2.optional && data2 === void 0) { + if (state2["default"] !== null) + data2 = state2["default"]; + else + return; + } + let content = null; + let primitive = false; + if (state2.any) { + result = this._createEncoderBuffer(data2); + } else if (state2.choice) { + result = this._encodeChoice(data2, reporter2); + } else if (state2.contains) { + content = this._getUse(state2.contains, parent)._encode(data2, reporter2); + primitive = true; + } else if (state2.children) { + content = state2.children.map(function(child) { + if (child._baseState.tag === "null_") + return child._encode(null, reporter2, data2); + if (child._baseState.key === null) + return reporter2.error("Child should have a key"); + const prevKey = reporter2.enterKey(child._baseState.key); + if (typeof data2 !== "object") + return reporter2.error("Child expected, but input is not object"); + const res = child._encode(data2[child._baseState.key], reporter2, data2); + reporter2.leaveKey(prevKey); + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state2.tag === "seqof" || state2.tag === "setof") { + if (!(state2.args && state2.args.length === 1)) + return reporter2.error("Too many args for : " + state2.tag); + if (!Array.isArray(data2)) + return reporter2.error("seqof/setof, but data is not Array"); + const child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data2.map(function(item) { + const state3 = this._baseState; + return this._getUse(state3.args[0], data2)._encode(item, reporter2); + }, child)); + } else if (state2.use !== null) { + result = this._getUse(state2.use, parent)._encode(data2, reporter2); + } else { + content = this._encodePrimitive(state2.tag, data2); + primitive = true; + } + } + if (!state2.any && state2.choice === null) { + const tag = state2.implicit !== null ? state2.implicit : state2.tag; + const cls = state2.implicit === null ? "universal" : "context"; + if (tag === null) { + if (state2.use === null) + reporter2.error("Tag could be omitted only for .use()"); + } else { + if (state2.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + if (state2.explicit !== null) + result = this._encodeComposite(state2.explicit, false, "context", result); + return result; + }; + Node3.prototype._encodeChoice = function encodeChoice(data2, reporter2) { + const state2 = this._baseState; + const node2 = state2.choice[data2.type]; + if (!node2) { + assert2( + false, + data2.type + " not found in " + JSON.stringify(Object.keys(state2.choice)) + ); + } + return node2._encode(data2.value, reporter2); + }; + Node3.prototype._encodePrimitive = function encodePrimitive(tag, data2) { + const state2 = this._baseState; + if (/str$/.test(tag)) + return this._encodeStr(data2, tag); + else if (tag === "objid" && state2.args) + return this._encodeObjid(data2, state2.reverseArgs[0], state2.args[1]); + else if (tag === "objid") + return this._encodeObjid(data2, null, null); + else if (tag === "gentime" || tag === "utctime") + return this._encodeTime(data2, tag); + else if (tag === "null_") + return this._encodeNull(); + else if (tag === "int" || tag === "enum") + return this._encodeInt(data2, state2.args && state2.reverseArgs[0]); + else if (tag === "bool") + return this._encodeBool(data2); + else if (tag === "objDesc") + return this._encodeStr(data2, tag); + else + throw new Error("Unsupported tag: " + tag); + }; + Node3.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); + }; + Node3.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); + }; + return node; +} +var der = {}; +var hasRequiredDer$2; +function requireDer$2() { + if (hasRequiredDer$2) return der; + hasRequiredDer$2 = 1; + (function(exports) { + function reverse(map2) { + const res = {}; + Object.keys(map2).forEach(function(key2) { + if ((key2 | 0) == key2) + key2 = key2 | 0; + const value = map2[key2]; + res[value] = key2; + }); + return res; + } + exports.tagClass = { + 0: "universal", + 1: "application", + 2: "context", + 3: "private" + }; + exports.tagClassByName = reverse(exports.tagClass); + exports.tag = { + 0: "end", + 1: "bool", + 2: "int", + 3: "bitstr", + 4: "octstr", + 5: "null_", + 6: "objid", + 7: "objDesc", + 8: "external", + 9: "real", + 10: "enum", + 11: "embed", + 12: "utf8str", + 13: "relativeOid", + 16: "seq", + 17: "set", + 18: "numstr", + 19: "printstr", + 20: "t61str", + 21: "videostr", + 22: "ia5str", + 23: "utctime", + 24: "gentime", + 25: "graphstr", + 26: "iso646str", + 27: "genstr", + 28: "unistr", + 29: "charstr", + 30: "bmpstr" + }; + exports.tagByName = reverse(exports.tag); + })(der); + return der; +} +var der_1$1; +var hasRequiredDer$1; +function requireDer$1() { + if (hasRequiredDer$1) return der_1$1; + hasRequiredDer$1 = 1; + const inherits = requireInherits_browser$1(); + const Buffer2 = requireSafer().Buffer; + const Node3 = requireNode(); + const der2 = requireDer$2(); + function DEREncoder(entity) { + this.enc = "der"; + this.name = entity.name; + this.entity = entity; + this.tree = new DERNode(); + this.tree._init(entity.body); + } + der_1$1 = DEREncoder; + DEREncoder.prototype.encode = function encode(data2, reporter2) { + return this.tree._encode(data2, reporter2).join(); + }; + function DERNode(parent) { + Node3.call(this, "der", parent); + } + inherits(DERNode, Node3); + DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { + const encodedTag = encodeTag(tag, primitive, cls, this.reporter); + if (content.length < 128) { + const header2 = Buffer2.alloc(2); + header2[0] = encodedTag; + header2[1] = content.length; + return this._createEncoderBuffer([header2, content]); + } + let lenOctets = 1; + for (let i = content.length; i >= 256; i >>= 8) + lenOctets++; + const header = Buffer2.alloc(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 128 | lenOctets; + for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 255; + return this._createEncoderBuffer([header, content]); + }; + DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === "bitstr") { + return this._createEncoderBuffer([str.unused | 0, str.data]); + } else if (tag === "bmpstr") { + const buf = Buffer2.alloc(str.length * 2); + for (let i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === "numstr") { + if (!this._isNumstr(str)) { + return this.reporter.error("Encoding of string type: numstr supports only digits and space"); + } + return this._createEncoderBuffer(str); + } else if (tag === "printstr") { + if (!this._isPrintstr(str)) { + return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === "objDesc") { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error("Encoding of string type: " + tag + " unsupported"); + } + }; + DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === "string") { + if (!values) + return this.reporter.error("string objid given, but no values map found"); + if (!values.hasOwnProperty(id)) + return this.reporter.error("objid not found in values map"); + id = values[id].split(/[\s.]+/g); + for (let i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (let i = 0; i < id.length; i++) + id[i] |= 0; + } + if (!Array.isArray(id)) { + return this.reporter.error("objid() should be either array or string, got: " + JSON.stringify(id)); + } + if (!relative) { + if (id[1] >= 40) + return this.reporter.error("Second objid identifier OOB"); + id.splice(0, 2, id[0] * 40 + id[1]); + } + let size = 0; + for (let i = 0; i < id.length; i++) { + let ident = id[i]; + for (size++; ident >= 128; ident >>= 7) + size++; + } + const objid = Buffer2.alloc(size); + let offset2 = objid.length - 1; + for (let i = id.length - 1; i >= 0; i--) { + let ident = id[i]; + objid[offset2--] = ident & 127; + while ((ident >>= 7) > 0) + objid[offset2--] = 128 | ident & 127; + } + return this._createEncoderBuffer(objid); + }; + function two(num) { + if (num < 10) + return "0" + num; + else + return num; + } + DERNode.prototype._encodeTime = function encodeTime(time, tag) { + let str; + const date = new Date(time); + if (tag === "gentime") { + str = [ + two(date.getUTCFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + "Z" + ].join(""); + } else if (tag === "utctime") { + str = [ + two(date.getUTCFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + "Z" + ].join(""); + } else { + this.reporter.error("Encoding " + tag + " time is not supported yet"); + } + return this._encodeStr(str, "octstr"); + }; + DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(""); + }; + DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === "string") { + if (!values) + return this.reporter.error("String int or enum given, but no values map"); + if (!values.hasOwnProperty(num)) { + return this.reporter.error("Values map doesn't contain: " + JSON.stringify(num)); + } + num = values[num]; + } + if (typeof num !== "number" && !Buffer2.isBuffer(num)) { + const numArray = num.toArray(); + if (!num.sign && numArray[0] & 128) { + numArray.unshift(0); + } + num = Buffer2.from(numArray); + } + if (Buffer2.isBuffer(num)) { + let size2 = num.length; + if (num.length === 0) + size2++; + const out2 = Buffer2.alloc(size2); + num.copy(out2); + if (num.length === 0) + out2[0] = 0; + return this._createEncoderBuffer(out2); + } + if (num < 128) + return this._createEncoderBuffer(num); + if (num < 256) + return this._createEncoderBuffer([0, num]); + let size = 1; + for (let i = num; i >= 256; i >>= 8) + size++; + const out = new Array(size); + for (let i = out.length - 1; i >= 0; i--) { + out[i] = num & 255; + num >>= 8; + } + if (out[0] & 128) { + out.unshift(0); + } + return this._createEncoderBuffer(Buffer2.from(out)); + }; + DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 255 : 0); + }; + DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === "function") + entity = entity(obj); + return entity._getEncoder("der").tree; + }; + DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter2, parent) { + const state2 = this._baseState; + let i; + if (state2["default"] === null) + return false; + const data2 = dataBuffer.join(); + if (state2.defaultBuffer === void 0) + state2.defaultBuffer = this._encodeValue(state2["default"], reporter2, parent).join(); + if (data2.length !== state2.defaultBuffer.length) + return false; + for (i = 0; i < data2.length; i++) + if (data2[i] !== state2.defaultBuffer[i]) + return false; + return true; + }; + function encodeTag(tag, primitive, cls, reporter2) { + let res; + if (tag === "seqof") + tag = "seq"; + else if (tag === "setof") + tag = "set"; + if (der2.tagByName.hasOwnProperty(tag)) + res = der2.tagByName[tag]; + else if (typeof tag === "number" && (tag | 0) === tag) + res = tag; + else + return reporter2.error("Unknown tag: " + tag); + if (res >= 31) + return reporter2.error("Multi-octet tag encoding unsupported"); + if (!primitive) + res |= 32; + res |= der2.tagClassByName[cls || "universal"] << 6; + return res; + } + return der_1$1; +} +var pem$1; +var hasRequiredPem$1; +function requirePem$1() { + if (hasRequiredPem$1) return pem$1; + hasRequiredPem$1 = 1; + const inherits = requireInherits_browser$1(); + const DEREncoder = requireDer$1(); + function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = "pem"; + } + inherits(PEMEncoder, DEREncoder); + pem$1 = PEMEncoder; + PEMEncoder.prototype.encode = function encode(data2, options2) { + const buf = DEREncoder.prototype.encode.call(this, data2); + const p = buf.toString("base64"); + const out = ["-----BEGIN " + options2.label + "-----"]; + for (let i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push("-----END " + options2.label + "-----"); + return out.join("\n"); + }; + return pem$1; +} +var hasRequiredEncoders; +function requireEncoders() { + if (hasRequiredEncoders) return encoders; + hasRequiredEncoders = 1; + (function(exports) { + const encoders2 = exports; + encoders2.der = requireDer$1(); + encoders2.pem = requirePem$1(); + })(encoders); + return encoders; +} +var decoders = {}; +var der_1; +var hasRequiredDer; +function requireDer() { + if (hasRequiredDer) return der_1; + hasRequiredDer = 1; + const inherits = requireInherits_browser$1(); + const bignum = requireBn$2(); + const DecoderBuffer = requireBuffer().DecoderBuffer; + const Node3 = requireNode(); + const der2 = requireDer$2(); + function DERDecoder(entity) { + this.enc = "der"; + this.name = entity.name; + this.entity = entity; + this.tree = new DERNode(); + this.tree._init(entity.body); + } + der_1 = DERDecoder; + DERDecoder.prototype.decode = function decode(data2, options2) { + if (!DecoderBuffer.isDecoderBuffer(data2)) { + data2 = new DecoderBuffer(data2, options2); + } + return this.tree._decode(data2, options2); + }; + function DERNode(parent) { + Node3.call(this, "der", parent); + } + inherits(DERNode, Node3); + DERNode.prototype._peekTag = function peekTag(buffer2, tag, any) { + if (buffer2.isEmpty()) + return false; + const state2 = buffer2.save(); + const decodedTag = derDecodeTag(buffer2, 'Failed to peek tag: "' + tag + '"'); + if (buffer2.isError(decodedTag)) + return decodedTag; + buffer2.restore(state2); + return decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + "of" === tag || any; + }; + DERNode.prototype._decodeTag = function decodeTag(buffer2, tag, any) { + const decodedTag = derDecodeTag( + buffer2, + 'Failed to decode tag of "' + tag + '"' + ); + if (buffer2.isError(decodedTag)) + return decodedTag; + let len = derDecodeLen( + buffer2, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"' + ); + if (buffer2.isError(len)) + return len; + if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + "of" !== tag) { + return buffer2.error('Failed to match tag: "' + tag + '"'); + } + if (decodedTag.primitive || len !== null) + return buffer2.skip(len, 'Failed to match body of: "' + tag + '"'); + const state2 = buffer2.save(); + const res = this._skipUntilEnd( + buffer2, + 'Failed to skip indefinite length body: "' + this.tag + '"' + ); + if (buffer2.isError(res)) + return res; + len = buffer2.offset - state2.offset; + buffer2.restore(state2); + return buffer2.skip(len, 'Failed to match body of: "' + tag + '"'); + }; + DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer2, fail) { + for (; ; ) { + const tag = derDecodeTag(buffer2, fail); + if (buffer2.isError(tag)) + return tag; + const len = derDecodeLen(buffer2, tag.primitive, fail); + if (buffer2.isError(len)) + return len; + let res; + if (tag.primitive || len !== null) + res = buffer2.skip(len); + else + res = this._skipUntilEnd(buffer2, fail); + if (buffer2.isError(res)) + return res; + if (tag.tagStr === "end") + break; + } + }; + DERNode.prototype._decodeList = function decodeList(buffer2, tag, decoder2, options2) { + const result = []; + while (!buffer2.isEmpty()) { + const possibleEnd = this._peekTag(buffer2, "end"); + if (buffer2.isError(possibleEnd)) + return possibleEnd; + const res = decoder2.decode(buffer2, "der", options2); + if (buffer2.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; + }; + DERNode.prototype._decodeStr = function decodeStr(buffer2, tag) { + if (tag === "bitstr") { + const unused = buffer2.readUInt8(); + if (buffer2.isError(unused)) + return unused; + return { unused, data: buffer2.raw() }; + } else if (tag === "bmpstr") { + const raw = buffer2.raw(); + if (raw.length % 2 === 1) + return buffer2.error("Decoding of string type: bmpstr length mismatch"); + let str = ""; + for (let i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === "numstr") { + const numstr = buffer2.raw().toString("ascii"); + if (!this._isNumstr(numstr)) { + return buffer2.error("Decoding of string type: numstr unsupported characters"); + } + return numstr; + } else if (tag === "octstr") { + return buffer2.raw(); + } else if (tag === "objDesc") { + return buffer2.raw(); + } else if (tag === "printstr") { + const printstr = buffer2.raw().toString("ascii"); + if (!this._isPrintstr(printstr)) { + return buffer2.error("Decoding of string type: printstr unsupported characters"); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer2.raw().toString(); + } else { + return buffer2.error("Decoding of string type: " + tag + " unsupported"); + } + }; + DERNode.prototype._decodeObjid = function decodeObjid(buffer2, values, relative) { + let result; + const identifiers = []; + let ident = 0; + let subident = 0; + while (!buffer2.isEmpty()) { + subident = buffer2.readUInt8(); + ident <<= 7; + ident |= subident & 127; + if ((subident & 128) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 128) + identifiers.push(ident); + const first = identifiers[0] / 40 | 0; + const second = identifiers[0] % 40; + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + if (values) { + let tmp = values[result.join(" ")]; + if (tmp === void 0) + tmp = values[result.join(".")]; + if (tmp !== void 0) + result = tmp; + } + return result; + }; + DERNode.prototype._decodeTime = function decodeTime(buffer2, tag) { + const str = buffer2.raw().toString(); + let year; + let mon; + let day; + let hour; + let min2; + let sec; + if (tag === "gentime") { + year = str.slice(0, 4) | 0; + mon = str.slice(4, 6) | 0; + day = str.slice(6, 8) | 0; + hour = str.slice(8, 10) | 0; + min2 = str.slice(10, 12) | 0; + sec = str.slice(12, 14) | 0; + } else if (tag === "utctime") { + year = str.slice(0, 2) | 0; + mon = str.slice(2, 4) | 0; + day = str.slice(4, 6) | 0; + hour = str.slice(6, 8) | 0; + min2 = str.slice(8, 10) | 0; + sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2e3 + year; + else + year = 1900 + year; + } else { + return buffer2.error("Decoding " + tag + " time is not supported yet"); + } + return Date.UTC(year, mon - 1, day, hour, min2, sec, 0); + }; + DERNode.prototype._decodeNull = function decodeNull() { + return null; + }; + DERNode.prototype._decodeBool = function decodeBool(buffer2) { + const res = buffer2.readUInt8(); + if (buffer2.isError(res)) + return res; + else + return res !== 0; + }; + DERNode.prototype._decodeInt = function decodeInt(buffer2, values) { + const raw = buffer2.raw(); + let res = new bignum(raw); + if (values) + res = values[res.toString(10)] || res; + return res; + }; + DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === "function") + entity = entity(obj); + return entity._getDecoder("der").tree; + }; + function derDecodeTag(buf, fail) { + let tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + const cls = der2.tagClass[tag >> 6]; + const primitive = (tag & 32) === 0; + if ((tag & 31) === 31) { + let oct = tag; + tag = 0; + while ((oct & 128) === 128) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + tag <<= 7; + tag |= oct & 127; + } + } else { + tag &= 31; + } + const tagStr = der2.tag[tag]; + return { + cls, + primitive, + tag, + tagStr + }; + } + function derDecodeLen(buf, primitive, fail) { + let len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + if (!primitive && len === 128) + return null; + if ((len & 128) === 0) { + return len; + } + const num = len & 127; + if (num > 4) + return buf.error("length octect is too long"); + len = 0; + for (let i = 0; i < num; i++) { + len <<= 8; + const j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + return len; + } + return der_1; +} +var pem; +var hasRequiredPem; +function requirePem() { + if (hasRequiredPem) return pem; + hasRequiredPem = 1; + const inherits = requireInherits_browser$1(); + const Buffer2 = requireSafer().Buffer; + const DERDecoder = requireDer(); + function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = "pem"; + } + inherits(PEMDecoder, DERDecoder); + pem = PEMDecoder; + PEMDecoder.prototype.decode = function decode(data2, options2) { + const lines = data2.toString().split(/[\r\n]+/g); + const label = options2.label.toUpperCase(); + const re2 = /^-----(BEGIN|END) ([^-]+)-----$/; + let start = -1; + let end = -1; + for (let i = 0; i < lines.length; i++) { + const match = lines[i].match(re2); + if (match === null) + continue; + if (match[2] !== label) + continue; + if (start === -1) { + if (match[1] !== "BEGIN") + break; + start = i; + } else { + if (match[1] !== "END") + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error("PEM section not found for: " + label); + const base64 = lines.slice(start + 1, end).join(""); + base64.replace(/[^a-z0-9+/=]+/gi, ""); + const input = Buffer2.from(base64, "base64"); + return DERDecoder.prototype.decode.call(this, input, options2); + }; + return pem; +} +var hasRequiredDecoders; +function requireDecoders() { + if (hasRequiredDecoders) return decoders; + hasRequiredDecoders = 1; + (function(exports) { + const decoders2 = exports; + decoders2.der = requireDer(); + decoders2.pem = requirePem(); + })(decoders); + return decoders; +} +var hasRequiredApi; +function requireApi() { + if (hasRequiredApi) return api; + hasRequiredApi = 1; + (function(exports) { + const encoders2 = requireEncoders(); + const decoders2 = requireDecoders(); + const inherits = requireInherits_browser$1(); + const api2 = exports; + api2.define = function define(name, body) { + return new Entity(name, body); + }; + function Entity(name, body) { + this.name = name; + this.body = body; + this.decoders = {}; + this.encoders = {}; + } + Entity.prototype._createNamed = function createNamed(Base) { + const name = this.name; + function Generated(entity) { + this._initNamed(entity, name); + } + inherits(Generated, Base); + Generated.prototype._initNamed = function _initNamed(entity, name2) { + Base.call(this, entity, name2); + }; + return new Generated(this); + }; + Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || "der"; + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(decoders2[enc]); + return this.decoders[enc]; + }; + Entity.prototype.decode = function decode(data2, enc, options2) { + return this._getDecoder(enc).decode(data2, options2); + }; + Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || "der"; + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(encoders2[enc]); + return this.encoders[enc]; + }; + Entity.prototype.encode = function encode(data2, enc, reporter2) { + return this._getEncoder(enc).encode(data2, reporter2); + }; + })(api); + return api; +} +var base$1 = {}; +var hasRequiredBase; +function requireBase() { + if (hasRequiredBase) return base$1; + hasRequiredBase = 1; + (function(exports) { + const base2 = exports; + base2.Reporter = requireReporter().Reporter; + base2.DecoderBuffer = requireBuffer().DecoderBuffer; + base2.EncoderBuffer = requireBuffer().EncoderBuffer; + base2.Node = requireNode(); + })(base$1); + return base$1; +} +var constants$5 = {}; +var hasRequiredConstants$5; +function requireConstants$5() { + if (hasRequiredConstants$5) return constants$5; + hasRequiredConstants$5 = 1; + (function(exports) { + const constants2 = exports; + constants2._reverse = function reverse(map2) { + const res = {}; + Object.keys(map2).forEach(function(key2) { + if ((key2 | 0) == key2) + key2 = key2 | 0; + const value = map2[key2]; + res[value] = key2; + }); + return res; + }; + constants2.der = requireDer$2(); + })(constants$5); + return constants$5; +} +var hasRequiredAsn1$1; +function requireAsn1$1() { + if (hasRequiredAsn1$1) return asn1; + hasRequiredAsn1$1 = 1; + (function(exports) { + const asn12 = exports; + asn12.bignum = requireBn$2(); + asn12.define = requireApi().define; + asn12.base = requireBase(); + asn12.constants = requireConstants$5(); + asn12.decoders = requireDecoders(); + asn12.encoders = requireEncoders(); + })(asn1); + return asn1; +} +var certificate; +var hasRequiredCertificate; +function requireCertificate() { + if (hasRequiredCertificate) return certificate; + hasRequiredCertificate = 1; + var asn = requireAsn1$1(); + var Time = asn.define("Time", function() { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime() + }); + }); + var AttributeTypeValue = asn.define("AttributeTypeValue", function() { + this.seq().obj( + this.key("type").objid(), + this.key("value").any() + ); + }); + var AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function() { + this.seq().obj( + this.key("algorithm").objid(), + this.key("parameters").optional(), + this.key("curve").objid().optional() + ); + }); + var SubjectPublicKeyInfo = asn.define("SubjectPublicKeyInfo", function() { + this.seq().obj( + this.key("algorithm").use(AlgorithmIdentifier), + this.key("subjectPublicKey").bitstr() + ); + }); + var RelativeDistinguishedName = asn.define("RelativeDistinguishedName", function() { + this.setof(AttributeTypeValue); + }); + var RDNSequence = asn.define("RDNSequence", function() { + this.seqof(RelativeDistinguishedName); + }); + var Name = asn.define("Name", function() { + this.choice({ + rdnSequence: this.use(RDNSequence) + }); + }); + var Validity = asn.define("Validity", function() { + this.seq().obj( + this.key("notBefore").use(Time), + this.key("notAfter").use(Time) + ); + }); + var Extension = asn.define("Extension", function() { + this.seq().obj( + this.key("extnID").objid(), + this.key("critical").bool().def(false), + this.key("extnValue").octstr() + ); + }); + var TBSCertificate = asn.define("TBSCertificate", function() { + this.seq().obj( + this.key("version").explicit(0).int().optional(), + this.key("serialNumber").int(), + this.key("signature").use(AlgorithmIdentifier), + this.key("issuer").use(Name), + this.key("validity").use(Validity), + this.key("subject").use(Name), + this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo), + this.key("issuerUniqueID").implicit(1).bitstr().optional(), + this.key("subjectUniqueID").implicit(2).bitstr().optional(), + this.key("extensions").explicit(3).seqof(Extension).optional() + ); + }); + var X509Certificate = asn.define("X509Certificate", function() { + this.seq().obj( + this.key("tbsCertificate").use(TBSCertificate), + this.key("signatureAlgorithm").use(AlgorithmIdentifier), + this.key("signatureValue").bitstr() + ); + }); + certificate = X509Certificate; + return certificate; +} +var hasRequiredAsn1; +function requireAsn1() { + if (hasRequiredAsn1) return asn1$1; + hasRequiredAsn1 = 1; + var asn12 = requireAsn1$1(); + asn1$1.certificate = requireCertificate(); + var RSAPrivateKey = asn12.define("RSAPrivateKey", function() { + this.seq().obj( + this.key("version").int(), + this.key("modulus").int(), + this.key("publicExponent").int(), + this.key("privateExponent").int(), + this.key("prime1").int(), + this.key("prime2").int(), + this.key("exponent1").int(), + this.key("exponent2").int(), + this.key("coefficient").int() + ); + }); + asn1$1.RSAPrivateKey = RSAPrivateKey; + var RSAPublicKey = asn12.define("RSAPublicKey", function() { + this.seq().obj( + this.key("modulus").int(), + this.key("publicExponent").int() + ); + }); + asn1$1.RSAPublicKey = RSAPublicKey; + var PublicKey = asn12.define("SubjectPublicKeyInfo", function() { + this.seq().obj( + this.key("algorithm").use(AlgorithmIdentifier), + this.key("subjectPublicKey").bitstr() + ); + }); + asn1$1.PublicKey = PublicKey; + var AlgorithmIdentifier = asn12.define("AlgorithmIdentifier", function() { + this.seq().obj( + this.key("algorithm").objid(), + this.key("none").null_().optional(), + this.key("curve").objid().optional(), + this.key("params").seq().obj( + this.key("p").int(), + this.key("q").int(), + this.key("g").int() + ).optional() + ); + }); + var PrivateKeyInfo = asn12.define("PrivateKeyInfo", function() { + this.seq().obj( + this.key("version").int(), + this.key("algorithm").use(AlgorithmIdentifier), + this.key("subjectPrivateKey").octstr() + ); + }); + asn1$1.PrivateKey = PrivateKeyInfo; + var EncryptedPrivateKeyInfo = asn12.define("EncryptedPrivateKeyInfo", function() { + this.seq().obj( + this.key("algorithm").seq().obj( + this.key("id").objid(), + this.key("decrypt").seq().obj( + this.key("kde").seq().obj( + this.key("id").objid(), + this.key("kdeparams").seq().obj( + this.key("salt").octstr(), + this.key("iters").int() + ) + ), + this.key("cipher").seq().obj( + this.key("algo").objid(), + this.key("iv").octstr() + ) + ) + ), + this.key("subjectPrivateKey").octstr() + ); + }); + asn1$1.EncryptedPrivateKey = EncryptedPrivateKeyInfo; + var DSAPrivateKey = asn12.define("DSAPrivateKey", function() { + this.seq().obj( + this.key("version").int(), + this.key("p").int(), + this.key("q").int(), + this.key("g").int(), + this.key("pub_key").int(), + this.key("priv_key").int() + ); + }); + asn1$1.DSAPrivateKey = DSAPrivateKey; + asn1$1.DSAparam = asn12.define("DSAparam", function() { + this.int(); + }); + var ECPrivateKey = asn12.define("ECPrivateKey", function() { + this.seq().obj( + this.key("version").int(), + this.key("privateKey").octstr(), + this.key("parameters").optional().explicit(0).use(ECParameters), + this.key("publicKey").optional().explicit(1).bitstr() + ); + }); + asn1$1.ECPrivateKey = ECPrivateKey; + var ECParameters = asn12.define("ECParameters", function() { + this.choice({ + namedCurve: this.objid() + }); + }); + asn1$1.signature = asn12.define("signature", function() { + this.seq().obj( + this.key("r").int(), + this.key("s").int() + ); + }); + return asn1$1; +} +const require$$1$3 = { + "2.16.840.1.101.3.4.1.1": "aes-128-ecb", + "2.16.840.1.101.3.4.1.2": "aes-128-cbc", + "2.16.840.1.101.3.4.1.3": "aes-128-ofb", + "2.16.840.1.101.3.4.1.4": "aes-128-cfb", + "2.16.840.1.101.3.4.1.21": "aes-192-ecb", + "2.16.840.1.101.3.4.1.22": "aes-192-cbc", + "2.16.840.1.101.3.4.1.23": "aes-192-ofb", + "2.16.840.1.101.3.4.1.24": "aes-192-cfb", + "2.16.840.1.101.3.4.1.41": "aes-256-ecb", + "2.16.840.1.101.3.4.1.42": "aes-256-cbc", + "2.16.840.1.101.3.4.1.43": "aes-256-ofb", + "2.16.840.1.101.3.4.1.44": "aes-256-cfb" +}; +var fixProc; +var hasRequiredFixProc; +function requireFixProc() { + if (hasRequiredFixProc) return fixProc; + hasRequiredFixProc = 1; + var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m; + var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m; + var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m; + var evp = requireEvp_bytestokey(); + var ciphers = requireBrowser$9(); + var Buffer2 = requireSafeBuffer().Buffer; + fixProc = function(okey, password) { + var key2 = okey.toString(); + var match = key2.match(findProc); + var decrypted; + if (!match) { + var match2 = key2.match(fullRegex); + decrypted = Buffer2.from(match2[2].replace(/[\r\n]/g, ""), "base64"); + } else { + var suite = "aes" + match[1]; + var iv = Buffer2.from(match[2], "hex"); + var cipherText = Buffer2.from(match[3].replace(/[\r\n]/g, ""), "base64"); + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key; + var out = []; + var cipher2 = ciphers.createDecipheriv(suite, cipherKey, iv); + out.push(cipher2.update(cipherText)); + out.push(cipher2.final()); + decrypted = Buffer2.concat(out); + } + var tag = key2.match(startRegex)[1]; + return { + tag, + data: decrypted + }; + }; + return fixProc; +} +var parseAsn1; +var hasRequiredParseAsn1; +function requireParseAsn1() { + if (hasRequiredParseAsn1) return parseAsn1; + hasRequiredParseAsn1 = 1; + var asn12 = requireAsn1(); + var aesid = require$$1$3; + var fixProc2 = requireFixProc(); + var ciphers = requireBrowser$9(); + var compat = requireBrowser$a(); + var Buffer2 = requireSafeBuffer().Buffer; + parseAsn1 = parseKeys; + function parseKeys(buffer2) { + var password; + if (typeof buffer2 === "object" && !Buffer2.isBuffer(buffer2)) { + password = buffer2.passphrase; + buffer2 = buffer2.key; + } + if (typeof buffer2 === "string") { + buffer2 = Buffer2.from(buffer2); + } + var stripped = fixProc2(buffer2, password); + var type2 = stripped.tag; + var data2 = stripped.data; + var subtype, ndata; + switch (type2) { + case "CERTIFICATE": + ndata = asn12.certificate.decode(data2, "der").tbsCertificate.subjectPublicKeyInfo; + // falls through + case "PUBLIC KEY": + if (!ndata) { + ndata = asn12.PublicKey.decode(data2, "der"); + } + subtype = ndata.algorithm.algorithm.join("."); + switch (subtype) { + case "1.2.840.113549.1.1.1": + return asn12.RSAPublicKey.decode(ndata.subjectPublicKey.data, "der"); + case "1.2.840.10045.2.1": + ndata.subjectPrivateKey = ndata.subjectPublicKey; + return { + type: "ec", + data: ndata + }; + case "1.2.840.10040.4.1": + ndata.algorithm.params.pub_key = asn12.DSAparam.decode(ndata.subjectPublicKey.data, "der"); + return { + type: "dsa", + data: ndata.algorithm.params + }; + default: + throw new Error("unknown key id " + subtype); + } + // throw new Error('unknown key type ' + type) + case "ENCRYPTED PRIVATE KEY": + data2 = asn12.EncryptedPrivateKey.decode(data2, "der"); + data2 = decrypt(data2, password); + // falls through + case "PRIVATE KEY": + ndata = asn12.PrivateKey.decode(data2, "der"); + subtype = ndata.algorithm.algorithm.join("."); + switch (subtype) { + case "1.2.840.113549.1.1.1": + return asn12.RSAPrivateKey.decode(ndata.subjectPrivateKey, "der"); + case "1.2.840.10045.2.1": + return { + curve: ndata.algorithm.curve, + privateKey: asn12.ECPrivateKey.decode(ndata.subjectPrivateKey, "der").privateKey + }; + case "1.2.840.10040.4.1": + ndata.algorithm.params.priv_key = asn12.DSAparam.decode(ndata.subjectPrivateKey, "der"); + return { + type: "dsa", + params: ndata.algorithm.params + }; + default: + throw new Error("unknown key id " + subtype); + } + // throw new Error('unknown key type ' + type) + case "RSA PUBLIC KEY": + return asn12.RSAPublicKey.decode(data2, "der"); + case "RSA PRIVATE KEY": + return asn12.RSAPrivateKey.decode(data2, "der"); + case "DSA PRIVATE KEY": + return { + type: "dsa", + params: asn12.DSAPrivateKey.decode(data2, "der") + }; + case "EC PRIVATE KEY": + data2 = asn12.ECPrivateKey.decode(data2, "der"); + return { + curve: data2.parameters.value, + privateKey: data2.privateKey + }; + default: + throw new Error("unknown key type " + type2); + } + } + parseKeys.signature = asn12.signature; + function decrypt(data2, password) { + var salt = data2.algorithm.decrypt.kde.kdeparams.salt; + var iters = parseInt(data2.algorithm.decrypt.kde.kdeparams.iters.toString(), 10); + var algo = aesid[data2.algorithm.decrypt.cipher.algo.join(".")]; + var iv = data2.algorithm.decrypt.cipher.iv; + var cipherText = data2.subjectPrivateKey; + var keylen = parseInt(algo.split("-")[1], 10) / 8; + var key2 = compat.pbkdf2Sync(password, salt, iters, keylen, "sha1"); + var cipher2 = ciphers.createDecipheriv(algo, key2, iv); + var out = []; + out.push(cipher2.update(cipherText)); + out.push(cipher2.final()); + return Buffer2.concat(out); + } + return parseAsn1; +} +const require$$4$1 = { + "1.3.132.0.10": "secp256k1", + "1.3.132.0.33": "p224", + "1.2.840.10045.3.1.1": "p192", + "1.2.840.10045.3.1.7": "p256", + "1.3.132.0.34": "p384", + "1.3.132.0.35": "p521" +}; +var hasRequiredSign; +function requireSign() { + if (hasRequiredSign) return sign.exports; + hasRequiredSign = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var createHmac = requireBrowser$b(); + var crt = requireBrowserifyRsa(); + var EC = requireElliptic().ec; + var BN = requireBn$4(); + var parseKeys = requireParseAsn1(); + var curves2 = require$$4$1; + function sign$12(hash2, key2, hashType, signType, tag) { + var priv = parseKeys(key2); + if (priv.curve) { + if (signType !== "ecdsa" && signType !== "ecdsa/rsa") throw new Error("wrong private key type"); + return ecSign(hash2, priv); + } else if (priv.type === "dsa") { + if (signType !== "dsa") throw new Error("wrong private key type"); + return dsaSign(hash2, priv, hashType); + } else { + if (signType !== "rsa" && signType !== "ecdsa/rsa") throw new Error("wrong private key type"); + } + hash2 = Buffer2.concat([tag, hash2]); + var len = priv.modulus.byteLength(); + var pad = [0, 1]; + while (hash2.length + pad.length + 1 < len) pad.push(255); + pad.push(0); + var i = -1; + while (++i < hash2.length) pad.push(hash2[i]); + var out = crt(pad, priv); + return out; + } + function ecSign(hash2, priv) { + var curveId = curves2[priv.curve.join(".")]; + if (!curveId) throw new Error("unknown curve " + priv.curve.join(".")); + var curve2 = new EC(curveId); + var key2 = curve2.keyFromPrivate(priv.privateKey); + var out = key2.sign(hash2); + return Buffer2.from(out.toDER()); + } + function dsaSign(hash2, priv, algo) { + var x = priv.params.priv_key; + var p = priv.params.p; + var q = priv.params.q; + var g = priv.params.g; + var r = new BN(0); + var k; + var H = bits2int(hash2, q).mod(q); + var s = false; + var kv = getKey(x, q, hash2, algo); + while (s === false) { + k = makeKey(q, kv, algo); + r = makeR(g, k, p, q); + s = k.invm(q).imul(H.add(x.mul(r))).mod(q); + if (s.cmpn(0) === 0) { + s = false; + r = new BN(0); + } + } + return toDER(r, s); + } + function toDER(r, s) { + r = r.toArray(); + s = s.toArray(); + if (r[0] & 128) r = [0].concat(r); + if (s[0] & 128) s = [0].concat(s); + var total = r.length + s.length + 4; + var res = [48, total, 2, r.length]; + res = res.concat(r, [2, s.length], s); + return Buffer2.from(res); + } + function getKey(x, q, hash2, algo) { + x = Buffer2.from(x.toArray()); + if (x.length < q.byteLength()) { + var zeros = Buffer2.alloc(q.byteLength() - x.length); + x = Buffer2.concat([zeros, x]); + } + var hlen = hash2.length; + var hbits = bits2octets(hash2, q); + var v = Buffer2.alloc(hlen); + v.fill(1); + var k = Buffer2.alloc(hlen); + k = createHmac(algo, k).update(v).update(Buffer2.from([0])).update(x).update(hbits).digest(); + v = createHmac(algo, k).update(v).digest(); + k = createHmac(algo, k).update(v).update(Buffer2.from([1])).update(x).update(hbits).digest(); + v = createHmac(algo, k).update(v).digest(); + return { k, v }; + } + function bits2int(obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) bits.ishrn(shift); + return bits; + } + function bits2octets(bits, q) { + bits = bits2int(bits, q); + bits = bits.mod(q); + var out = Buffer2.from(bits.toArray()); + if (out.length < q.byteLength()) { + var zeros = Buffer2.alloc(q.byteLength() - out.length); + out = Buffer2.concat([zeros, out]); + } + return out; + } + function makeKey(q, kv, algo) { + var t; + var k; + do { + t = Buffer2.alloc(0); + while (t.length * 8 < q.bitLength()) { + kv.v = createHmac(algo, kv.k).update(kv.v).digest(); + t = Buffer2.concat([t, kv.v]); + } + k = bits2int(t, q); + kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer2.from([0])).digest(); + kv.v = createHmac(algo, kv.k).update(kv.v).digest(); + } while (k.cmp(q) !== -1); + return k; + } + function makeR(g, k, p, q) { + return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + } + sign.exports = sign$12; + sign.exports.getKey = getKey; + sign.exports.makeKey = makeKey; + return sign.exports; +} +var verify_1; +var hasRequiredVerify; +function requireVerify() { + if (hasRequiredVerify) return verify_1; + hasRequiredVerify = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var BN = requireBn$4(); + var EC = requireElliptic().ec; + var parseKeys = requireParseAsn1(); + var curves2 = require$$4$1; + function verify(sig, hash2, key2, signType, tag) { + var pub = parseKeys(key2); + if (pub.type === "ec") { + if (signType !== "ecdsa" && signType !== "ecdsa/rsa") throw new Error("wrong public key type"); + return ecVerify(sig, hash2, pub); + } else if (pub.type === "dsa") { + if (signType !== "dsa") throw new Error("wrong public key type"); + return dsaVerify(sig, hash2, pub); + } else { + if (signType !== "rsa" && signType !== "ecdsa/rsa") throw new Error("wrong public key type"); + } + hash2 = Buffer2.concat([tag, hash2]); + var len = pub.modulus.byteLength(); + var pad = [1]; + var padNum = 0; + while (hash2.length + pad.length + 2 < len) { + pad.push(255); + padNum++; + } + pad.push(0); + var i = -1; + while (++i < hash2.length) { + pad.push(hash2[i]); + } + pad = Buffer2.from(pad); + var red = BN.mont(pub.modulus); + sig = new BN(sig).toRed(red); + sig = sig.redPow(new BN(pub.publicExponent)); + sig = Buffer2.from(sig.fromRed().toArray()); + var out = padNum < 8 ? 1 : 0; + len = Math.min(sig.length, pad.length); + if (sig.length !== pad.length) out = 1; + i = -1; + while (++i < len) out |= sig[i] ^ pad[i]; + return out === 0; + } + function ecVerify(sig, hash2, pub) { + var curveId = curves2[pub.data.algorithm.curve.join(".")]; + if (!curveId) throw new Error("unknown curve " + pub.data.algorithm.curve.join(".")); + var curve2 = new EC(curveId); + var pubkey = pub.data.subjectPrivateKey.data; + return curve2.verify(hash2, sig, pubkey); + } + function dsaVerify(sig, hash2, pub) { + var p = pub.data.p; + var q = pub.data.q; + var g = pub.data.g; + var y = pub.data.pub_key; + var unpacked = parseKeys.signature.decode(sig, "der"); + var s = unpacked.s; + var r = unpacked.r; + checkValue(s, q); + checkValue(r, q); + var montp = BN.mont(p); + var w = s.invm(q); + var v = g.toRed(montp).redPow(new BN(hash2).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q); + return v.cmp(r) === 0; + } + function checkValue(b, q) { + if (b.cmpn(0) <= 0) throw new Error("invalid sig"); + if (b.cmp(q) >= q) throw new Error("invalid sig"); + } + verify_1 = verify; + return verify_1; +} +var browser$6; +var hasRequiredBrowser$6; +function requireBrowser$6() { + if (hasRequiredBrowser$6) return browser$6; + hasRequiredBrowser$6 = 1; + var Buffer2 = requireSafeBuffer().Buffer; + var createHash = requireBrowser$c(); + var stream2 = requireReadableBrowser$1(); + var inherits = requireInherits_browser$1(); + var sign2 = requireSign(); + var verify = requireVerify(); + var algorithms = require$$6; + Object.keys(algorithms).forEach(function(key2) { + algorithms[key2].id = Buffer2.from(algorithms[key2].id, "hex"); + algorithms[key2.toLowerCase()] = algorithms[key2]; + }); + function Sign(algorithm) { + stream2.Writable.call(this); + var data2 = algorithms[algorithm]; + if (!data2) throw new Error("Unknown message digest"); + this._hashType = data2.hash; + this._hash = createHash(data2.hash); + this._tag = data2.id; + this._signType = data2.sign; + } + inherits(Sign, stream2.Writable); + Sign.prototype._write = function _write(data2, _, done) { + this._hash.update(data2); + done(); + }; + Sign.prototype.update = function update(data2, enc) { + if (typeof data2 === "string") data2 = Buffer2.from(data2, enc); + this._hash.update(data2); + return this; + }; + Sign.prototype.sign = function signMethod(key2, enc) { + this.end(); + var hash2 = this._hash.digest(); + var sig = sign2(hash2, key2, this._hashType, this._signType, this._tag); + return enc ? sig.toString(enc) : sig; + }; + function Verify(algorithm) { + stream2.Writable.call(this); + var data2 = algorithms[algorithm]; + if (!data2) throw new Error("Unknown message digest"); + this._hash = createHash(data2.hash); + this._tag = data2.id; + this._signType = data2.sign; + } + inherits(Verify, stream2.Writable); + Verify.prototype._write = function _write(data2, _, done) { + this._hash.update(data2); + done(); + }; + Verify.prototype.update = function update(data2, enc) { + if (typeof data2 === "string") data2 = Buffer2.from(data2, enc); + this._hash.update(data2); + return this; + }; + Verify.prototype.verify = function verifyMethod(key2, sig, enc) { + if (typeof sig === "string") sig = Buffer2.from(sig, enc); + this.end(); + var hash2 = this._hash.digest(); + return verify(sig, hash2, key2, this._signType, this._tag); + }; + function createSign(algorithm) { + return new Sign(algorithm); + } + function createVerify(algorithm) { + return new Verify(algorithm); + } + browser$6 = { + Sign: createSign, + Verify: createVerify, + createSign, + createVerify + }; + return browser$6; +} +var bn$3 = { exports: {} }; +var bn$2 = bn$3.exports; +var hasRequiredBn$1; +function requireBn$1() { + if (hasRequiredBn$1) return bn$3.exports; + hasRequiredBn$1 = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + return c - 48 & 15; + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this.strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + r += c - 49 + 10; + } else if (c >= 17) { + r += c - 17 + 10; + } else { + r += c; + } + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this.strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + BN.prototype.inspect = function inspect() { + return (this.red ? ""; + }; + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16); + }; + BN.prototype.toBuffer = function toBuffer2(endian, length) { + assert2(typeof Buffer2 !== "undefined"); + return this.toArrayLike(Buffer2, endian, length); + }; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + this.strip(); + var littleEndian = endian === "le"; + var res = new ArrayType(reqLength); + var b, i; + var q = this.clone(); + if (!littleEndian) { + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[i] = b; + } + for (; i < reqLength; i++) { + res[i] = 0; + } + } + return res; + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = (num.words[off] & 1 << wbit) >>> wbit; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this.strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this.strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this.strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this.strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this.strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this.strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out.strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out.strip(); + } + function jumboMulTo(self2, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + function FFTM(x, y) { + this.x = x; + this.y = y; + } + FFTM.prototype.makeRBT = function makeRBT(N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + return t; + }; + FFTM.prototype.revBin = function revBin(x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << l - i - 1; + x >>= 1; + } + return rb; + }; + FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + FFTM.prototype.transform = function transform2(rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + for (var j = 0; j < s; j++) { + var re2 = rtws[p + j]; + var ie = itws[p + j]; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + rtws[p + j] = re2 + ro; + itws[p + j] = ie + io; + rtws[p + j + s] = re2 - ro; + itws[p + j + s] = ie - io; + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + FFTM.prototype.guessLen13b = function guessLen13b(n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + return 1 << i + 1 + odd; + }; + FFTM.prototype.conjugate = function conjugate(rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + t = iws[i]; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + FFTM.prototype.normalize13b = function normalize13b(ws2, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws2[2 * i + 1] / N) * 8192 + Math.round(ws2[2 * i] / N) + carry; + ws2[i] = w & 67108863; + if (w < 67108864) { + carry = 0; + } else { + carry = w / 67108864 | 0; + } + } + return ws2; + }; + FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws2[i] | 0); + rws[2 * i] = carry & 8191; + carry = carry >>> 13; + rws[2 * i + 1] = carry & 8191; + carry = carry >>> 13; + } + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + assert2(carry === 0); + assert2((carry & -8192) === 0); + }; + FFTM.prototype.stub = function stub(N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + return ph; + }; + FFTM.prototype.mulp = function mulp(x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + var rbt = this.makeRBT(N); + var _ = this.stub(N); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + var rmws = out.words; + rmws.length = N; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this.strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this.strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this.strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this.strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this.strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this.strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modn = function modn(num) { + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return acc; + }; + BN.prototype.idivn = function idivn(num) { + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + return this.strip(); + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this.strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn$2); + })(bn$3); + return bn$3.exports; +} +var browser$5; +var hasRequiredBrowser$5; +function requireBrowser$5() { + if (hasRequiredBrowser$5) return browser$5; + hasRequiredBrowser$5 = 1; + var elliptic2 = requireElliptic(); + var BN = requireBn$1(); + browser$5 = function createECDH(curve2) { + return new ECDH(curve2); + }; + var aliases2 = { + secp256k1: { + name: "secp256k1", + byteLength: 32 + }, + secp224r1: { + name: "p224", + byteLength: 28 + }, + prime256v1: { + name: "p256", + byteLength: 32 + }, + prime192v1: { + name: "p192", + byteLength: 24 + }, + ed25519: { + name: "ed25519", + byteLength: 32 + }, + secp384r1: { + name: "p384", + byteLength: 48 + }, + secp521r1: { + name: "p521", + byteLength: 66 + } + }; + aliases2.p224 = aliases2.secp224r1; + aliases2.p256 = aliases2.secp256r1 = aliases2.prime256v1; + aliases2.p192 = aliases2.secp192r1 = aliases2.prime192v1; + aliases2.p384 = aliases2.secp384r1; + aliases2.p521 = aliases2.secp521r1; + function ECDH(curve2) { + this.curveType = aliases2[curve2]; + if (!this.curveType) { + this.curveType = { + name: curve2 + }; + } + this.curve = new elliptic2.ec(this.curveType.name); + this.keys = void 0; + } + ECDH.prototype.generateKeys = function(enc, format) { + this.keys = this.curve.genKeyPair(); + return this.getPublicKey(enc, format); + }; + ECDH.prototype.computeSecret = function(other2, inenc, enc) { + inenc = inenc || "utf8"; + if (!Buffer.isBuffer(other2)) { + other2 = new Buffer(other2, inenc); + } + var otherPub = this.curve.keyFromPublic(other2).getPublic(); + var out = otherPub.mul(this.keys.getPrivate()).getX(); + return formatReturnValue(out, enc, this.curveType.byteLength); + }; + ECDH.prototype.getPublicKey = function(enc, format) { + var key2 = this.keys.getPublic(format === "compressed", true); + if (format === "hybrid") { + if (key2[key2.length - 1] % 2) { + key2[0] = 7; + } else { + key2[0] = 6; + } + } + return formatReturnValue(key2, enc); + }; + ECDH.prototype.getPrivateKey = function(enc) { + return formatReturnValue(this.keys.getPrivate(), enc); + }; + ECDH.prototype.setPublicKey = function(pub, enc) { + enc = enc || "utf8"; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this.keys._importPublic(pub); + return this; + }; + ECDH.prototype.setPrivateKey = function(priv, enc) { + enc = enc || "utf8"; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + var _priv = new BN(priv); + _priv = _priv.toString(16); + this.keys = this.curve.genKeyPair(); + this.keys._importPrivate(_priv); + return this; + }; + function formatReturnValue(bn2, enc, len) { + if (!Array.isArray(bn2)) { + bn2 = bn2.toArray(); + } + var buf = new Buffer(bn2); + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length); + zeros.fill(0); + buf = Buffer.concat([zeros, buf]); + } + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } + } + return browser$5; +} +var browser$4 = {}; +var mgf; +var hasRequiredMgf; +function requireMgf() { + if (hasRequiredMgf) return mgf; + hasRequiredMgf = 1; + var createHash = requireBrowser$c(); + var Buffer2 = requireSafeBuffer().Buffer; + mgf = function(seed, len) { + var t = Buffer2.alloc(0); + var i = 0; + var c; + while (t.length < len) { + c = i2ops(i++); + t = Buffer2.concat([t, createHash("sha1").update(seed).update(c).digest()]); + } + return t.slice(0, len); + }; + function i2ops(c) { + var out = Buffer2.allocUnsafe(4); + out.writeUInt32BE(c, 0); + return out; + } + return mgf; +} +var xor; +var hasRequiredXor; +function requireXor() { + if (hasRequiredXor) return xor; + hasRequiredXor = 1; + xor = function xor2(a, b) { + var len = a.length; + var i = -1; + while (++i < len) { + a[i] ^= b[i]; + } + return a; + }; + return xor; +} +var bn$1 = { exports: {} }; +var bn = bn$1.exports; +var hasRequiredBn; +function requireBn() { + if (hasRequiredBn) return bn$1.exports; + hasRequiredBn = 1; + (function(module) { + (function(module2, exports) { + function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN(number, base2, endian) { + if (BN.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base2 === "le" || base2 === "be") { + endian = base2; + base2 = 10; + } + this._init(number || 0, base2 || 10, endian || "be"); + } + } + if (typeof module2 === "object") { + module2.exports = BN; + } else { + exports.BN = BN; + } + BN.BN = BN; + BN.wordSize = 26; + var Buffer2; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer2 = window.Buffer; + } else { + Buffer2 = requireBuffer$2().Buffer; + } + } catch (e) { + } + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + BN.max = function max2(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN.min = function min2(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN.prototype._init = function init(number, base2, endian) { + if (typeof number === "number") { + return this._initNumber(number, base2, endian); + } + if (typeof number === "object") { + return this._initArray(number, base2, endian); + } + if (base2 === "hex") { + base2 = 16; + } + assert2(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base2 === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base2, start); + if (endian === "le") { + this._initArray(this.toArray(), base2, endian); + } + } + } + }; + BN.prototype._initNumber = function _initNumber(number, base2, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [number & 67108863]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert2(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base2, endian); + }; + BN.prototype._initArray = function _initArray(number, base2, endian) { + assert2(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === "le") { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + function parseHex4Bits(string2, index2) { + var c = string2.charCodeAt(index2); + if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + return c - 48 & 15; + } + } + function parseHexByte(string2, lowerBound, index2) { + var r = parseHex4Bits(string2, index2); + if (index2 - 1 >= lowerBound) { + r |= parseHex4Bits(string2, index2 - 1) << 4; + } + return r; + } + BN.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this.strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + r += c - 49 + 10; + } else if (c >= 17) { + r += c - 17 + 10; + } else { + r += c; + } + } + return r; + } + BN.prototype._parseBase = function _parseBase(number, base2, start) { + this.words = [0]; + this.length = 1; + for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) { + limbLen++; + } + limbLen--; + limbPow = limbPow / base2 | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base2); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow2 = 1; + word = parseBase(number, i, number.length, base2); + for (i = 0; i < mod; i++) { + pow2 *= base2; + } + this.imuln(pow2); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this.strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + BN.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + BN.prototype.inspect = function inspect() { + return (this.red ? ""; + }; + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN.prototype.toString = function toString2(base2, padding) { + base2 = base2 || 10; + padding = padding | 0 || 1; + var out; + if (base2 === 16 || base2 === "hex") { + out = ""; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) { + var groupSize = groupSizes[base2]; + var groupBase = groupBases[base2]; + out = ""; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base2); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = "0" + out; + } + while (out.length % padding !== 0) { + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert2(false, "Base should be between 2 and 36"); + }; + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert2(false, "Number can only safely store up to 53 bits"); + } + return this.negative !== 0 ? -ret : ret; + }; + BN.prototype.toJSON = function toJSON() { + return this.toString(16); + }; + BN.prototype.toBuffer = function toBuffer2(endian, length) { + assert2(typeof Buffer2 !== "undefined"); + return this.toArrayLike(Buffer2, endian, length); + }; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert2(byteLength <= reqLength, "byte array longer than desired length"); + assert2(reqLength > 0, "Requested array length <= 0"); + this.strip(); + var littleEndian = endian === "le"; + var res = new ArrayType(reqLength); + var b, i; + var q = this.clone(); + if (!littleEndian) { + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(255); + q.iushrn(8); + res[i] = b; + } + for (; i < reqLength; i++) { + res[i] = 0; + } + } + return res; + }; + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + BN.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = (num.words[off] & 1 << wbit) >>> wbit; + } + return w; + } + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + return this.strip(); + }; + BN.prototype.ior = function ior(num) { + assert2((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this.strip(); + }; + BN.prototype.iand = function iand(num) { + assert2((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this.strip(); + }; + BN.prototype.ixor = function ixor(num) { + assert2((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN.prototype.xor = function xor2(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN.prototype.inotn = function inotn(width) { + assert2(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this.strip(); + }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN.prototype.setn = function setn(bit, val) { + assert2(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this.strip(); + }; + BN.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + return this; + }; + BN.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this.strip(); + }; + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for (var k = 1; k < len; k++) { + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out.strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out.strip(); + } + function jumboMulTo(self2, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self2, num, out); + } + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + function FFTM(x, y) { + this.x = x; + this.y = y; + } + FFTM.prototype.makeRBT = function makeRBT(N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + return t; + }; + FFTM.prototype.revBin = function revBin(x, l, N) { + if (x === 0 || x === N - 1) return x; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << l - i - 1; + x >>= 1; + } + return rb; + }; + FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + FFTM.prototype.transform = function transform2(rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + for (var j = 0; j < s; j++) { + var re2 = rtws[p + j]; + var ie = itws[p + j]; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + var rx = rtwdf_ * ro - itwdf_ * io; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + rtws[p + j] = re2 + ro; + itws[p + j] = ie + io; + rtws[p + j + s] = re2 - ro; + itws[p + j + s] = ie - io; + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + FFTM.prototype.guessLen13b = function guessLen13b(n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + return 1 << i + 1 + odd; + }; + FFTM.prototype.conjugate = function conjugate(rws, iws, N) { + if (N <= 1) return; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + t = iws[i]; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + FFTM.prototype.normalize13b = function normalize13b(ws2, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws2[2 * i + 1] / N) * 8192 + Math.round(ws2[2 * i] / N) + carry; + ws2[i] = w & 67108863; + if (w < 67108864) { + carry = 0; + } else { + carry = w / 67108864 | 0; + } + } + return ws2; + }; + FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws2[i] | 0); + rws[2 * i] = carry & 8191; + carry = carry >>> 13; + rws[2 * i + 1] = carry & 8191; + carry = carry >>> 13; + } + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + assert2(carry === 0); + assert2((carry & -8192) === 0); + }; + FFTM.prototype.stub = function stub(N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + return ph; + }; + FFTM.prototype.mulp = function mulp(x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + var rbt = this.makeRBT(N); + var _ = this.stub(N); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + var rmws = out.words; + rmws.length = N; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN.prototype.imuln = function imuln(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN.prototype.pow = function pow2(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN.prototype.iushln = function iushln(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + this.length += s; + } + return this.strip(); + }; + BN.prototype.ishln = function ishln(bits) { + assert2(this.negative === 0); + return this.iushln(bits); + }; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert2(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this.strip(); + }; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert2(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN.prototype.testn = function testn(bit) { + assert2(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN.prototype.imaskn = function imaskn(bits) { + assert2(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert2(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this.strip(); + }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN.prototype.iaddn = function iaddn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) { + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN.prototype.isubn = function isubn(num) { + assert2(typeof num === "number"); + assert2(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this.strip(); + }; + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN.prototype.abs = function abs2() { + return this.clone().iabs(); + }; + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this.strip(); + assert2(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this.strip(); + }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + var diff3 = a.clone()._ishlnsubmul(b, 1, m); + if (diff3.negative === 0) { + a = diff3; + if (q) { + q.words[m] = 1; + } + } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN.prototype.divmod = function divmod(num, mode, positive) { + assert2(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN.prototype.modn = function modn(num) { + assert2(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + return acc; + }; + BN.prototype.idivn = function idivn(num) { + assert2(num <= 67108863); + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + return this.strip(); + }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN.prototype.egcd = function egcd(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN(1); + var B = new BN(0); + var C = new BN(0); + var D = new BN(1); + var g = 0; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN.prototype._invmp = function _invmp(p) { + assert2(p.negative === 0); + assert2(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ; + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ; + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + } while (true); + return b.iushln(shift); + }; + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN.prototype.bincn = function bincn(bit) { + assert2(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this.strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert2(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN.red = function red(num) { + return new Red(num); + }; + BN.prototype.toRed = function toRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + assert2(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN.prototype.fromRed = function fromRed() { + assert2(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN.prototype.forceRed = function forceRed(ctx) { + assert2(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN.prototype.redAdd = function redAdd(num) { + assert2(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN.prototype.redIAdd = function redIAdd(num) { + assert2(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN.prototype.redSub = function redSub(num) { + assert2(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN.prototype.redISub = function redISub(num) { + assert2(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN.prototype.redShl = function redShl(num) { + assert2(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN.prototype.redMul = function redMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN.prototype.redIMul = function redIMul(num) { + assert2(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN.prototype.redSqr = function redSqr() { + assert2(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN.prototype.redISqr = function redISqr() { + assert2(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN.prototype.redSqrt = function redSqrt() { + assert2(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN.prototype.redInvm = function redInvm() { + assert2(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN.prototype.redNeg = function redNeg() { + assert2(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN.prototype.redPow = function redPow(num) { + assert2(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call( + this, + "k256", + "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" + ); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call( + this, + "p224", + "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" + ); + } + inherits(P224, MPrime); + function P192() { + MPrime.call( + this, + "p192", + "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" + ); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call( + this, + "25519", + "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" + ); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert2(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert2(a.negative === 0, "red works only with positives"); + assert2(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert2((a.negative | b.negative) === 0, "red works only with positives"); + assert2( + a.red && a.red === b.red, + "red works only with red numbers" + ); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert2(mod3 % 2 === 1); + if (mod3 === 3) { + var pow2 = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow2); + } + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert2(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert2(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow2(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current2 = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current2 === 0) { + currentLen = 0; + continue; + } + current2 <<= 1; + current2 |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current2]); + currentLen = 0; + current2 = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN.mont = function mont2(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, bn); + })(bn$1); + return bn$1.exports; +} +var withPublic_1; +var hasRequiredWithPublic; +function requireWithPublic() { + if (hasRequiredWithPublic) return withPublic_1; + hasRequiredWithPublic = 1; + var BN = requireBn(); + var Buffer2 = requireSafeBuffer().Buffer; + function withPublic(paddedMsg, key2) { + return Buffer2.from(paddedMsg.toRed(BN.mont(key2.modulus)).redPow(new BN(key2.publicExponent)).fromRed().toArray()); + } + withPublic_1 = withPublic; + return withPublic_1; +} +var publicEncrypt; +var hasRequiredPublicEncrypt; +function requirePublicEncrypt() { + if (hasRequiredPublicEncrypt) return publicEncrypt; + hasRequiredPublicEncrypt = 1; + var parseKeys = requireParseAsn1(); + var randomBytes = requireBrowser$e(); + var createHash = requireBrowser$c(); + var mgf2 = requireMgf(); + var xor2 = requireXor(); + var BN = requireBn(); + var withPublic = requireWithPublic(); + var crt = requireBrowserifyRsa(); + var Buffer2 = requireSafeBuffer().Buffer; + publicEncrypt = function publicEncrypt2(publicKey, msg, reverse) { + var padding; + if (publicKey.padding) { + padding = publicKey.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + var key2 = parseKeys(publicKey); + var paddedMsg; + if (padding === 4) { + paddedMsg = oaep(key2, msg); + } else if (padding === 1) { + paddedMsg = pkcs1(key2, msg, reverse); + } else if (padding === 3) { + paddedMsg = new BN(msg); + if (paddedMsg.cmp(key2.modulus) >= 0) { + throw new Error("data too long for modulus"); + } + } else { + throw new Error("unknown padding"); + } + if (reverse) { + return crt(paddedMsg, key2); + } else { + return withPublic(paddedMsg, key2); + } + }; + function oaep(key2, msg) { + var k = key2.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash("sha1").update(Buffer2.alloc(0)).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (mLen > k - hLen2 - 2) { + throw new Error("message too long"); + } + var ps = Buffer2.alloc(k - mLen - hLen2 - 2); + var dblen = k - hLen - 1; + var seed = randomBytes(hLen); + var maskedDb = xor2(Buffer2.concat([iHash, ps, Buffer2.alloc(1, 1), msg], dblen), mgf2(seed, dblen)); + var maskedSeed = xor2(seed, mgf2(maskedDb, hLen)); + return new BN(Buffer2.concat([Buffer2.alloc(1), maskedSeed, maskedDb], k)); + } + function pkcs1(key2, msg, reverse) { + var mLen = msg.length; + var k = key2.modulus.byteLength(); + if (mLen > k - 11) { + throw new Error("message too long"); + } + var ps; + if (reverse) { + ps = Buffer2.alloc(k - mLen - 3, 255); + } else { + ps = nonZero(k - mLen - 3); + } + return new BN(Buffer2.concat([Buffer2.from([0, reverse ? 1 : 2]), ps, Buffer2.alloc(1), msg], k)); + } + function nonZero(len) { + var out = Buffer2.allocUnsafe(len); + var i = 0; + var cache = randomBytes(len * 2); + var cur = 0; + var num; + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len * 2); + cur = 0; + } + num = cache[cur++]; + if (num) { + out[i++] = num; + } + } + return out; + } + return publicEncrypt; +} +var privateDecrypt; +var hasRequiredPrivateDecrypt; +function requirePrivateDecrypt() { + if (hasRequiredPrivateDecrypt) return privateDecrypt; + hasRequiredPrivateDecrypt = 1; + var parseKeys = requireParseAsn1(); + var mgf2 = requireMgf(); + var xor2 = requireXor(); + var BN = requireBn(); + var crt = requireBrowserifyRsa(); + var createHash = requireBrowser$c(); + var withPublic = requireWithPublic(); + var Buffer2 = requireSafeBuffer().Buffer; + privateDecrypt = function privateDecrypt2(privateKey, enc, reverse) { + var padding; + if (privateKey.padding) { + padding = privateKey.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + var key2 = parseKeys(privateKey); + var k = key2.modulus.byteLength(); + if (enc.length > k || new BN(enc).cmp(key2.modulus) >= 0) { + throw new Error("decryption error"); + } + var msg; + if (reverse) { + msg = withPublic(new BN(enc), key2); + } else { + msg = crt(enc, key2); + } + var zBuffer = Buffer2.alloc(k - msg.length); + msg = Buffer2.concat([zBuffer, msg], k); + if (padding === 4) { + return oaep(key2, msg); + } else if (padding === 1) { + return pkcs1(key2, msg, reverse); + } else if (padding === 3) { + return msg; + } else { + throw new Error("unknown padding"); + } + }; + function oaep(key2, msg) { + var k = key2.modulus.byteLength(); + var iHash = createHash("sha1").update(Buffer2.alloc(0)).digest(); + var hLen = iHash.length; + if (msg[0] !== 0) { + throw new Error("decryption error"); + } + var maskedSeed = msg.slice(1, hLen + 1); + var maskedDb = msg.slice(hLen + 1); + var seed = xor2(maskedSeed, mgf2(maskedDb, hLen)); + var db = xor2(maskedDb, mgf2(seed, k - hLen - 1)); + if (compare2(iHash, db.slice(0, hLen))) { + throw new Error("decryption error"); + } + var i = hLen; + while (db[i] === 0) { + i++; + } + if (db[i++] !== 1) { + throw new Error("decryption error"); + } + return db.slice(i); + } + function pkcs1(key2, msg, reverse) { + var p1 = msg.slice(0, 2); + var i = 2; + var status = 0; + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++; + break; + } + } + var ps = msg.slice(2, i - 1); + if (p1.toString("hex") !== "0002" && !reverse || p1.toString("hex") !== "0001" && reverse) { + status++; + } + if (ps.length < 8) { + status++; + } + if (status) { + throw new Error("decryption error"); + } + return msg.slice(i); + } + function compare2(a, b) { + a = Buffer2.from(a); + b = Buffer2.from(b); + var dif = 0; + var len = a.length; + if (a.length !== b.length) { + dif++; + len = Math.min(a.length, b.length); + } + var i = -1; + while (++i < len) { + dif += a[i] ^ b[i]; + } + return dif; + } + return privateDecrypt; +} +var hasRequiredBrowser$4; +function requireBrowser$4() { + if (hasRequiredBrowser$4) return browser$4; + hasRequiredBrowser$4 = 1; + (function(exports) { + exports.publicEncrypt = requirePublicEncrypt(); + exports.privateDecrypt = requirePrivateDecrypt(); + exports.privateEncrypt = function privateEncrypt(key2, buf) { + return exports.publicEncrypt(key2, buf, true); + }; + exports.publicDecrypt = function publicDecrypt(key2, buf) { + return exports.privateDecrypt(key2, buf, true); + }; + })(browser$4); + return browser$4; +} +var browser$3 = {}; +var hasRequiredBrowser$3; +function requireBrowser$3() { + if (hasRequiredBrowser$3) return browser$3; + hasRequiredBrowser$3 = 1; + function oldBrowser() { + throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11"); + } + var safeBuffer2 = requireSafeBuffer(); + var randombytes = requireBrowser$e(); + var Buffer2 = safeBuffer2.Buffer; + var kBufferMaxLength = safeBuffer2.kMaxLength; + var crypto2 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + var kMaxUint32 = Math.pow(2, 32) - 1; + function assertOffset(offset2, length) { + if (typeof offset2 !== "number" || offset2 !== offset2) { + throw new TypeError("offset must be a number"); + } + if (offset2 > kMaxUint32 || offset2 < 0) { + throw new TypeError("offset must be a uint32"); + } + if (offset2 > kBufferMaxLength || offset2 > length) { + throw new RangeError("offset out of range"); + } + } + function assertSize(size, offset2, length) { + if (typeof size !== "number" || size !== size) { + throw new TypeError("size must be a number"); + } + if (size > kMaxUint32 || size < 0) { + throw new TypeError("size must be a uint32"); + } + if (size + offset2 > length || size > kBufferMaxLength) { + throw new RangeError("buffer too small"); + } + } + if (crypto2 && crypto2.getRandomValues || !process.browser) { + browser$3.randomFill = randomFill; + browser$3.randomFillSync = randomFillSync; + } else { + browser$3.randomFill = oldBrowser; + browser$3.randomFillSync = oldBrowser; + } + function randomFill(buf, offset2, size, cb) { + if (!Buffer2.isBuffer(buf) && !(buf instanceof commonjsGlobal.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); + } + if (typeof offset2 === "function") { + cb = offset2; + offset2 = 0; + size = buf.length; + } else if (typeof size === "function") { + cb = size; + size = buf.length - offset2; + } else if (typeof cb !== "function") { + throw new TypeError('"cb" argument must be a function'); + } + assertOffset(offset2, buf.length); + assertSize(size, offset2, buf.length); + return actualFill(buf, offset2, size, cb); + } + function actualFill(buf, offset2, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer; + var uint = new Uint8Array(ourBuf, offset2, size); + crypto2.getRandomValues(uint); + if (cb) { + process.nextTick(function() { + cb(null, buf); + }); + return; + } + return buf; + } + if (cb) { + randombytes(size, function(err, bytes2) { + if (err) { + return cb(err); + } + bytes2.copy(buf, offset2); + cb(null, buf); + }); + return; + } + var bytes = randombytes(size); + bytes.copy(buf, offset2); + return buf; + } + function randomFillSync(buf, offset2, size) { + if (typeof offset2 === "undefined") { + offset2 = 0; + } + if (!Buffer2.isBuffer(buf) && !(buf instanceof commonjsGlobal.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); + } + assertOffset(offset2, buf.length); + if (size === void 0) size = buf.length - offset2; + assertSize(size, offset2, buf.length); + return actualFill(buf, offset2, size); + } + return browser$3; +} +var hasRequiredCryptoBrowserify; +function requireCryptoBrowserify() { + if (hasRequiredCryptoBrowserify) return cryptoBrowserify; + hasRequiredCryptoBrowserify = 1; + cryptoBrowserify.randomBytes = cryptoBrowserify.rng = cryptoBrowserify.pseudoRandomBytes = cryptoBrowserify.prng = requireBrowser$e(); + cryptoBrowserify.createHash = cryptoBrowserify.Hash = requireBrowser$c(); + cryptoBrowserify.createHmac = cryptoBrowserify.Hmac = requireBrowser$b(); + var algos2 = requireAlgos(); + var algoKeys = Object.keys(algos2); + var hashes = ["sha1", "sha224", "sha256", "sha384", "sha512", "md5", "rmd160"].concat(algoKeys); + cryptoBrowserify.getHashes = function() { + return hashes; + }; + var p = requireBrowser$a(); + cryptoBrowserify.pbkdf2 = p.pbkdf2; + cryptoBrowserify.pbkdf2Sync = p.pbkdf2Sync; + var aes2 = requireBrowser$8(); + cryptoBrowserify.Cipher = aes2.Cipher; + cryptoBrowserify.createCipher = aes2.createCipher; + cryptoBrowserify.Cipheriv = aes2.Cipheriv; + cryptoBrowserify.createCipheriv = aes2.createCipheriv; + cryptoBrowserify.Decipher = aes2.Decipher; + cryptoBrowserify.createDecipher = aes2.createDecipher; + cryptoBrowserify.Decipheriv = aes2.Decipheriv; + cryptoBrowserify.createDecipheriv = aes2.createDecipheriv; + cryptoBrowserify.getCiphers = aes2.getCiphers; + cryptoBrowserify.listCiphers = aes2.listCiphers; + var dh2 = requireBrowser$7(); + cryptoBrowserify.DiffieHellmanGroup = dh2.DiffieHellmanGroup; + cryptoBrowserify.createDiffieHellmanGroup = dh2.createDiffieHellmanGroup; + cryptoBrowserify.getDiffieHellman = dh2.getDiffieHellman; + cryptoBrowserify.createDiffieHellman = dh2.createDiffieHellman; + cryptoBrowserify.DiffieHellman = dh2.DiffieHellman; + var sign2 = requireBrowser$6(); + cryptoBrowserify.createSign = sign2.createSign; + cryptoBrowserify.Sign = sign2.Sign; + cryptoBrowserify.createVerify = sign2.createVerify; + cryptoBrowserify.Verify = sign2.Verify; + cryptoBrowserify.createECDH = requireBrowser$5(); + var publicEncrypt2 = requireBrowser$4(); + cryptoBrowserify.publicEncrypt = publicEncrypt2.publicEncrypt; + cryptoBrowserify.privateEncrypt = publicEncrypt2.privateEncrypt; + cryptoBrowserify.publicDecrypt = publicEncrypt2.publicDecrypt; + cryptoBrowserify.privateDecrypt = publicEncrypt2.privateDecrypt; + var rf = requireBrowser$3(); + cryptoBrowserify.randomFill = rf.randomFill; + cryptoBrowserify.randomFillSync = rf.randomFillSync; + cryptoBrowserify.createCredentials = function() { + throw new Error([ + "sorry, createCredentials is not implemented yet", + "we accept pull requests", + "https://github.com/crypto-browserify/crypto-browserify" + ].join("\n")); + }; + cryptoBrowserify.constants = { + "DH_CHECK_P_NOT_SAFE_PRIME": 2, + "DH_CHECK_P_NOT_PRIME": 1, + "DH_UNABLE_TO_CHECK_GENERATOR": 4, + "DH_NOT_SUITABLE_GENERATOR": 8, + "NPN_ENABLED": 1, + "ALPN_ENABLED": 1, + "RSA_PKCS1_PADDING": 1, + "RSA_SSLV23_PADDING": 2, + "RSA_NO_PADDING": 3, + "RSA_PKCS1_OAEP_PADDING": 4, + "RSA_X931_PADDING": 5, + "RSA_PKCS1_PSS_PADDING": 6, + "POINT_CONVERSION_COMPRESSED": 2, + "POINT_CONVERSION_UNCOMPRESSED": 4, + "POINT_CONVERSION_HYBRID": 6 + }; + return cryptoBrowserify; +} +const version$3 = "16.4.5"; +const require$$4 = { + version: version$3 +}; +var hasRequiredMain; +function requireMain() { + if (hasRequiredMain) return main.exports; + hasRequiredMain = 1; + const fs2 = require$$2$1; + const path2 = requirePath(); + const os2 = requireBrowser$g(); + const crypto2 = requireCryptoBrowserify(); + const packageJson = require$$4; + const version2 = packageJson.version; + const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + function parse4(src2) { + const obj = {}; + let lines = src2.toString(); + lines = lines.replace(/\r\n?/mg, "\n"); + let match; + while ((match = LINE.exec(lines)) != null) { + const key2 = match[1]; + let value = match[2] || ""; + value = value.trim(); + const maybeQuote = value[0]; + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"); + if (maybeQuote === '"') { + value = value.replace(/\\n/g, "\n"); + value = value.replace(/\\r/g, "\r"); + } + obj[key2] = value; + } + return obj; + } + function _parseVault(options2) { + const vaultPath = _vaultPath(options2); + const result = DotenvModule.configDotenv({ path: vaultPath }); + if (!result.parsed) { + const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); + err.code = "MISSING_DATA"; + throw err; + } + const keys = _dotenvKey(options2).split(","); + const length = keys.length; + let decrypted; + for (let i = 0; i < length; i++) { + try { + const key2 = keys[i].trim(); + const attrs = _instructions(result, key2); + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); + break; + } catch (error2) { + if (i + 1 >= length) { + throw error2; + } + } + } + return DotenvModule.parse(decrypted); + } + function _log(message) { + console.log(`[dotenv@${version2}][INFO] ${message}`); + } + function _warn(message) { + console.log(`[dotenv@${version2}][WARN] ${message}`); + } + function _debug(message) { + console.log(`[dotenv@${version2}][DEBUG] ${message}`); + } + function _dotenvKey(options2) { + if (options2 && options2.DOTENV_KEY && options2.DOTENV_KEY.length > 0) { + return options2.DOTENV_KEY; + } + if (define_process_env_default.DOTENV_KEY && define_process_env_default.DOTENV_KEY.length > 0) { + return define_process_env_default.DOTENV_KEY; + } + return ""; + } + function _instructions(result, dotenvKey) { + let uri2; + try { + uri2 = new URL(dotenvKey); + } catch (error2) { + if (error2.code === "ERR_INVALID_URL") { + const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + throw error2; + } + const key2 = uri2.password; + if (!key2) { + const err = new Error("INVALID_DOTENV_KEY: Missing key part"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + const environment = uri2.searchParams.get("environment"); + if (!environment) { + const err = new Error("INVALID_DOTENV_KEY: Missing environment part"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; + const ciphertext = result.parsed[environmentKey]; + if (!ciphertext) { + const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); + err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; + throw err; + } + return { ciphertext, key: key2 }; + } + function _vaultPath(options2) { + let possibleVaultPath = null; + if (options2 && options2.path && options2.path.length > 0) { + if (Array.isArray(options2.path)) { + for (const filepath of options2.path) { + if (fs2.existsSync(filepath)) { + possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; + } + } + } else { + possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`; + } + } else { + possibleVaultPath = path2.resolve(process.cwd(), ".env.vault"); + } + if (fs2.existsSync(possibleVaultPath)) { + return possibleVaultPath; + } + return null; + } + function _resolveHome(envPath) { + return envPath[0] === "~" ? path2.join(os2.homedir(), envPath.slice(1)) : envPath; + } + function _configVault(options2) { + _log("Loading env from encrypted .env.vault"); + const parsed = DotenvModule._parseVault(options2); + let processEnv = define_process_env_default; + if (options2 && options2.processEnv != null) { + processEnv = options2.processEnv; + } + DotenvModule.populate(processEnv, parsed, options2); + return { parsed }; + } + function configDotenv(options2) { + const dotenvPath = path2.resolve(process.cwd(), ".env"); + let encoding2 = "utf8"; + const debug2 = Boolean(options2 && options2.debug); + if (options2 && options2.encoding) { + encoding2 = options2.encoding; + } else { + if (debug2) { + _debug("No encoding is specified. UTF-8 is used by default"); + } + } + let optionPaths = [dotenvPath]; + if (options2 && options2.path) { + if (!Array.isArray(options2.path)) { + optionPaths = [_resolveHome(options2.path)]; + } else { + optionPaths = []; + for (const filepath of options2.path) { + optionPaths.push(_resolveHome(filepath)); + } + } + } + let lastError; + const parsedAll = {}; + for (const path3 of optionPaths) { + try { + const parsed = DotenvModule.parse(fs2.readFileSync(path3, { encoding: encoding2 })); + DotenvModule.populate(parsedAll, parsed, options2); + } catch (e) { + if (debug2) { + _debug(`Failed to load ${path3} ${e.message}`); + } + lastError = e; + } + } + let processEnv = define_process_env_default; + if (options2 && options2.processEnv != null) { + processEnv = options2.processEnv; + } + DotenvModule.populate(processEnv, parsedAll, options2); + if (lastError) { + return { parsed: parsedAll, error: lastError }; + } else { + return { parsed: parsedAll }; + } + } + function config(options2) { + if (_dotenvKey(options2).length === 0) { + return DotenvModule.configDotenv(options2); + } + const vaultPath = _vaultPath(options2); + if (!vaultPath) { + _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); + return DotenvModule.configDotenv(options2); + } + return DotenvModule._configVault(options2); + } + function decrypt(encrypted, keyStr) { + const key2 = Buffer.from(keyStr.slice(-64), "hex"); + let ciphertext = Buffer.from(encrypted, "base64"); + const nonce = ciphertext.subarray(0, 12); + const authTag = ciphertext.subarray(-16); + ciphertext = ciphertext.subarray(12, -16); + try { + const aesgcm = crypto2.createDecipheriv("aes-256-gcm", key2, nonce); + aesgcm.setAuthTag(authTag); + return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; + } catch (error2) { + const isRange = error2 instanceof RangeError; + const invalidKeyLength = error2.message === "Invalid key length"; + const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data"; + if (isRange || invalidKeyLength) { + const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } else if (decryptionFailed) { + const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); + err.code = "DECRYPTION_FAILED"; + throw err; + } else { + throw error2; + } + } + } + function populate(processEnv, parsed, options2 = {}) { + const debug2 = Boolean(options2 && options2.debug); + const override = Boolean(options2 && options2.override); + if (typeof parsed !== "object") { + const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); + err.code = "OBJECT_REQUIRED"; + throw err; + } + for (const key2 of Object.keys(parsed)) { + if (Object.prototype.hasOwnProperty.call(processEnv, key2)) { + if (override === true) { + processEnv[key2] = parsed[key2]; + } + if (debug2) { + if (override === true) { + _debug(`"${key2}" is already defined and WAS overwritten`); + } else { + _debug(`"${key2}" is already defined and was NOT overwritten`); + } + } + } else { + processEnv[key2] = parsed[key2]; + } + } + } + const DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config, + decrypt, + parse: parse4, + populate + }; + main.exports.configDotenv = DotenvModule.configDotenv; + main.exports._configVault = DotenvModule._configVault; + main.exports._parseVault = DotenvModule._parseVault; + main.exports.config = DotenvModule.config; + main.exports.decrypt = DotenvModule.decrypt; + main.exports.parse = DotenvModule.parse; + main.exports.populate = DotenvModule.populate; + main.exports = DotenvModule; + return main.exports; +} +var mainExports = requireMain(); +const dotenvLibrary = /* @__PURE__ */ getDefaultExportFromCjs(mainExports); +var proxyFromEnv = {}; +var hasRequiredProxyFromEnv; +function requireProxyFromEnv() { + if (hasRequiredProxyFromEnv) return proxyFromEnv; + hasRequiredProxyFromEnv = 1; + var parseUrl = require$$1$5.parse; + var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 + }; + var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && this.indexOf(s, this.length - s.length) !== -1; + }; + function getProxyForUrl2(url2) { + var parsedUrl = typeof url2 === "string" ? parseUrl(url2) : url2 || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== "string" || !hostname || typeof proto !== "string") { + return ""; + } + proto = proto.split(":", 1)[0]; + hostname = hostname.replace(/:\d*$/, ""); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ""; + } + var proxy = getEnv("npm_config_" + proto + "_proxy") || getEnv(proto + "_proxy") || getEnv("npm_config_proxy") || getEnv("all_proxy"); + if (proxy && proxy.indexOf("://") === -1) { + proxy = proto + "://" + proxy; + } + return proxy; + } + function shouldProxy(hostname, port) { + var NO_PROXY = (getEnv("npm_config_no_proxy") || getEnv("no_proxy")).toLowerCase(); + if (!NO_PROXY) { + return true; + } + if (NO_PROXY === "*") { + return false; + } + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; + } + if (!/^[.*]/.test(parsedProxyHostname)) { + return hostname !== parsedProxyHostname; + } + if (parsedProxyHostname.charAt(0) === "*") { + parsedProxyHostname = parsedProxyHostname.slice(1); + } + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); + } + function getEnv(key2) { + return define_process_env_default[key2.toLowerCase()] || define_process_env_default[key2.toUpperCase()] || ""; + } + proxyFromEnv.getProxyForUrl = getProxyForUrl2; + return proxyFromEnv; +} +var proxyFromEnvExports = requireProxyFromEnv(); +var agent$1 = {}; +function noop$3() { +} +const createConnection = noop$3; +const isIP = noop$3; +const net = { + createConnection, + isIP +}; +const net$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + createConnection, + default: net, + isIP +}, Symbol.toStringTag, { value: "Module" })); +const require$$1$2 = /* @__PURE__ */ getAugmentedNamespace(net$1); +function noop$2() { +} +const connect = noop$2; +const TLSSocket = noop$2; +const tls = { + connect, + TLSSocket +}; +const tls$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + TLSSocket, + connect, + default: tls +}, Symbol.toStringTag, { value: "Module" })); +const require$$1$1 = /* @__PURE__ */ getAugmentedNamespace(tls$1); +var promisify = {}; +var hasRequiredPromisify; +function requirePromisify() { + if (hasRequiredPromisify) return promisify; + hasRequiredPromisify = 1; + Object.defineProperty(promisify, "__esModule", { value: true }); + function promisify$1(fn) { + return function(req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } else { + resolve(rtn); + } + }); + }); + }; + } + promisify.default = promisify$1; + return promisify; +} +var src; +var hasRequiredSrc; +function requireSrc() { + if (hasRequiredSrc) return src; + hasRequiredSrc = 1; + var __importDefault = src && src.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + const events_1 = requireEvents(); + const debug_1 = __importDefault(requireBrowser$f()); + const promisify_1 = __importDefault(requirePromisify()); + const debug2 = debug_1.default("agent-base"); + function isAgent(v) { + return Boolean(v) && typeof v.addRequest === "function"; + } + function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); + } + (function(createAgent2) { + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === "function") { + this.callback = callback; + } else if (callback) { + opts = callback; + } + this.timeout = null; + if (opts && typeof opts.timeout === "number") { + this.timeout = opts.timeout; + } + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === "number") { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === "string") { + return this.explicitProtocol; + } + return isSecureEndpoint() ? "https:" : "http:"; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== "boolean") { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = "localhost"; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? "https:" : "http:"; + } + if (opts.host && opts.path) { + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit("error", err); + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = "ETIMEOUT"; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + debug2("Callback returned another Agent instance %o", socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once("free", () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== "function") { + onerror(new Error("`callback` is not defined")); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug2("Converting legacy callback function to promise"); + this.promisifiedCallback = promisify_1.default(this.callback); + } else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === "number" && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ("port" in opts && typeof opts.port !== "number") { + opts.port = Number(opts.port); + } + try { + debug2("Resolving socket for %o request: %o", opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug2("Freeing socket %o %o", socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug2("Destroying agent %o", this.constructor.name); + } + } + createAgent2.Agent = Agent; + createAgent2.prototype = createAgent2.Agent.prototype; + })(createAgent || (createAgent = {})); + src = createAgent; + return src; +} +var parseProxyResponse = {}; +var hasRequiredParseProxyResponse; +function requireParseProxyResponse() { + if (hasRequiredParseProxyResponse) return parseProxyResponse; + hasRequiredParseProxyResponse = 1; + var __importDefault = parseProxyResponse && parseProxyResponse.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(parseProxyResponse, "__esModule", { value: true }); + const debug_1 = __importDefault(requireBrowser$f()); + const debug2 = debug_1.default("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse$1(socket) { + return new Promise((resolve, reject) => { + let buffersLength = 0; + const buffers = []; + function read2() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read2); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("close", onclose); + socket.removeListener("readable", read2); + } + function onclose(err) { + debug2("onclose had error %o", err); + } + function onend() { + debug2("onend"); + } + function onerror(err) { + cleanup(); + debug2("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug2("have not received end of HTTP headers yet..."); + read2(); + return; + } + const firstLine = buffered.toString("ascii", 0, buffered.indexOf("\r\n")); + const statusCode = +firstLine.split(" ")[1]; + debug2("got proxy server response: %o", firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on("error", onerror); + socket.on("close", onclose); + socket.on("end", onend); + read2(); + }); + } + parseProxyResponse.default = parseProxyResponse$1; + return parseProxyResponse; +} +var hasRequiredAgent$1; +function requireAgent$1() { + if (hasRequiredAgent$1) return agent$1; + hasRequiredAgent$1 = 1; + var __awaiter = agent$1 && agent$1.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault = agent$1 && agent$1.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(agent$1, "__esModule", { value: true }); + const net_1 = __importDefault(require$$1$2); + const tls_1 = __importDefault(require$$1$1); + const url_1 = __importDefault(require$$1$5); + const assert_1 = __importDefault(requireAssert()); + const debug_1 = __importDefault(requireBrowser$f()); + const agent_base_1 = requireSrc(); + const parse_proxy_response_1 = __importDefault(requireParseProxyResponse()); + const debug2 = debug_1.default("https-proxy-agent:agent"); + class HttpsProxyAgent2 extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === "string") { + opts = url_1.default.parse(_opts); + } else { + opts = _opts; + } + if (!opts) { + throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!"); + } + debug2("creating new HttpsProxyAgent instance: %o", opts); + super(opts); + const proxy = Object.assign({}, opts); + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === "string") { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + if (this.secureProxy && !("ALPNProtocols" in proxy)) { + proxy.ALPNProtocols = ["http 1.1"]; + } + if (proxy.host && proxy.path) { + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + let socket; + if (secureProxy) { + debug2("Creating `tls.Socket`: %o", proxy); + socket = tls_1.default.connect(proxy); + } else { + debug2("Creating `net.Socket`: %o", proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r +`; + if (proxy.auth) { + headers["Proxy-Authorization"] = `Basic ${Buffer.from(proxy.auth).toString("base64")}`; + } + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = "close"; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r +`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug2("Upgrading socket connection to TLS"); + const servername = opts.servername || opts.host; + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, "host", "hostname", "path", "port")), { + socket, + servername + })); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net_1.default.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug2("replaying proxy buffer for failed request"); + assert_1.default(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } + } + agent$1.default = HttpsProxyAgent2; + function resume(socket) { + socket.resume(); + } + function isDefaultPort(port, secure) { + return Boolean(!secure && port === 80 || secure && port === 443); + } + function isHTTPS(protocol) { + return typeof protocol === "string" ? /^https:?$/i.test(protocol) : false; + } + function omit(obj, ...keys) { + const ret = {}; + let key2; + for (key2 in obj) { + if (!keys.includes(key2)) { + ret[key2] = obj[key2]; + } + } + return ret; + } + return agent$1; +} +var dist$1; +var hasRequiredDist$1; +function requireDist$1() { + if (hasRequiredDist$1) return dist$1; + hasRequiredDist$1 = 1; + var __importDefault = dist$1 && dist$1.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + const agent_1 = __importDefault(requireAgent$1()); + function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); + } + (function(createHttpsProxyAgent2) { + createHttpsProxyAgent2.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent2.prototype = agent_1.default.prototype; + })(createHttpsProxyAgent || (createHttpsProxyAgent = {})); + dist$1 = createHttpsProxyAgent; + return dist$1; +} +var distExports$1 = requireDist$1(); +var encoder = { exports: {} }; +var hasRequiredEncoder; +function requireEncoder() { + if (hasRequiredEncoder) return encoder.exports; + hasRequiredEncoder = 1; + (function(module) { + function JPEGEncoder(quality) { + var ffloor = Math.floor; + var YTable = new Array(64); + var UVTable = new Array(64); + var fdtbl_Y = new Array(64); + var fdtbl_UV = new Array(64); + var YDC_HT; + var UVDC_HT; + var YAC_HT; + var UVAC_HT; + var bitcode = new Array(65535); + var category = new Array(65535); + var outputfDCTQuant = new Array(64); + var DU = new Array(64); + var byteout = []; + var bytenew = 0; + var bytepos = 7; + var YDU = new Array(64); + var UDU = new Array(64); + var VDU = new Array(64); + var clt = new Array(256); + var RGB_YUV_TABLE = new Array(2048); + var currentQuality; + var ZigZag = [ + 0, + 1, + 5, + 6, + 14, + 15, + 27, + 28, + 2, + 4, + 7, + 13, + 16, + 26, + 29, + 42, + 3, + 8, + 12, + 17, + 25, + 30, + 41, + 43, + 9, + 11, + 18, + 24, + 31, + 40, + 44, + 53, + 10, + 19, + 23, + 32, + 39, + 45, + 52, + 54, + 20, + 22, + 33, + 38, + 46, + 51, + 55, + 60, + 21, + 34, + 37, + 47, + 50, + 56, + 59, + 61, + 35, + 36, + 48, + 49, + 57, + 58, + 62, + 63 + ]; + var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; + var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125]; + var std_ac_luminance_values = [ + 1, + 2, + 3, + 0, + 4, + 17, + 5, + 18, + 33, + 49, + 65, + 6, + 19, + 81, + 97, + 7, + 34, + 113, + 20, + 50, + 129, + 145, + 161, + 8, + 35, + 66, + 177, + 193, + 21, + 82, + 209, + 240, + 36, + 51, + 98, + 114, + 130, + 9, + 10, + 22, + 23, + 24, + 25, + 26, + 37, + 38, + 39, + 40, + 41, + 42, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 178, + 179, + 180, + 181, + 182, + 183, + 184, + 185, + 186, + 194, + 195, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 210, + 211, + 212, + 213, + 214, + 215, + 216, + 217, + 218, + 225, + 226, + 227, + 228, + 229, + 230, + 231, + 232, + 233, + 234, + 241, + 242, + 243, + 244, + 245, + 246, + 247, + 248, + 249, + 250 + ]; + var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; + var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119]; + var std_ac_chrominance_values = [ + 0, + 1, + 2, + 3, + 17, + 4, + 5, + 33, + 49, + 6, + 18, + 65, + 81, + 7, + 97, + 113, + 19, + 34, + 50, + 129, + 8, + 20, + 66, + 145, + 161, + 177, + 193, + 9, + 35, + 51, + 82, + 240, + 21, + 98, + 114, + 209, + 10, + 22, + 36, + 52, + 225, + 37, + 241, + 23, + 24, + 25, + 26, + 38, + 39, + 40, + 41, + 42, + 53, + 54, + 55, + 56, + 57, + 58, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 130, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 178, + 179, + 180, + 181, + 182, + 183, + 184, + 185, + 186, + 194, + 195, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 210, + 211, + 212, + 213, + 214, + 215, + 216, + 217, + 218, + 226, + 227, + 228, + 229, + 230, + 231, + 232, + 233, + 234, + 242, + 243, + 244, + 245, + 246, + 247, + 248, + 249, + 250 + ]; + function initQuantTables(sf) { + var YQT = [ + 16, + 11, + 10, + 16, + 24, + 40, + 51, + 61, + 12, + 12, + 14, + 19, + 26, + 58, + 60, + 55, + 14, + 13, + 16, + 24, + 40, + 57, + 69, + 56, + 14, + 17, + 22, + 29, + 51, + 87, + 80, + 62, + 18, + 22, + 37, + 56, + 68, + 109, + 103, + 77, + 24, + 35, + 55, + 64, + 81, + 104, + 113, + 92, + 49, + 64, + 78, + 87, + 103, + 121, + 120, + 101, + 72, + 92, + 95, + 98, + 112, + 100, + 103, + 99 + ]; + for (var i = 0; i < 64; i++) { + var t = ffloor((YQT[i] * sf + 50) / 100); + if (t < 1) { + t = 1; + } else if (t > 255) { + t = 255; + } + YTable[ZigZag[i]] = t; + } + var UVQT = [ + 17, + 18, + 24, + 47, + 99, + 99, + 99, + 99, + 18, + 21, + 26, + 66, + 99, + 99, + 99, + 99, + 24, + 26, + 56, + 99, + 99, + 99, + 99, + 99, + 47, + 66, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99, + 99 + ]; + for (var j = 0; j < 64; j++) { + var u = ffloor((UVQT[j] * sf + 50) / 100); + if (u < 1) { + u = 1; + } else if (u > 255) { + u = 255; + } + UVTable[ZigZag[j]] = u; + } + var aasf = [ + 1, + 1.387039845, + 1.306562965, + 1.175875602, + 1, + 0.785694958, + 0.5411961, + 0.275899379 + ]; + var k = 0; + for (var row = 0; row < 8; row++) { + for (var col = 0; col < 8; col++) { + fdtbl_Y[k] = 1 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8); + fdtbl_UV[k] = 1 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8); + k++; + } + } + } + function computeHuffmanTbl(nrcodes, std_table) { + var codevalue = 0; + var pos_in_table = 0; + var HT = new Array(); + for (var k = 1; k <= 16; k++) { + for (var j = 1; j <= nrcodes[k]; j++) { + HT[std_table[pos_in_table]] = []; + HT[std_table[pos_in_table]][0] = codevalue; + HT[std_table[pos_in_table]][1] = k; + pos_in_table++; + codevalue++; + } + codevalue *= 2; + } + return HT; + } + function initHuffmanTbl() { + YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values); + UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values); + YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values); + UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values); + } + function initCategoryNumber() { + var nrlower = 1; + var nrupper = 2; + for (var cat = 1; cat <= 15; cat++) { + for (var nr = nrlower; nr < nrupper; nr++) { + category[32767 + nr] = cat; + bitcode[32767 + nr] = []; + bitcode[32767 + nr][1] = cat; + bitcode[32767 + nr][0] = nr; + } + for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) { + category[32767 + nrneg] = cat; + bitcode[32767 + nrneg] = []; + bitcode[32767 + nrneg][1] = cat; + bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg; + } + nrlower <<= 1; + nrupper <<= 1; + } + } + function initRGBYUVTable() { + for (var i = 0; i < 256; i++) { + RGB_YUV_TABLE[i] = 19595 * i; + RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i; + RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 32768; + RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i; + RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i; + RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 8421375; + RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i; + RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i; + } + } + function writeBits(bs) { + var value = bs[0]; + var posval = bs[1] - 1; + while (posval >= 0) { + if (value & 1 << posval) { + bytenew |= 1 << bytepos; + } + posval--; + bytepos--; + if (bytepos < 0) { + if (bytenew == 255) { + writeByte(255); + writeByte(0); + } else { + writeByte(bytenew); + } + bytepos = 7; + bytenew = 0; + } + } + } + function writeByte(value) { + byteout.push(value); + } + function writeWord(value) { + writeByte(value >> 8 & 255); + writeByte(value & 255); + } + function fDCTQuant(data2, fdtbl) { + var d0, d1, d2, d3, d4, d5, d6, d7; + var dataOff = 0; + var i; + var I8 = 8; + var I64 = 64; + for (i = 0; i < I8; ++i) { + d0 = data2[dataOff]; + d1 = data2[dataOff + 1]; + d2 = data2[dataOff + 2]; + d3 = data2[dataOff + 3]; + d4 = data2[dataOff + 4]; + d5 = data2[dataOff + 5]; + d6 = data2[dataOff + 6]; + d7 = data2[dataOff + 7]; + var tmp0 = d0 + d7; + var tmp7 = d0 - d7; + var tmp1 = d1 + d6; + var tmp6 = d1 - d6; + var tmp2 = d2 + d5; + var tmp5 = d2 - d5; + var tmp3 = d3 + d4; + var tmp4 = d3 - d4; + var tmp10 = tmp0 + tmp3; + var tmp13 = tmp0 - tmp3; + var tmp11 = tmp1 + tmp2; + var tmp12 = tmp1 - tmp2; + data2[dataOff] = tmp10 + tmp11; + data2[dataOff + 4] = tmp10 - tmp11; + var z1 = (tmp12 + tmp13) * 0.707106781; + data2[dataOff + 2] = tmp13 + z1; + data2[dataOff + 6] = tmp13 - z1; + tmp10 = tmp4 + tmp5; + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + var z5 = (tmp10 - tmp12) * 0.382683433; + var z2 = 0.5411961 * tmp10 + z5; + var z4 = 1.306562965 * tmp12 + z5; + var z3 = tmp11 * 0.707106781; + var z11 = tmp7 + z3; + var z13 = tmp7 - z3; + data2[dataOff + 5] = z13 + z2; + data2[dataOff + 3] = z13 - z2; + data2[dataOff + 1] = z11 + z4; + data2[dataOff + 7] = z11 - z4; + dataOff += 8; + } + dataOff = 0; + for (i = 0; i < I8; ++i) { + d0 = data2[dataOff]; + d1 = data2[dataOff + 8]; + d2 = data2[dataOff + 16]; + d3 = data2[dataOff + 24]; + d4 = data2[dataOff + 32]; + d5 = data2[dataOff + 40]; + d6 = data2[dataOff + 48]; + d7 = data2[dataOff + 56]; + var tmp0p2 = d0 + d7; + var tmp7p2 = d0 - d7; + var tmp1p2 = d1 + d6; + var tmp6p2 = d1 - d6; + var tmp2p2 = d2 + d5; + var tmp5p2 = d2 - d5; + var tmp3p2 = d3 + d4; + var tmp4p2 = d3 - d4; + var tmp10p2 = tmp0p2 + tmp3p2; + var tmp13p2 = tmp0p2 - tmp3p2; + var tmp11p2 = tmp1p2 + tmp2p2; + var tmp12p2 = tmp1p2 - tmp2p2; + data2[dataOff] = tmp10p2 + tmp11p2; + data2[dataOff + 32] = tmp10p2 - tmp11p2; + var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; + data2[dataOff + 16] = tmp13p2 + z1p2; + data2[dataOff + 48] = tmp13p2 - z1p2; + tmp10p2 = tmp4p2 + tmp5p2; + tmp11p2 = tmp5p2 + tmp6p2; + tmp12p2 = tmp6p2 + tmp7p2; + var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; + var z2p2 = 0.5411961 * tmp10p2 + z5p2; + var z4p2 = 1.306562965 * tmp12p2 + z5p2; + var z3p2 = tmp11p2 * 0.707106781; + var z11p2 = tmp7p2 + z3p2; + var z13p2 = tmp7p2 - z3p2; + data2[dataOff + 40] = z13p2 + z2p2; + data2[dataOff + 24] = z13p2 - z2p2; + data2[dataOff + 8] = z11p2 + z4p2; + data2[dataOff + 56] = z11p2 - z4p2; + dataOff++; + } + var fDCTQuant2; + for (i = 0; i < I64; ++i) { + fDCTQuant2 = data2[i] * fdtbl[i]; + outputfDCTQuant[i] = fDCTQuant2 > 0 ? fDCTQuant2 + 0.5 | 0 : fDCTQuant2 - 0.5 | 0; + } + return outputfDCTQuant; + } + function writeAPP0() { + writeWord(65504); + writeWord(16); + writeByte(74); + writeByte(70); + writeByte(73); + writeByte(70); + writeByte(0); + writeByte(1); + writeByte(1); + writeByte(0); + writeWord(1); + writeWord(1); + writeByte(0); + writeByte(0); + } + function writeAPP1(exifBuffer) { + if (!exifBuffer) return; + writeWord(65505); + if (exifBuffer[0] === 69 && exifBuffer[1] === 120 && exifBuffer[2] === 105 && exifBuffer[3] === 102) { + writeWord(exifBuffer.length + 2); + } else { + writeWord(exifBuffer.length + 5 + 2); + writeByte(69); + writeByte(120); + writeByte(105); + writeByte(102); + writeByte(0); + } + for (var i = 0; i < exifBuffer.length; i++) { + writeByte(exifBuffer[i]); + } + } + function writeSOF0(width, height) { + writeWord(65472); + writeWord(17); + writeByte(8); + writeWord(height); + writeWord(width); + writeByte(3); + writeByte(1); + writeByte(17); + writeByte(0); + writeByte(2); + writeByte(17); + writeByte(1); + writeByte(3); + writeByte(17); + writeByte(1); + } + function writeDQT() { + writeWord(65499); + writeWord(132); + writeByte(0); + for (var i = 0; i < 64; i++) { + writeByte(YTable[i]); + } + writeByte(1); + for (var j = 0; j < 64; j++) { + writeByte(UVTable[j]); + } + } + function writeDHT() { + writeWord(65476); + writeWord(418); + writeByte(0); + for (var i = 0; i < 16; i++) { + writeByte(std_dc_luminance_nrcodes[i + 1]); + } + for (var j = 0; j <= 11; j++) { + writeByte(std_dc_luminance_values[j]); + } + writeByte(16); + for (var k = 0; k < 16; k++) { + writeByte(std_ac_luminance_nrcodes[k + 1]); + } + for (var l = 0; l <= 161; l++) { + writeByte(std_ac_luminance_values[l]); + } + writeByte(1); + for (var m = 0; m < 16; m++) { + writeByte(std_dc_chrominance_nrcodes[m + 1]); + } + for (var n = 0; n <= 11; n++) { + writeByte(std_dc_chrominance_values[n]); + } + writeByte(17); + for (var o = 0; o < 16; o++) { + writeByte(std_ac_chrominance_nrcodes[o + 1]); + } + for (var p = 0; p <= 161; p++) { + writeByte(std_ac_chrominance_values[p]); + } + } + function writeCOM(comments) { + if (typeof comments === "undefined" || comments.constructor !== Array) return; + comments.forEach((e) => { + if (typeof e !== "string") return; + writeWord(65534); + var l = e.length; + writeWord(l + 2); + var i; + for (i = 0; i < l; i++) + writeByte(e.charCodeAt(i)); + }); + } + function writeSOS() { + writeWord(65498); + writeWord(12); + writeByte(3); + writeByte(1); + writeByte(0); + writeByte(2); + writeByte(17); + writeByte(3); + writeByte(17); + writeByte(0); + writeByte(63); + writeByte(0); + } + function processDU(CDU, fdtbl, DC, HTDC, HTAC) { + var EOB = HTAC[0]; + var M16zeroes = HTAC[240]; + var pos; + var I16 = 16; + var I63 = 63; + var I64 = 64; + var DU_DCT = fDCTQuant(CDU, fdtbl); + for (var j = 0; j < I64; ++j) { + DU[ZigZag[j]] = DU_DCT[j]; + } + var Diff2 = DU[0] - DC; + DC = DU[0]; + if (Diff2 == 0) { + writeBits(HTDC[0]); + } else { + pos = 32767 + Diff2; + writeBits(HTDC[category[pos]]); + writeBits(bitcode[pos]); + } + var end0pos = 63; + for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) { + } + if (end0pos == 0) { + writeBits(EOB); + return DC; + } + var i = 1; + var lng; + while (i <= end0pos) { + var startpos = i; + for (; DU[i] == 0 && i <= end0pos; ++i) { + } + var nrzeroes = i - startpos; + if (nrzeroes >= I16) { + lng = nrzeroes >> 4; + for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) + writeBits(M16zeroes); + nrzeroes = nrzeroes & 15; + } + pos = 32767 + DU[i]; + writeBits(HTAC[(nrzeroes << 4) + category[pos]]); + writeBits(bitcode[pos]); + i++; + } + if (end0pos != I63) { + writeBits(EOB); + } + return DC; + } + function initCharLookupTable() { + var sfcc = String.fromCharCode; + for (var i = 0; i < 256; i++) { + clt[i] = sfcc(i); + } + } + this.encode = function(image, quality2) { + (/* @__PURE__ */ new Date()).getTime(); + if (quality2) setQuality(quality2); + byteout = new Array(); + bytenew = 0; + bytepos = 7; + writeWord(65496); + writeAPP0(); + writeCOM(image.comments); + writeAPP1(image.exifBuffer); + writeDQT(); + writeSOF0(image.width, image.height); + writeDHT(); + writeSOS(); + var DCY = 0; + var DCU = 0; + var DCV = 0; + bytenew = 0; + bytepos = 7; + this.encode.displayName = "_encode_"; + var imageData = image.data; + var width = image.width; + var height = image.height; + var quadWidth = width * 4; + var x, y = 0; + var r, g, b; + var start, p, col, row, pos; + while (y < height) { + x = 0; + while (x < quadWidth) { + start = quadWidth * y + x; + p = start; + col = -1; + row = 0; + for (pos = 0; pos < 64; pos++) { + row = pos >> 3; + col = (pos & 7) * 4; + p = start + row * quadWidth + col; + if (y + row >= height) { + p -= quadWidth * (y + 1 + row - height); + } + if (x + col >= quadWidth) { + p -= x + col - quadWidth + 4; + } + r = imageData[p++]; + g = imageData[p++]; + b = imageData[p++]; + YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128; + UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128; + VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128; + } + DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + x += 32; + } + y += 8; + } + if (bytepos >= 0) { + var fillbits = []; + fillbits[1] = bytepos + 1; + fillbits[0] = (1 << bytepos + 1) - 1; + writeBits(fillbits); + } + writeWord(65497); + return Buffer.from(byteout); + }; + function setQuality(quality2) { + if (quality2 <= 0) { + quality2 = 1; + } + if (quality2 > 100) { + quality2 = 100; + } + if (currentQuality == quality2) return; + var sf = 0; + if (quality2 < 50) { + sf = Math.floor(5e3 / quality2); + } else { + sf = Math.floor(200 - quality2 * 2); + } + initQuantTables(sf); + currentQuality = quality2; + } + function init() { + var time_start = (/* @__PURE__ */ new Date()).getTime(); + if (!quality) quality = 50; + initCharLookupTable(); + initHuffmanTbl(); + initCategoryNumber(); + initRGBYUVTable(); + setQuality(quality); + (/* @__PURE__ */ new Date()).getTime() - time_start; + } + init(); + } + { + module.exports = encode; + } + function encode(imgData, qu) { + if (typeof qu === "undefined") qu = 50; + var encoder2 = new JPEGEncoder(qu); + var data2 = encoder2.encode(imgData, qu); + return { + data: data2, + width: imgData.width, + height: imgData.height + }; + } + })(encoder); + return encoder.exports; +} +var decoder = { exports: {} }; +var hasRequiredDecoder; +function requireDecoder() { + if (hasRequiredDecoder) return decoder.exports; + hasRequiredDecoder = 1; + (function(module) { + var JpegImage = function jpegImage() { + var dctZigZag = new Int32Array([ + 0, + 1, + 8, + 16, + 9, + 2, + 3, + 10, + 17, + 24, + 32, + 25, + 18, + 11, + 4, + 5, + 12, + 19, + 26, + 33, + 40, + 48, + 41, + 34, + 27, + 20, + 13, + 6, + 7, + 14, + 21, + 28, + 35, + 42, + 49, + 56, + 57, + 50, + 43, + 36, + 29, + 22, + 15, + 23, + 30, + 37, + 44, + 51, + 58, + 59, + 52, + 45, + 38, + 31, + 39, + 46, + 53, + 60, + 61, + 54, + 47, + 55, + 62, + 63 + ]); + var dctCos1 = 4017; + var dctSin1 = 799; + var dctCos3 = 3406; + var dctSin3 = 2276; + var dctCos6 = 1567; + var dctSin6 = 3784; + var dctSqrt2 = 5793; + var dctSqrt1d2 = 2896; + function constructor() { + } + function buildHuffmanTable(codeLengths, values) { + var k = 0, code = [], i, j, length = 16; + while (length > 0 && !codeLengths[length - 1]) + length--; + code.push({ children: [], index: 0 }); + var p = code[0], q; + for (i = 0; i < length; i++) { + for (j = 0; j < codeLengths[i]; j++) { + p = code.pop(); + p.children[p.index] = values[k]; + while (p.index > 0) { + if (code.length === 0) + throw new Error("Could not recreate Huffman Table"); + p = code.pop(); + } + p.index++; + code.push(p); + while (code.length <= i) { + code.push(q = { children: [], index: 0 }); + p.children[p.index] = q.children; + p = q; + } + k++; + } + if (i + 1 < length) { + code.push(q = { children: [], index: 0 }); + p.children[p.index] = q.children; + p = q; + } + } + return code[0].children; + } + function decodeScan(data2, offset2, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, opts) { + frame.precision; + frame.samplesPerLine; + frame.scanLines; + var mcusPerLine = frame.mcusPerLine; + var progressive = frame.progressive; + frame.maxH; + frame.maxV; + var startOffset = offset2, bitsData = 0, bitsCount = 0; + function readBit() { + if (bitsCount > 0) { + bitsCount--; + return bitsData >> bitsCount & 1; + } + bitsData = data2[offset2++]; + if (bitsData == 255) { + var nextByte = data2[offset2++]; + if (nextByte) { + throw new Error("unexpected marker: " + (bitsData << 8 | nextByte).toString(16)); + } + } + bitsCount = 7; + return bitsData >>> 7; + } + function decodeHuffman(tree) { + var node2 = tree, bit; + while ((bit = readBit()) !== null) { + node2 = node2[bit]; + if (typeof node2 === "number") + return node2; + if (typeof node2 !== "object") + throw new Error("invalid huffman sequence"); + } + return null; + } + function receive(length) { + var n2 = 0; + while (length > 0) { + var bit = readBit(); + if (bit === null) return; + n2 = n2 << 1 | bit; + length--; + } + return n2; + } + function receiveAndExtend(length) { + var n2 = receive(length); + if (n2 >= 1 << length - 1) + return n2; + return n2 + (-1 << length) + 1; + } + function decodeBaseline(component2, zz) { + var t = decodeHuffman(component2.huffmanTableDC); + var diff3 = t === 0 ? 0 : receiveAndExtend(t); + zz[0] = component2.pred += diff3; + var k2 = 1; + while (k2 < 64) { + var rs = decodeHuffman(component2.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) + break; + k2 += 16; + continue; + } + k2 += r; + var z = dctZigZag[k2]; + zz[z] = receiveAndExtend(s); + k2++; + } + } + function decodeDCFirst(component2, zz) { + var t = decodeHuffman(component2.huffmanTableDC); + var diff3 = t === 0 ? 0 : receiveAndExtend(t) << successive; + zz[0] = component2.pred += diff3; + } + function decodeDCSuccessive(component2, zz) { + zz[0] |= readBit() << successive; + } + var eobrun = 0; + function decodeACFirst(component2, zz) { + if (eobrun > 0) { + eobrun--; + return; + } + var k2 = spectralStart, e = spectralEnd; + while (k2 <= e) { + var rs = decodeHuffman(component2.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r) - 1; + break; + } + k2 += 16; + continue; + } + k2 += r; + var z = dctZigZag[k2]; + zz[z] = receiveAndExtend(s) * (1 << successive); + k2++; + } + } + var successiveACState = 0, successiveACNextValue; + function decodeACSuccessive(component2, zz) { + var k2 = spectralStart, e = spectralEnd, r = 0; + while (k2 <= e) { + var z = dctZigZag[k2]; + var direction = zz[z] < 0 ? -1 : 1; + switch (successiveACState) { + case 0: + var rs = decodeHuffman(component2.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r); + successiveACState = 4; + } else { + r = 16; + successiveACState = 1; + } + } else { + if (s !== 1) + throw new Error("invalid ACn encoding"); + successiveACNextValue = receiveAndExtend(s); + successiveACState = r ? 2 : 3; + } + continue; + case 1: + // skipping r zero items + case 2: + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + else { + r--; + if (r === 0) + successiveACState = successiveACState == 2 ? 3 : 0; + } + break; + case 3: + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + else { + zz[z] = successiveACNextValue << successive; + successiveACState = 0; + } + break; + case 4: + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + break; + } + k2++; + } + if (successiveACState === 4) { + eobrun--; + if (eobrun === 0) + successiveACState = 0; + } + } + function decodeMcu(component2, decode2, mcu2, row, col) { + var mcuRow = mcu2 / mcusPerLine | 0; + var mcuCol = mcu2 % mcusPerLine; + var blockRow = mcuRow * component2.v + row; + var blockCol = mcuCol * component2.h + col; + if (component2.blocks[blockRow] === void 0 && opts.tolerantDecoding) + return; + decode2(component2, component2.blocks[blockRow][blockCol]); + } + function decodeBlock(component2, decode2, mcu2) { + var blockRow = mcu2 / component2.blocksPerLine | 0; + var blockCol = mcu2 % component2.blocksPerLine; + if (component2.blocks[blockRow] === void 0 && opts.tolerantDecoding) + return; + decode2(component2, component2.blocks[blockRow][blockCol]); + } + var componentsLength = components.length; + var component, i, j, k, n; + var decodeFn; + if (progressive) { + if (spectralStart === 0) + decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; + else + decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; + } else { + decodeFn = decodeBaseline; + } + var mcu = 0, marker; + var mcuExpected; + if (componentsLength == 1) { + mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; + } else { + mcuExpected = mcusPerLine * frame.mcusPerColumn; + } + if (!resetInterval) resetInterval = mcuExpected; + var h, v; + while (mcu < mcuExpected) { + for (i = 0; i < componentsLength; i++) + components[i].pred = 0; + eobrun = 0; + if (componentsLength == 1) { + component = components[0]; + for (n = 0; n < resetInterval; n++) { + decodeBlock(component, decodeFn, mcu); + mcu++; + } + } else { + for (n = 0; n < resetInterval; n++) { + for (i = 0; i < componentsLength; i++) { + component = components[i]; + h = component.h; + v = component.v; + for (j = 0; j < v; j++) { + for (k = 0; k < h; k++) { + decodeMcu(component, decodeFn, mcu, j, k); + } + } + } + mcu++; + if (mcu === mcuExpected) break; + } + } + if (mcu === mcuExpected) { + do { + if (data2[offset2] === 255) { + if (data2[offset2 + 1] !== 0) { + break; + } + } + offset2 += 1; + } while (offset2 < data2.length - 2); + } + bitsCount = 0; + marker = data2[offset2] << 8 | data2[offset2 + 1]; + if (marker < 65280) { + throw new Error("marker was not found"); + } + if (marker >= 65488 && marker <= 65495) { + offset2 += 2; + } else + break; + } + return offset2 - startOffset; + } + function buildComponentData(frame, component) { + var lines = []; + var blocksPerLine = component.blocksPerLine; + var blocksPerColumn = component.blocksPerColumn; + var samplesPerLine = blocksPerLine << 3; + var R = new Int32Array(64), r = new Uint8Array(64); + function quantizeAndInverse(zz, dataOut, dataIn) { + var qt = component.quantizationTable; + var v0, v1, v2, v3, v4, v5, v6, v7, t; + var p = dataIn; + var i2; + for (i2 = 0; i2 < 64; i2++) + p[i2] = zz[i2] * qt[i2]; + for (i2 = 0; i2 < 8; ++i2) { + var row = 8 * i2; + if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) { + t = dctSqrt2 * p[0 + row] + 512 >> 10; + p[0 + row] = t; + p[1 + row] = t; + p[2 + row] = t; + p[3 + row] = t; + p[4 + row] = t; + p[5 + row] = t; + p[6 + row] = t; + p[7 + row] = t; + continue; + } + v0 = dctSqrt2 * p[0 + row] + 128 >> 8; + v1 = dctSqrt2 * p[4 + row] + 128 >> 8; + v2 = p[2 + row]; + v3 = p[6 + row]; + v4 = dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128 >> 8; + v7 = dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128 >> 8; + v5 = p[3 + row] << 4; + v6 = p[5 + row] << 4; + t = v0 - v1 + 1 >> 1; + v0 = v0 + v1 + 1 >> 1; + v1 = t; + t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8; + v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8; + v3 = t; + t = v4 - v6 + 1 >> 1; + v4 = v4 + v6 + 1 >> 1; + v6 = t; + t = v7 + v5 + 1 >> 1; + v5 = v7 - v5 + 1 >> 1; + v7 = t; + t = v0 - v3 + 1 >> 1; + v0 = v0 + v3 + 1 >> 1; + v3 = t; + t = v1 - v2 + 1 >> 1; + v1 = v1 + v2 + 1 >> 1; + v2 = t; + t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12; + v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12; + v7 = t; + t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12; + v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12; + v6 = t; + p[0 + row] = v0 + v7; + p[7 + row] = v0 - v7; + p[1 + row] = v1 + v6; + p[6 + row] = v1 - v6; + p[2 + row] = v2 + v5; + p[5 + row] = v2 - v5; + p[3 + row] = v3 + v4; + p[4 + row] = v3 - v4; + } + for (i2 = 0; i2 < 8; ++i2) { + var col = i2; + if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 && p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 && p[7 * 8 + col] == 0) { + t = dctSqrt2 * dataIn[i2 + 0] + 8192 >> 14; + p[0 * 8 + col] = t; + p[1 * 8 + col] = t; + p[2 * 8 + col] = t; + p[3 * 8 + col] = t; + p[4 * 8 + col] = t; + p[5 * 8 + col] = t; + p[6 * 8 + col] = t; + p[7 * 8 + col] = t; + continue; + } + v0 = dctSqrt2 * p[0 * 8 + col] + 2048 >> 12; + v1 = dctSqrt2 * p[4 * 8 + col] + 2048 >> 12; + v2 = p[2 * 8 + col]; + v3 = p[6 * 8 + col]; + v4 = dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048 >> 12; + v7 = dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048 >> 12; + v5 = p[3 * 8 + col]; + v6 = p[5 * 8 + col]; + t = v0 - v1 + 1 >> 1; + v0 = v0 + v1 + 1 >> 1; + v1 = t; + t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12; + v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12; + v3 = t; + t = v4 - v6 + 1 >> 1; + v4 = v4 + v6 + 1 >> 1; + v6 = t; + t = v7 + v5 + 1 >> 1; + v5 = v7 - v5 + 1 >> 1; + v7 = t; + t = v0 - v3 + 1 >> 1; + v0 = v0 + v3 + 1 >> 1; + v3 = t; + t = v1 - v2 + 1 >> 1; + v1 = v1 + v2 + 1 >> 1; + v2 = t; + t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12; + v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12; + v7 = t; + t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12; + v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12; + v6 = t; + p[0 * 8 + col] = v0 + v7; + p[7 * 8 + col] = v0 - v7; + p[1 * 8 + col] = v1 + v6; + p[6 * 8 + col] = v1 - v6; + p[2 * 8 + col] = v2 + v5; + p[5 * 8 + col] = v2 - v5; + p[3 * 8 + col] = v3 + v4; + p[4 * 8 + col] = v3 - v4; + } + for (i2 = 0; i2 < 64; ++i2) { + var sample2 = 128 + (p[i2] + 8 >> 4); + dataOut[i2] = sample2 < 0 ? 0 : sample2 > 255 ? 255 : sample2; + } + } + requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8); + var i, j; + for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { + var scanLine = blockRow << 3; + for (i = 0; i < 8; i++) + lines.push(new Uint8Array(samplesPerLine)); + for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { + quantizeAndInverse(component.blocks[blockRow][blockCol], r, R); + var offset2 = 0, sample = blockCol << 3; + for (j = 0; j < 8; j++) { + var line = lines[scanLine + j]; + for (i = 0; i < 8; i++) + line[sample + i] = r[offset2++]; + } + } + } + return lines; + } + function clampTo8bit(a) { + return a < 0 ? 0 : a > 255 ? 255 : a; + } + constructor.prototype = { + load: function load(path2) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", path2, true); + xhr.responseType = "arraybuffer"; + xhr.onload = (function() { + var data2 = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); + this.parse(data2); + if (this.onload) + this.onload(); + }).bind(this); + xhr.send(null); + }, + parse: function parse4(data2) { + var maxResolutionInPixels = this.opts.maxResolutionInMP * 1e3 * 1e3; + var offset2 = 0; + data2.length; + function readUint16() { + var value = data2[offset2] << 8 | data2[offset2 + 1]; + offset2 += 2; + return value; + } + function readDataBlock() { + var length = readUint16(); + var array = data2.subarray(offset2, offset2 + length - 2); + offset2 += array.length; + return array; + } + function prepareComponents(frame2) { + var maxH = 1, maxV = 1; + var component2, componentId2; + for (componentId2 in frame2.components) { + if (frame2.components.hasOwnProperty(componentId2)) { + component2 = frame2.components[componentId2]; + if (maxH < component2.h) maxH = component2.h; + if (maxV < component2.v) maxV = component2.v; + } + } + var mcusPerLine = Math.ceil(frame2.samplesPerLine / 8 / maxH); + var mcusPerColumn = Math.ceil(frame2.scanLines / 8 / maxV); + for (componentId2 in frame2.components) { + if (frame2.components.hasOwnProperty(componentId2)) { + component2 = frame2.components[componentId2]; + var blocksPerLine = Math.ceil(Math.ceil(frame2.samplesPerLine / 8) * component2.h / maxH); + var blocksPerColumn = Math.ceil(Math.ceil(frame2.scanLines / 8) * component2.v / maxV); + var blocksPerLineForMcu = mcusPerLine * component2.h; + var blocksPerColumnForMcu = mcusPerColumn * component2.v; + var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu; + var blocks = []; + requestMemoryAllocation(blocksToAllocate * 256); + for (var i2 = 0; i2 < blocksPerColumnForMcu; i2++) { + var row = []; + for (var j2 = 0; j2 < blocksPerLineForMcu; j2++) + row.push(new Int32Array(64)); + blocks.push(row); + } + component2.blocksPerLine = blocksPerLine; + component2.blocksPerColumn = blocksPerColumn; + component2.blocks = blocks; + } + } + frame2.maxH = maxH; + frame2.maxV = maxV; + frame2.mcusPerLine = mcusPerLine; + frame2.mcusPerColumn = mcusPerColumn; + } + var jfif = null; + var adobe = null; + var frame, resetInterval; + var quantizationTables = [], frames = []; + var huffmanTablesAC = [], huffmanTablesDC = []; + var fileMarker = readUint16(); + var malformedDataOffset = -1; + this.comments = []; + if (fileMarker != 65496) { + throw new Error("SOI not found"); + } + fileMarker = readUint16(); + while (fileMarker != 65497) { + var i, j; + switch (fileMarker) { + case 65280: + break; + case 65504: + // APP0 (Application Specific) + case 65505: + // APP1 + case 65506: + // APP2 + case 65507: + // APP3 + case 65508: + // APP4 + case 65509: + // APP5 + case 65510: + // APP6 + case 65511: + // APP7 + case 65512: + // APP8 + case 65513: + // APP9 + case 65514: + // APP10 + case 65515: + // APP11 + case 65516: + // APP12 + case 65517: + // APP13 + case 65518: + // APP14 + case 65519: + // APP15 + case 65534: + var appData = readDataBlock(); + if (fileMarker === 65534) { + var comment2 = String.fromCharCode.apply(null, appData); + this.comments.push(comment2); + } + if (fileMarker === 65504) { + if (appData[0] === 74 && appData[1] === 70 && appData[2] === 73 && appData[3] === 70 && appData[4] === 0) { + jfif = { + version: { major: appData[5], minor: appData[6] }, + densityUnits: appData[7], + xDensity: appData[8] << 8 | appData[9], + yDensity: appData[10] << 8 | appData[11], + thumbWidth: appData[12], + thumbHeight: appData[13], + thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) + }; + } + } + if (fileMarker === 65505) { + if (appData[0] === 69 && appData[1] === 120 && appData[2] === 105 && appData[3] === 102 && appData[4] === 0) { + this.exifBuffer = appData.subarray(5, appData.length); + } + } + if (fileMarker === 65518) { + if (appData[0] === 65 && appData[1] === 100 && appData[2] === 111 && appData[3] === 98 && appData[4] === 101 && appData[5] === 0) { + adobe = { + version: appData[6], + flags0: appData[7] << 8 | appData[8], + flags1: appData[9] << 8 | appData[10], + transformCode: appData[11] + }; + } + } + break; + case 65499: + var quantizationTablesLength = readUint16(); + var quantizationTablesEnd = quantizationTablesLength + offset2 - 2; + while (offset2 < quantizationTablesEnd) { + var quantizationTableSpec = data2[offset2++]; + requestMemoryAllocation(64 * 4); + var tableData = new Int32Array(64); + if (quantizationTableSpec >> 4 === 0) { + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = data2[offset2++]; + } + } else if (quantizationTableSpec >> 4 === 1) { + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = readUint16(); + } + } else + throw new Error("DQT: invalid table spec"); + quantizationTables[quantizationTableSpec & 15] = tableData; + } + break; + case 65472: + // SOF0 (Start of Frame, Baseline DCT) + case 65473: + // SOF1 (Start of Frame, Extended DCT) + case 65474: + readUint16(); + frame = {}; + frame.extended = fileMarker === 65473; + frame.progressive = fileMarker === 65474; + frame.precision = data2[offset2++]; + frame.scanLines = readUint16(); + frame.samplesPerLine = readUint16(); + frame.components = {}; + frame.componentsOrder = []; + var pixelsInFrame = frame.scanLines * frame.samplesPerLine; + if (pixelsInFrame > maxResolutionInPixels) { + var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6); + throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`); + } + var componentsCount = data2[offset2++], componentId; + for (i = 0; i < componentsCount; i++) { + componentId = data2[offset2]; + var h = data2[offset2 + 1] >> 4; + var v = data2[offset2 + 1] & 15; + var qId = data2[offset2 + 2]; + if (h <= 0 || v <= 0) { + throw new Error("Invalid sampling factor, expected values above 0"); + } + frame.componentsOrder.push(componentId); + frame.components[componentId] = { + h, + v, + quantizationIdx: qId + }; + offset2 += 3; + } + prepareComponents(frame); + frames.push(frame); + break; + case 65476: + var huffmanLength = readUint16(); + for (i = 2; i < huffmanLength; ) { + var huffmanTableSpec = data2[offset2++]; + var codeLengths = new Uint8Array(16); + var codeLengthSum = 0; + for (j = 0; j < 16; j++, offset2++) { + codeLengthSum += codeLengths[j] = data2[offset2]; + } + requestMemoryAllocation(16 + codeLengthSum); + var huffmanValues = new Uint8Array(codeLengthSum); + for (j = 0; j < codeLengthSum; j++, offset2++) + huffmanValues[j] = data2[offset2]; + i += 17 + codeLengthSum; + (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues); + } + break; + case 65501: + readUint16(); + resetInterval = readUint16(); + break; + case 65500: + readUint16(); + readUint16(); + break; + case 65498: + readUint16(); + var selectorsCount = data2[offset2++]; + var components = [], component; + for (i = 0; i < selectorsCount; i++) { + component = frame.components[data2[offset2++]]; + var tableSpec = data2[offset2++]; + component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; + component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; + components.push(component); + } + var spectralStart = data2[offset2++]; + var spectralEnd = data2[offset2++]; + var successiveApproximation = data2[offset2++]; + var processed = decodeScan( + data2, + offset2, + frame, + components, + resetInterval, + spectralStart, + spectralEnd, + successiveApproximation >> 4, + successiveApproximation & 15, + this.opts + ); + offset2 += processed; + break; + case 65535: + if (data2[offset2] !== 255) { + offset2--; + } + break; + default: + if (data2[offset2 - 3] == 255 && data2[offset2 - 2] >= 192 && data2[offset2 - 2] <= 254) { + offset2 -= 3; + break; + } else if (fileMarker === 224 || fileMarker == 225) { + if (malformedDataOffset !== -1) { + throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset2 - 1).toString(16)}`); + } + malformedDataOffset = offset2 - 1; + const nextOffset = readUint16(); + if (data2[offset2 + nextOffset - 2] === 255) { + offset2 += nextOffset - 2; + break; + } + } + throw new Error("unknown JPEG marker " + fileMarker.toString(16)); + } + fileMarker = readUint16(); + } + if (frames.length != 1) + throw new Error("only single frame JPEGs supported"); + for (var i = 0; i < frames.length; i++) { + var cp2 = frames[i].components; + for (var j in cp2) { + cp2[j].quantizationTable = quantizationTables[cp2[j].quantizationIdx]; + delete cp2[j].quantizationIdx; + } + } + this.width = frame.samplesPerLine; + this.height = frame.scanLines; + this.jfif = jfif; + this.adobe = adobe; + this.components = []; + for (var i = 0; i < frame.componentsOrder.length; i++) { + var component = frame.components[frame.componentsOrder[i]]; + this.components.push({ + lines: buildComponentData(frame, component), + scaleX: component.h / frame.maxH, + scaleY: component.v / frame.maxV + }); + } + }, + getData: function getData(width, height) { + var scaleX = this.width / width, scaleY = this.height / height; + var component1, component2, component3, component4; + var component1Line, component2Line, component3Line, component4Line; + var x, y; + var offset2 = 0; + var Y, Cb, Cr, K, C, M, Ye, R, G, B; + var colorTransform; + var dataLength = width * height * this.components.length; + requestMemoryAllocation(dataLength); + var data2 = new Uint8Array(dataLength); + switch (this.components.length) { + case 1: + component1 = this.components[0]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | x * component1.scaleX * scaleX]; + data2[offset2++] = Y; + } + } + break; + case 2: + component1 = this.components[0]; + component2 = this.components[1]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; + component2Line = component2.lines[0 | y * component2.scaleY * scaleY]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | x * component1.scaleX * scaleX]; + data2[offset2++] = Y; + Y = component2Line[0 | x * component2.scaleX * scaleX]; + data2[offset2++] = Y; + } + } + break; + case 3: + colorTransform = true; + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.opts.colorTransform !== "undefined") + colorTransform = !!this.opts.colorTransform; + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; + component2Line = component2.lines[0 | y * component2.scaleY * scaleY]; + component3Line = component3.lines[0 | y * component3.scaleY * scaleY]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + R = component1Line[0 | x * component1.scaleX * scaleX]; + G = component2Line[0 | x * component2.scaleX * scaleX]; + B = component3Line[0 | x * component3.scaleX * scaleX]; + } else { + Y = component1Line[0 | x * component1.scaleX * scaleX]; + Cb = component2Line[0 | x * component2.scaleX * scaleX]; + Cr = component3Line[0 | x * component3.scaleX * scaleX]; + R = clampTo8bit(Y + 1.402 * (Cr - 128)); + G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + B = clampTo8bit(Y + 1.772 * (Cb - 128)); + } + data2[offset2++] = R; + data2[offset2++] = G; + data2[offset2++] = B; + } + } + break; + case 4: + if (!this.adobe) + throw new Error("Unsupported color mode (4 components)"); + colorTransform = false; + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.opts.colorTransform !== "undefined") + colorTransform = !!this.opts.colorTransform; + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + component4 = this.components[3]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; + component2Line = component2.lines[0 | y * component2.scaleY * scaleY]; + component3Line = component3.lines[0 | y * component3.scaleY * scaleY]; + component4Line = component4.lines[0 | y * component4.scaleY * scaleY]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + C = component1Line[0 | x * component1.scaleX * scaleX]; + M = component2Line[0 | x * component2.scaleX * scaleX]; + Ye = component3Line[0 | x * component3.scaleX * scaleX]; + K = component4Line[0 | x * component4.scaleX * scaleX]; + } else { + Y = component1Line[0 | x * component1.scaleX * scaleX]; + Cb = component2Line[0 | x * component2.scaleX * scaleX]; + Cr = component3Line[0 | x * component3.scaleX * scaleX]; + K = component4Line[0 | x * component4.scaleX * scaleX]; + C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128)); + M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128)); + } + data2[offset2++] = 255 - C; + data2[offset2++] = 255 - M; + data2[offset2++] = 255 - Ye; + data2[offset2++] = 255 - K; + } + } + break; + default: + throw new Error("Unsupported color mode"); + } + return data2; + }, + copyToImageData: function copyToImageData(imageData, formatAsRGBA) { + var width = imageData.width, height = imageData.height; + var imageDataArray = imageData.data; + var data2 = this.getData(width, height); + var i = 0, j = 0, x, y; + var Y, K, C, M, R, G, B; + switch (this.components.length) { + case 1: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + Y = data2[i++]; + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + case 3: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + R = data2[i++]; + G = data2[i++]; + B = data2[i++]; + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + case 4: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + C = data2[i++]; + M = data2[i++]; + Y = data2[i++]; + K = data2[i++]; + R = 255 - clampTo8bit(C * (1 - K / 255) + K); + G = 255 - clampTo8bit(M * (1 - K / 255) + K); + B = 255 - clampTo8bit(Y * (1 - K / 255) + K); + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + default: + throw new Error("Unsupported color mode"); + } + } + }; + var totalBytesAllocated = 0; + var maxMemoryUsageBytes = 0; + function requestMemoryAllocation(increaseAmount = 0) { + var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount; + if (totalMemoryImpactBytes > maxMemoryUsageBytes) { + var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024); + throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`); + } + totalBytesAllocated = totalMemoryImpactBytes; + } + constructor.resetMaxMemoryUsage = function(maxMemoryUsageBytes_) { + totalBytesAllocated = 0; + maxMemoryUsageBytes = maxMemoryUsageBytes_; + }; + constructor.getBytesAllocated = function() { + return totalBytesAllocated; + }; + constructor.requestMemoryAllocation = requestMemoryAllocation; + return constructor; + }(); + { + module.exports = decode; + } + function decode(jpegData, userOpts = {}) { + var defaultOpts = { + // "undefined" means "Choose whether to transform colors based on the image’s color model." + colorTransform: void 0, + useTArray: false, + formatAsRGBA: true, + tolerantDecoding: true, + maxResolutionInMP: 100, + // Don't decode more than 100 megapixels + maxMemoryUsageInMB: 512 + // Don't decode if memory footprint is more than 512MB + }; + var opts = { ...defaultOpts, ...userOpts }; + var arr = new Uint8Array(jpegData); + var decoder2 = new JpegImage(); + decoder2.opts = opts; + JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024); + decoder2.parse(arr); + var channels = opts.formatAsRGBA ? 4 : 3; + var bytesNeeded = decoder2.width * decoder2.height * channels; + try { + JpegImage.requestMemoryAllocation(bytesNeeded); + var image = { + width: decoder2.width, + height: decoder2.height, + exifBuffer: decoder2.exifBuffer, + data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded) + }; + if (decoder2.comments.length > 0) { + image["comments"] = decoder2.comments; + } + } catch (err) { + if (err instanceof RangeError) { + throw new Error("Could not allocate enough memory for the image. Required: " + bytesNeeded); + } + if (err instanceof ReferenceError) { + if (err.message === "Buffer is not defined") { + throw new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true"); + } + } + throw err; + } + decoder2.copyToImageData(image, opts.formatAsRGBA); + return image; + } + })(decoder); + return decoder.exports; +} +var jpegJs; +var hasRequiredJpegJs; +function requireJpegJs() { + if (hasRequiredJpegJs) return jpegJs; + hasRequiredJpegJs = 1; + var encode = requireEncoder(), decode = requireDecoder(); + jpegJs = { + encode, + decode + }; + return jpegJs; +} +var jpegJsExports = requireJpegJs(); +const jpegLibrary = /* @__PURE__ */ getDefaultExportFromCjs(jpegJsExports); +var Mime_1; +var hasRequiredMime$1; +function requireMime$1() { + if (hasRequiredMime$1) return Mime_1; + hasRequiredMime$1 = 1; + function Mime() { + this._types = /* @__PURE__ */ Object.create(null); + this._extensions = /* @__PURE__ */ Object.create(null); + for (let i = 0; i < arguments.length; i++) { + this.define(arguments[i]); + } + this.define = this.define.bind(this); + this.getType = this.getType.bind(this); + this.getExtension = this.getExtension.bind(this); + } + Mime.prototype.define = function(typeMap, force) { + for (let type2 in typeMap) { + let extensions = typeMap[type2].map(function(t) { + return t.toLowerCase(); + }); + type2 = type2.toLowerCase(); + for (let i = 0; i < extensions.length; i++) { + const ext = extensions[i]; + if (ext[0] === "*") { + continue; + } + if (!force && ext in this._types) { + throw new Error( + 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type2 + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type2 + '".' + ); + } + this._types[ext] = type2; + } + if (force || !this._extensions[type2]) { + const ext = extensions[0]; + this._extensions[type2] = ext[0] !== "*" ? ext : ext.substr(1); + } + } + }; + Mime.prototype.getType = function(path2) { + path2 = String(path2); + let last = path2.replace(/^.*[/\\]/, "").toLowerCase(); + let ext = last.replace(/^.*\./, "").toLowerCase(); + let hasPath = last.length < path2.length; + let hasDot = ext.length < last.length - 1; + return (hasDot || !hasPath) && this._types[ext] || null; + }; + Mime.prototype.getExtension = function(type2) { + type2 = /^\s*([^;\s]*)/.test(type2) && RegExp.$1; + return type2 && this._extensions[type2.toLowerCase()] || null; + }; + Mime_1 = Mime; + return Mime_1; +} +var standard; +var hasRequiredStandard; +function requireStandard() { + if (hasRequiredStandard) return standard; + hasRequiredStandard = 1; + standard = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] }; + return standard; +} +var other; +var hasRequiredOther; +function requireOther() { + if (hasRequiredOther) return other; + hasRequiredOther = 1; + other = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mapbox-vector-tile": ["mvt"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["*stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.ac+xml": ["*ac"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openblox.game+xml": ["obgx"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openstreetmap.data+xml": ["osm"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.rar": ["rar"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.software602.filler.form+xml": ["fo"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.syncml.dmddf+xml": ["ddf"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": ["*dmg"], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": ["*bdoc"], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["*deb", "udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": ["*iso"], "application/x-iwork-keynote-sffkey": ["*key"], "application/x-iwork-numbers-sffnumbers": ["*numbers"], "application/x-iwork-pages-sffpages": ["*pages"], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-keepass2": ["kdbx"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": ["*exe"], "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": ["*prc", "*pdb"], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["*rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["*obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["*xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": ["*m4a"], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": ["*ra"], "audio/x-wav": ["*wav"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "image/prs.btif": ["btif"], "image/prs.pti": ["pti"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.airzip.accelerator.azv": ["azv"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": ["*sub"], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.microsoft.icon": ["ico"], "image/vnd.ms-dds": ["dds"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.pco.b16": ["b16"], "image/vnd.tencent.tap": ["tap"], "image/vnd.valve.source.texture": ["vtf"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/vnd.zbrush.pcx": ["pcx"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["*ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": ["*bmp"], "image/x-pcx": ["*pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/vnd.wfa.wsc": ["wsc"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.opengex": ["ogex"], "model/vnd.parasolid.transmit.binary": ["x_b"], "model/vnd.parasolid.transmit.text": ["x_t"], "model/vnd.sap.vds": ["vds"], "model/vnd.usdz+zip": ["usdz"], "model/vnd.valve.source.compiled-map": ["bsp"], "model/vnd.vtu": ["vtu"], "text/prs.lines.tag": ["dsc"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": ["*org"], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] }; + return other; +} +var mime$2; +var hasRequiredMime; +function requireMime() { + if (hasRequiredMime) return mime$2; + hasRequiredMime = 1; + let Mime = requireMime$1(); + mime$2 = new Mime(requireStandard(), requireOther()); + return mime$2; +} +var mimeExports = requireMime(); +const mimeLibrary = /* @__PURE__ */ getDefaultExportFromCjs(mimeExports); +var concatMap; +var hasRequiredConcatMap; +function requireConcatMap() { + if (hasRequiredConcatMap) return concatMap; + hasRequiredConcatMap = 1; + concatMap = function(xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray2(x)) res.push.apply(res, x); + else res.push(x); + } + return res; + }; + var isArray2 = Array.isArray || function(xs) { + return Object.prototype.toString.call(xs) === "[object Array]"; + }; + return concatMap; +} +var balancedMatch; +var hasRequiredBalancedMatch; +function requireBalancedMatch() { + if (hasRequiredBalancedMatch) return balancedMatch; + hasRequiredBalancedMatch = 1; + balancedMatch = balanced; + function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + var r = range2(a, b, str); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; + } + function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; + } + balanced.range = range2; + function range2(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length) { + result = [left, right]; + } + } + return result; + } + return balancedMatch; +} +var braceExpansion; +var hasRequiredBraceExpansion; +function requireBraceExpansion() { + if (hasRequiredBraceExpansion) return braceExpansion; + hasRequiredBraceExpansion = 1; + var concatMap2 = requireConcatMap(); + var balanced = requireBalancedMatch(); + braceExpansion = expandTop; + var escSlash = "\0SLASH" + Math.random() + "\0"; + var escOpen = "\0OPEN" + Math.random() + "\0"; + var escClose = "\0CLOSE" + Math.random() + "\0"; + var escComma = "\0COMMA" + Math.random() + "\0"; + var escPeriod = "\0PERIOD" + Math.random() + "\0"; + function numeric(str) { + return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); + } + function escapeBraces(str) { + return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); + } + function unescapeBraces(str) { + return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); + } + function parseCommaParts(str) { + if (!str) + return [""]; + var parts = []; + var m = balanced("{", "}", str); + if (!m) + return str.split(","); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[p.length - 1] += "{" + body + "}"; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; + } + function expandTop(str) { + if (!str) + return []; + if (str.substr(0, 2) === "{}") { + str = "\\{\\}" + str.substr(2); + } + return expand(escapeBraces(str), true).map(unescapeBraces); + } + function embrace(str) { + return "{" + str + "}"; + } + function isPadded(el) { + return /^-?0\d/.test(el); + } + function lte(i, y) { + return i <= y; + } + function gte(i, y) { + return i >= y; + } + function expand(str, isTop) { + var expansions = []; + var m = balanced("{", "}", str); + if (!m || /\$$/.test(m.pre)) return [str]; + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(",") >= 0; + if (!isSequence && !isOptions) { + if (m.post.match(/,.*\}/)) { + str = m.pre + "{" + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length ? expand(m.post, false) : [""]; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + var pre = m.pre; + var post = m.post.length ? expand(m.post, false) : [""]; + var N; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + N = []; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === "\\") + c = ""; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join("0"); + if (i < 0) + c = "-" + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap2(n, function(el) { + return expand(el, false); + }); + } + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + return expansions; + } + return braceExpansion; +} +var minimatch_1; +var hasRequiredMinimatch; +function requireMinimatch() { + if (hasRequiredMinimatch) return minimatch_1; + hasRequiredMinimatch = 1; + minimatch_1 = minimatch2; + minimatch2.Minimatch = Minimatch; + var path2 = function() { + try { + return requirePath(); + } catch (e) { + } + }() || { + sep: "/" + }; + minimatch2.sep = path2.sep; + var GLOBSTAR = minimatch2.GLOBSTAR = Minimatch.GLOBSTAR = {}; + var expand = requireBraceExpansion(); + var plTypes = { + "!": { open: "(?:(?!(?:", close: "))[^/]*?)" }, + "?": { open: "(?:", close: ")?" }, + "+": { open: "(?:", close: ")+" }, + "*": { open: "(?:", close: ")*" }, + "@": { open: "(?:", close: ")" } + }; + var qmark = "[^/]"; + var star = qmark + "*?"; + var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; + var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; + var reSpecials = charSet("().*{}+?[]^$\\!"); + function charSet(s) { + return s.split("").reduce(function(set2, c) { + set2[c] = true; + return set2; + }, {}); + } + var slashSplit = /\/+/; + minimatch2.filter = filter; + function filter(pattern, options2) { + options2 = options2 || {}; + return function(p, i, list) { + return minimatch2(p, pattern, options2); + }; + } + function ext(a, b) { + b = b || {}; + var t = {}; + Object.keys(a).forEach(function(k) { + t[k] = a[k]; + }); + Object.keys(b).forEach(function(k) { + t[k] = b[k]; + }); + return t; + } + minimatch2.defaults = function(def) { + if (!def || typeof def !== "object" || !Object.keys(def).length) { + return minimatch2; + } + var orig = minimatch2; + var m = function minimatch3(p, pattern, options2) { + return orig(p, pattern, ext(def, options2)); + }; + m.Minimatch = function Minimatch2(pattern, options2) { + return new orig.Minimatch(pattern, ext(def, options2)); + }; + m.Minimatch.defaults = function defaults(options2) { + return orig.defaults(ext(def, options2)).Minimatch; + }; + m.filter = function filter2(pattern, options2) { + return orig.filter(pattern, ext(def, options2)); + }; + m.defaults = function defaults(options2) { + return orig.defaults(ext(def, options2)); + }; + m.makeRe = function makeRe2(pattern, options2) { + return orig.makeRe(pattern, ext(def, options2)); + }; + m.braceExpand = function braceExpand2(pattern, options2) { + return orig.braceExpand(pattern, ext(def, options2)); + }; + m.match = function(list, pattern, options2) { + return orig.match(list, pattern, ext(def, options2)); + }; + return m; + }; + Minimatch.defaults = function(def) { + return minimatch2.defaults(def).Minimatch; + }; + function minimatch2(p, pattern, options2) { + assertValidPattern(pattern); + if (!options2) options2 = {}; + if (!options2.nocomment && pattern.charAt(0) === "#") { + return false; + } + return new Minimatch(pattern, options2).match(p); + } + function Minimatch(pattern, options2) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options2); + } + assertValidPattern(pattern); + if (!options2) options2 = {}; + pattern = pattern.trim(); + if (!options2.allowWindowsEscape && path2.sep !== "/") { + pattern = pattern.split(path2.sep).join("/"); + } + this.options = options2; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + this.partial = !!options2.partial; + this.make(); + } + Minimatch.prototype.debug = function() { + }; + Minimatch.prototype.make = make; + function make() { + var pattern = this.pattern; + var options2 = this.options; + if (!options2.nocomment && pattern.charAt(0) === "#") { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + this.parseNegate(); + var set2 = this.globSet = this.braceExpand(); + if (options2.debug) this.debug = function debug2() { + console.error.apply(console, arguments); + }; + this.debug(this.pattern, set2); + set2 = this.globParts = set2.map(function(s) { + return s.split(slashSplit); + }); + this.debug(this.pattern, set2); + set2 = set2.map(function(s, si, set3) { + return s.map(this.parse, this); + }, this); + this.debug(this.pattern, set2); + set2 = set2.filter(function(s) { + return s.indexOf(false) === -1; + }); + this.debug(this.pattern, set2); + this.set = set2; + } + Minimatch.prototype.parseNegate = parseNegate; + function parseNegate() { + var pattern = this.pattern; + var negate = false; + var options2 = this.options; + var negateOffset = 0; + if (options2.nonegate) return; + for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) { + negate = !negate; + negateOffset++; + } + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; + } + minimatch2.braceExpand = function(pattern, options2) { + return braceExpand(pattern, options2); + }; + Minimatch.prototype.braceExpand = braceExpand; + function braceExpand(pattern, options2) { + if (!options2) { + if (this instanceof Minimatch) { + options2 = this.options; + } else { + options2 = {}; + } + } + pattern = typeof pattern === "undefined" ? this.pattern : pattern; + assertValidPattern(pattern); + if (options2.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + return [pattern]; + } + return expand(pattern); + } + var MAX_PATTERN_LENGTH = 1024 * 64; + var assertValidPattern = function(pattern) { + if (typeof pattern !== "string") { + throw new TypeError("invalid pattern"); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError("pattern is too long"); + } + }; + Minimatch.prototype.parse = parse4; + var SUBPARSE = {}; + function parse4(pattern, isSub) { + assertValidPattern(pattern); + var options2 = this.options; + if (pattern === "**") { + if (!options2.noglobstar) + return GLOBSTAR; + else + pattern = "*"; + } + if (pattern === "") return ""; + var re2 = ""; + var hasMagic = !!options2.nocase; + var escaping = false; + var patternListStack = []; + var negativeLists = []; + var stateChar; + var inClass = false; + var reClassStart = -1; + var classStart = -1; + var patternStart = pattern.charAt(0) === "." ? "" : options2.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)"; + var self2 = this; + function clearStateChar() { + if (stateChar) { + switch (stateChar) { + case "*": + re2 += star; + hasMagic = true; + break; + case "?": + re2 += qmark; + hasMagic = true; + break; + default: + re2 += "\\" + stateChar; + break; + } + self2.debug("clearStateChar %j %j", stateChar, re2); + stateChar = false; + } + } + for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) { + this.debug("%s %s %s %j", pattern, i, re2, c); + if (escaping && reSpecials[c]) { + re2 += "\\" + c; + escaping = false; + continue; + } + switch (c) { + /* istanbul ignore next */ + case "/": { + return false; + } + case "\\": + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + case "?": + case "*": + case "+": + case "@": + case "!": + this.debug("%s %s %s %j <-- stateChar", pattern, i, re2, c); + if (inClass) { + this.debug(" in class"); + if (c === "!" && i === classStart + 1) c = "^"; + re2 += c; + continue; + } + self2.debug("call clearStateChar %j", stateChar); + clearStateChar(); + stateChar = c; + if (options2.noext) clearStateChar(); + continue; + case "(": + if (inClass) { + re2 += "("; + continue; + } + if (!stateChar) { + re2 += "\\("; + continue; + } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re2.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }); + re2 += stateChar === "!" ? "(?:(?!(?:" : "(?:"; + this.debug("plType %j %j", stateChar, re2); + stateChar = false; + continue; + case ")": + if (inClass || !patternListStack.length) { + re2 += "\\)"; + continue; + } + clearStateChar(); + hasMagic = true; + var pl = patternListStack.pop(); + re2 += pl.close; + if (pl.type === "!") { + negativeLists.push(pl); + } + pl.reEnd = re2.length; + continue; + case "|": + if (inClass || !patternListStack.length || escaping) { + re2 += "\\|"; + escaping = false; + continue; + } + clearStateChar(); + re2 += "|"; + continue; + // these are mostly the same in regexp and glob + case "[": + clearStateChar(); + if (inClass) { + re2 += "\\" + c; + continue; + } + inClass = true; + classStart = i; + reClassStart = re2.length; + re2 += c; + continue; + case "]": + if (i === classStart + 1 || !inClass) { + re2 += "\\" + c; + escaping = false; + continue; + } + var cs = pattern.substring(classStart + 1, i); + try { + RegExp("[" + cs + "]"); + } catch (er) { + var sp = this.parse(cs, SUBPARSE); + re2 = re2.substr(0, reClassStart) + "\\[" + sp[0] + "\\]"; + hasMagic = hasMagic || sp[1]; + inClass = false; + continue; + } + hasMagic = true; + inClass = false; + re2 += c; + continue; + default: + clearStateChar(); + if (escaping) { + escaping = false; + } else if (reSpecials[c] && !(c === "^" && inClass)) { + re2 += "\\"; + } + re2 += c; + } + } + if (inClass) { + cs = pattern.substr(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re2 = re2.substr(0, reClassStart) + "\\[" + sp[0]; + hasMagic = hasMagic || sp[1]; + } + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re2.slice(pl.reStart + pl.open.length); + this.debug("setting tail", re2, pl); + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_, $1, $2) { + if (!$2) { + $2 = "\\"; + } + return $1 + $1 + $2 + "|"; + }); + this.debug("tail=%j\n %s", tail, tail, pl, re2); + var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; + hasMagic = true; + re2 = re2.slice(0, pl.reStart) + t + "\\(" + tail; + } + clearStateChar(); + if (escaping) { + re2 += "\\\\"; + } + var addPatternStart = false; + switch (re2.charAt(0)) { + case "[": + case ".": + case "(": + addPatternStart = true; + } + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n]; + var nlBefore = re2.slice(0, nl.reStart); + var nlFirst = re2.slice(nl.reStart, nl.reEnd - 8); + var nlLast = re2.slice(nl.reEnd - 8, nl.reEnd); + var nlAfter = re2.slice(nl.reEnd); + nlLast += nlAfter; + var openParensBefore = nlBefore.split("(").length - 1; + var cleanAfter = nlAfter; + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ""); + } + nlAfter = cleanAfter; + var dollar = ""; + if (nlAfter === "" && isSub !== SUBPARSE) { + dollar = "$"; + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; + re2 = newRe; + } + if (re2 !== "" && hasMagic) { + re2 = "(?=.)" + re2; + } + if (addPatternStart) { + re2 = patternStart + re2; + } + if (isSub === SUBPARSE) { + return [re2, hasMagic]; + } + if (!hasMagic) { + return globUnescape(pattern); + } + var flags = options2.nocase ? "i" : ""; + try { + var regExp = new RegExp("^" + re2 + "$", flags); + } catch (er) { + return new RegExp("$."); + } + regExp._glob = pattern; + regExp._src = re2; + return regExp; + } + minimatch2.makeRe = function(pattern, options2) { + return new Minimatch(pattern, options2 || {}).makeRe(); + }; + Minimatch.prototype.makeRe = makeRe; + function makeRe() { + if (this.regexp || this.regexp === false) return this.regexp; + var set2 = this.set; + if (!set2.length) { + this.regexp = false; + return this.regexp; + } + var options2 = this.options; + var twoStar = options2.noglobstar ? star : options2.dot ? twoStarDot : twoStarNoDot; + var flags = options2.nocase ? "i" : ""; + var re2 = set2.map(function(pattern) { + return pattern.map(function(p) { + return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src; + }).join("\\/"); + }).join("|"); + re2 = "^(?:" + re2 + ")$"; + if (this.negate) re2 = "^(?!" + re2 + ").*$"; + try { + this.regexp = new RegExp(re2, flags); + } catch (ex) { + this.regexp = false; + } + return this.regexp; + } + minimatch2.match = function(list, pattern, options2) { + options2 = options2 || {}; + var mm = new Minimatch(pattern, options2); + list = list.filter(function(f) { + return mm.match(f); + }); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; + }; + Minimatch.prototype.match = function match(f, partial) { + if (typeof partial === "undefined") partial = this.partial; + this.debug("match", f, this.pattern); + if (this.comment) return false; + if (this.empty) return f === ""; + if (f === "/" && partial) return true; + var options2 = this.options; + if (path2.sep !== "/") { + f = f.split(path2.sep).join("/"); + } + f = f.split(slashSplit); + this.debug(this.pattern, "split", f); + var set2 = this.set; + this.debug(this.pattern, "set", set2); + var filename; + var i; + for (i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break; + } + for (i = 0; i < set2.length; i++) { + var pattern = set2[i]; + var file = f; + if (options2.matchBase && pattern.length === 1) { + file = [filename]; + } + var hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options2.flipNegate) return true; + return !this.negate; + } + } + if (options2.flipNegate) return false; + return this.negate; + }; + Minimatch.prototype.matchOne = function(file, pattern, partial) { + var options2 = this.options; + this.debug( + "matchOne", + { "this": this, file, pattern } + ); + this.debug("matchOne", file.length, pattern.length); + for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + this.debug("matchOne loop"); + var p = pattern[pi]; + var f = file[fi]; + this.debug(pattern, p, f); + if (p === false) return false; + if (p === GLOBSTAR) { + this.debug("GLOBSTAR", [pattern, p, f]); + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug("** at the end"); + for (; fi < fl; fi++) { + if (file[fi] === "." || file[fi] === ".." || !options2.dot && file[fi].charAt(0) === ".") return false; + } + return true; + } + while (fr < fl) { + var swallowee = file[fr]; + this.debug("\nglobstar while", file, fr, pattern, pr, swallowee); + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug("globstar found match!", fr, fl, swallowee); + return true; + } else { + if (swallowee === "." || swallowee === ".." || !options2.dot && swallowee.charAt(0) === ".") { + this.debug("dot detected!", file, fr, pattern, pr); + break; + } + this.debug("globstar swallow a segment, and continue"); + fr++; + } + } + if (partial) { + this.debug("\n>>> no match, partial?", file, fr, pattern, pr); + if (fr === fl) return true; + } + return false; + } + var hit; + if (typeof p === "string") { + hit = f === p; + this.debug("string match", p, f, hit); + } else { + hit = f.match(p); + this.debug("pattern match", p, f, hit); + } + if (!hit) return false; + } + if (fi === fl && pi === pl) { + return true; + } else if (fi === fl) { + return partial; + } else if (pi === pl) { + return fi === fl - 1 && file[fi] === ""; + } + throw new Error("wtf?"); + }; + function globUnescape(s) { + return s.replace(/\\(.)/g, "$1"); + } + function regExpEscape(s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + } + return minimatch_1; +} +var minimatchExports = requireMinimatch(); +const minimatchLibrary = /* @__PURE__ */ getDefaultExportFromCjs(minimatchExports); +const require$$1 = /* @__PURE__ */ getAugmentedNamespace(child_process$1); +var isWsl = { exports: {} }; +var isDocker_1; +var hasRequiredIsDocker; +function requireIsDocker() { + if (hasRequiredIsDocker) return isDocker_1; + hasRequiredIsDocker = 1; + const fs2 = require$$2$1; + let isDocker; + function hasDockerEnv() { + try { + fs2.statSync("/.dockerenv"); + return true; + } catch (_) { + return false; + } + } + function hasDockerCGroup() { + try { + return fs2.readFileSync("/proc/self/cgroup", "utf8").includes("docker"); + } catch (_) { + return false; + } + } + isDocker_1 = () => { + if (isDocker === void 0) { + isDocker = hasDockerEnv() || hasDockerCGroup(); + } + return isDocker; + }; + return isDocker_1; +} +var hasRequiredIsWsl; +function requireIsWsl() { + if (hasRequiredIsWsl) return isWsl.exports; + hasRequiredIsWsl = 1; + const os2 = requireBrowser$g(); + const fs2 = require$$2$1; + const isDocker = requireIsDocker(); + const isWsl$1 = () => { + if (process.platform !== "linux") { + return false; + } + if (os2.release().toLowerCase().includes("microsoft")) { + if (isDocker()) { + return false; + } + return true; + } + try { + return fs2.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false; + } catch (_) { + return false; + } + }; + if (define_process_env_default.__IS_WSL_TEST__) { + isWsl.exports = isWsl$1; + } else { + isWsl.exports = isWsl$1(); + } + return isWsl.exports; +} +var defineLazyProp; +var hasRequiredDefineLazyProp; +function requireDefineLazyProp() { + if (hasRequiredDefineLazyProp) return defineLazyProp; + hasRequiredDefineLazyProp = 1; + defineLazyProp = (object, propertyName, fn) => { + const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true }); + Object.defineProperty(object, propertyName, { + configurable: true, + enumerable: true, + get() { + const result = fn(); + define(result); + return result; + }, + set(value) { + define(value); + } + }); + return object; + }; + return defineLazyProp; +} +var open_1; +var hasRequiredOpen; +function requireOpen() { + if (hasRequiredOpen) return open_1; + hasRequiredOpen = 1; + const path2 = requirePath(); + const childProcess = require$$1; + const { promises: fs2, constants: fsConstants } = require$$2$1; + const isWsl2 = requireIsWsl(); + const isDocker = requireIsDocker(); + const defineLazyProperty = requireDefineLazyProp(); + const localXdgOpenPath = path2.join(__dirname, "xdg-open"); + const { platform, arch } = process; + const getWslDrivesMountPoint = /* @__PURE__ */ (() => { + const defaultMountPoint = "/mnt/"; + let mountPoint; + return async function() { + if (mountPoint) { + return mountPoint; + } + const configFilePath = "/etc/wsl.conf"; + let isConfigFileExists = false; + try { + await fs2.access(configFilePath, fsConstants.F_OK); + isConfigFileExists = true; + } catch { + } + if (!isConfigFileExists) { + return defaultMountPoint; + } + const configContent = await fs2.readFile(configFilePath, { encoding: "utf8" }); + const configMountPoint = new RegExp("(?.*)", "g").exec(configContent); + if (!configMountPoint) { + return defaultMountPoint; + } + mountPoint = configMountPoint.groups.mountPoint.trim(); + mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`; + return mountPoint; + }; + })(); + const pTryEach = async (array, mapper) => { + let latestError; + for (const item of array) { + try { + return await mapper(item); + } catch (error2) { + latestError = error2; + } + } + throw latestError; + }; + const baseOpen = async (options2) => { + options2 = { + wait: false, + background: false, + newInstance: false, + allowNonzeroExitCode: false, + ...options2 + }; + if (Array.isArray(options2.app)) { + return pTryEach(options2.app, (singleApp) => baseOpen({ + ...options2, + app: singleApp + })); + } + let { name: app, arguments: appArguments = [] } = options2.app || {}; + appArguments = [...appArguments]; + if (Array.isArray(app)) { + return pTryEach(app, (appName) => baseOpen({ + ...options2, + app: { + name: appName, + arguments: appArguments + } + })); + } + let command2; + const cliArguments = []; + const childProcessOptions = {}; + if (platform === "darwin") { + command2 = "open"; + if (options2.wait) { + cliArguments.push("--wait-apps"); + } + if (options2.background) { + cliArguments.push("--background"); + } + if (options2.newInstance) { + cliArguments.push("--new"); + } + if (app) { + cliArguments.push("-a", app); + } + } else if (platform === "win32" || isWsl2 && !isDocker()) { + const mountPoint = await getWslDrivesMountPoint(); + command2 = isWsl2 ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${define_process_env_default.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; + cliArguments.push( + "-NoProfile", + "-NonInteractive", + "–ExecutionPolicy", + "Bypass", + "-EncodedCommand" + ); + if (!isWsl2) { + childProcessOptions.windowsVerbatimArguments = true; + } + const encodedArguments = ["Start"]; + if (options2.wait) { + encodedArguments.push("-Wait"); + } + if (app) { + encodedArguments.push(`"\`"${app}\`""`, "-ArgumentList"); + if (options2.target) { + appArguments.unshift(options2.target); + } + } else if (options2.target) { + encodedArguments.push(`"${options2.target}"`); + } + if (appArguments.length > 0) { + appArguments = appArguments.map((arg) => `"\`"${arg}\`""`); + encodedArguments.push(appArguments.join(",")); + } + options2.target = Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64"); + } else { + if (app) { + command2 = app; + } else { + const isBundled = !__dirname || __dirname === "/"; + let exeLocalXdgOpen = false; + try { + await fs2.access(localXdgOpenPath, fsConstants.X_OK); + exeLocalXdgOpen = true; + } catch { + } + const useSystemXdgOpen = process.versions.electron || platform === "android" || isBundled || !exeLocalXdgOpen; + command2 = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath; + } + if (appArguments.length > 0) { + cliArguments.push(...appArguments); + } + if (!options2.wait) { + childProcessOptions.stdio = "ignore"; + childProcessOptions.detached = true; + } + } + if (options2.target) { + cliArguments.push(options2.target); + } + if (platform === "darwin" && appArguments.length > 0) { + cliArguments.push("--args", ...appArguments); + } + const subprocess = childProcess.spawn(command2, cliArguments, childProcessOptions); + if (options2.wait) { + return new Promise((resolve, reject) => { + subprocess.once("error", reject); + subprocess.once("close", (exitCode) => { + if (options2.allowNonzeroExitCode && exitCode > 0) { + reject(new Error(`Exited with code ${exitCode}`)); + return; + } + resolve(subprocess); + }); + }); + } + subprocess.unref(); + return subprocess; + }; + const open2 = (target, options2) => { + if (typeof target !== "string") { + throw new TypeError("Expected a `target`"); + } + return baseOpen({ + ...options2, + target + }); + }; + const openApp = (name, options2) => { + if (typeof name !== "string") { + throw new TypeError("Expected a `name`"); + } + const { arguments: appArguments = [] } = options2 || {}; + if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) { + throw new TypeError("Expected `appArguments` as Array type"); + } + return baseOpen({ + ...options2, + app: { + name, + arguments: appArguments + } + }); + }; + function detectArchBinary(binary2) { + if (typeof binary2 === "string" || Array.isArray(binary2)) { + return binary2; + } + const { [arch]: archBinary } = binary2; + if (!archBinary) { + throw new Error(`${arch} is not supported`); + } + return archBinary; + } + function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) { + if (wsl && isWsl2) { + return detectArchBinary(wsl); + } + if (!platformBinary) { + throw new Error(`${platform} is not supported`); + } + return detectArchBinary(platformBinary); + } + const apps = {}; + defineLazyProperty(apps, "chrome", () => detectPlatformBinary({ + darwin: "google chrome", + win32: "chrome", + linux: ["google-chrome", "google-chrome-stable", "chromium"] + }, { + wsl: { + ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe", + x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"] + } + })); + defineLazyProperty(apps, "firefox", () => detectPlatformBinary({ + darwin: "firefox", + win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe", + linux: "firefox" + }, { + wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" + })); + defineLazyProperty(apps, "edge", () => detectPlatformBinary({ + darwin: "microsoft edge", + win32: "msedge", + linux: ["microsoft-edge", "microsoft-edge-dev"] + }, { + wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" + })); + open2.apps = apps; + open2.openApp = openApp; + open_1 = open2; + return open_1; +} +var openExports = requireOpen(); +const openLibrary = /* @__PURE__ */ getDefaultExportFromCjs(openExports); +var png = {}; +var parserAsync = { exports: {} }; +var lib = {}; +var binding = {}; +var zstream; +var hasRequiredZstream; +function requireZstream() { + if (hasRequiredZstream) return zstream; + hasRequiredZstream = 1; + function ZStream() { + this.input = null; + this.next_in = 0; + this.avail_in = 0; + this.total_in = 0; + this.output = null; + this.next_out = 0; + this.avail_out = 0; + this.total_out = 0; + this.msg = ""; + this.state = null; + this.data_type = 2; + this.adler = 0; + } + zstream = ZStream; + return zstream; +} +var deflate = {}; +var common$1 = {}; +var hasRequiredCommon$1; +function requireCommon$1() { + if (hasRequiredCommon$1) return common$1; + hasRequiredCommon$1 = 1; + (function(exports) { + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key2) { + return Object.prototype.hasOwnProperty.call(obj, key2); + } + exports.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source2 = sources.shift(); + if (!source2) { + continue; + } + if (typeof source2 !== "object") { + throw new TypeError(source2 + "must be non-object"); + } + for (var p in source2) { + if (_has(source2, p)) { + obj[p] = source2[p]; + } + } + } + return obj; + }; + exports.shrinkBuf = function(buf, size) { + if (buf.length === size) { + return buf; + } + if (buf.subarray) { + return buf.subarray(0, size); + } + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src2, src_offs, len, dest_offs) { + if (src2.subarray && dest.subarray) { + dest.set(src2.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src2[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function(chunks) { + var i, l, len, pos, chunk, result; + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src2, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src2[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports.setTyped = function(on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } + }; + exports.setTyped(TYPED_OK); + })(common$1); + return common$1; +} +var trees = {}; +var hasRequiredTrees; +function requireTrees() { + if (hasRequiredTrees) return trees; + hasRequiredTrees = 1; + var utils2 = requireCommon$1(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var extra_lbits = ( + /* extra bits for each length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0] + ); + var extra_dbits = ( + /* extra bits for each distance code */ + [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13] + ); + var extra_blbits = ( + /* extra bits for each bit length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7] + ); + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist2) { + return dist2 < 256 ? _dist_code[dist2] : _dist_code[256 + (dist2 >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value, length) { + if (s.bi_valid > Buf_size - length) { + s.bi_buf |= value << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value >> Buf_size - s.bi_valid; + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= value << s.bi_valid & 65535; + s.bi_valid += length; + } + } + function send_code(s, c, tree) { + send_bits( + s, + tree[c * 2], + tree[c * 2 + 1] + /*.Len*/ + ); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base2 = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) { + continue; + } + s.bl_count[bits]++; + xbits = 0; + if (n >= base2) { + xbits = extra[n - base2]; + } + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + } + if (overflow === 0) { + return; + } + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = code + bl_count[bits - 1] << 1; + } + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) { + continue; + } + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length; + var code; + var dist2; + var bl_count = new Array(MAX_BITS + 1); + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < 1 << extra_lbits[code]; n++) { + _length_code[length++] = code; + } + } + _length_code[length - 1] = code; + dist2 = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist2; + for (n = 0; n < 1 << extra_dbits[code]; n++) { + _dist_code[dist2++] = code; + } + } + dist2 >>= 7; + for (; code < D_CODES; code++) { + base_dist[code] = dist2 << 7; + for (n = 0; n < 1 << extra_dbits[code] - 7; n++) { + _dist_code[256 + dist2++] = code; + } + } + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0; n < L_CODES; n++) { + s.dyn_ltree[n * 2] = 0; + } + for (n = 0; n < D_CODES; n++) { + s.dyn_dtree[n * 2] = 0; + } + for (n = 0; n < BL_CODES; n++) { + s.bl_tree[n * 2] = 0; + } + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + { + put_short(s, len); + put_short(s, ~len); + } + utils2.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k) { + var v = s.heap[k]; + var j = k << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + s.heap[k] = s.heap[j]; + k = j; + j <<= 1; + } + s.heap[k] = v; + } + function compress_block(s, ltree, dtree) { + var dist2; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) { + do { + dist2 = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist2 === 0) { + send_code(s, lc, ltree); + } else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist2--; + code = d_code(dist2); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist2 -= base_dist[code]; + send_bits(s, dist2, extra); + } + } + } while (lx < s.last_lit); + } + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node2; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0; n < elems; n++) { + if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else { + tree[n * 2 + 1] = 0; + } + } + while (s.heap_len < 2) { + node2 = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node2 * 2] = 1; + s.depth[node2] = 0; + s.opt_len--; + if (has_stree) { + s.static_len -= stree[node2 * 2 + 1]; + } + } + desc.max_code = max_code; + for (n = s.heap_len >> 1; n >= 1; n--) { + pqdownheap(s, tree, n); + } + node2 = elems; + do { + n = s.heap[ + 1 + /*SMALLEST*/ + ]; + s.heap[ + 1 + /*SMALLEST*/ + ] = s.heap[s.heap_len--]; + pqdownheap( + s, + tree, + 1 + /*SMALLEST*/ + ); + m = s.heap[ + 1 + /*SMALLEST*/ + ]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node2 * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node2] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node2; + s.heap[ + 1 + /*SMALLEST*/ + ] = node2++; + pqdownheap( + s, + tree, + 1 + /*SMALLEST*/ + ); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[ + 1 + /*SMALLEST*/ + ]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + s.bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen !== prevlen) { + s.bl_tree[curlen * 2]++; + } + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]++; + } else { + s.bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) { + break; + } + } + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0; rank < blcodes; rank++) { + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + } + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) { + return Z_BINARY; + } + } + if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] !== 0) { + return Z_TEXT; + } + } + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last) { + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); + copy_block(s, buf, stored_len); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + } else { + opt_lenb = static_lenb = stored_len + 5; + } + if (stored_len + 4 <= opt_lenb && buf !== -1) { + _tr_stored_block(s, buf, stored_len, last); + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last) { + bi_windup(s); + } + } + function _tr_tally(s, dist2, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist2 >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist2 & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist2 === 0) { + s.dyn_ltree[lc * 2]++; + } else { + s.matches++; + dist2--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist2) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + trees._tr_init = _tr_init; + trees._tr_stored_block = _tr_stored_block; + trees._tr_flush_block = _tr_flush_block; + trees._tr_tally = _tr_tally; + trees._tr_align = _tr_align; + return trees; +} +var adler32_1; +var hasRequiredAdler32; +function requireAdler32() { + if (hasRequiredAdler32) return adler32_1; + hasRequiredAdler32 = 1; + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2e3 ? 2e3 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + adler32_1 = adler32; + return adler32_1; +} +var crc32_1; +var hasRequiredCrc32; +function requireCrc32() { + if (hasRequiredCrc32) return crc32_1; + hasRequiredCrc32 = 1; + function makeTable() { + var c, table = []; + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc2, buf, len, pos) { + var t = crcTable, end = pos + len; + crc2 ^= -1; + for (var i = pos; i < end; i++) { + crc2 = crc2 >>> 8 ^ t[(crc2 ^ buf[i]) & 255]; + } + return crc2 ^ -1; + } + crc32_1 = crc32; + return crc32_1; +} +var messages; +var hasRequiredMessages; +function requireMessages() { + if (hasRequiredMessages) return messages; + hasRequiredMessages = 1; + messages = { + 2: "need dictionary", + /* Z_NEED_DICT 2 */ + 1: "stream end", + /* Z_STREAM_END 1 */ + 0: "", + /* Z_OK 0 */ + "-1": "file error", + /* Z_ERRNO (-1) */ + "-2": "stream error", + /* Z_STREAM_ERROR (-2) */ + "-3": "data error", + /* Z_DATA_ERROR (-3) */ + "-4": "insufficient memory", + /* Z_MEM_ERROR (-4) */ + "-5": "buffer error", + /* Z_BUF_ERROR (-5) */ + "-6": "incompatible version" + /* Z_VERSION_ERROR (-6) */ + }; + return messages; +} +var hasRequiredDeflate; +function requireDeflate() { + if (hasRequiredDeflate) return deflate; + hasRequiredDeflate = 1; + var utils2 = requireCommon$1(); + var trees2 = requireTrees(); + var adler32 = requireAdler32(); + var crc32 = requireCrc32(); + var msg = requireMessages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + utils2.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + function flush_block_only(s, last) { + trees2._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + strm.avail_in -= len; + utils2.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { + continue; + } + scan += 2; + match++; + do { + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils2.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + for (; ; ) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush) { + var hash_head; + var bflush; + for (; ; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + } + if (s.match_length >= MIN_MATCH) { + bflush = trees2._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + bflush = trees2._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush) { + var hash_head; + var bflush; + var max_insert; + for (; ; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) { + s.match_length = MIN_MATCH - 1; + } + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + bflush = trees2._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } else if (s.match_available) { + bflush = trees2._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + flush_block_only(s, false); + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + bflush = trees2._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (; ; ) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + } + if (s.match_length >= MIN_MATCH) { + bflush = trees2._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + bflush = trees2._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush) { + var bflush; + for (; ; ) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; + } + } + s.match_length = 0; + bflush = trees2._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table; + configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), + /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), + /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), + /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), + /* 3 */ + new Config(4, 4, 16, 16, deflate_slow), + /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), + /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), + /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), + /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), + /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) + /* 9 max compression */ + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils2.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils2.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils2.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils2.Buf16(MAX_BITS + 1); + this.heap = new utils2.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils2.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) { + s.wrap = -s.wrap; + } + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees2._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + if (strm.state.wrap !== 2) { + return Z_STREAM_ERROR; + } + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { + return Z_STREAM_ERROR; + } + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + if (windowBits === 8) { + windowBits = 9; + } + var s = new DeflateState(); + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils2.Buf8(s.w_size * 2); + s.head = new utils2.Buf16(s.hash_size); + s.prev = new utils2.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils2.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate$1(strm, flush) { + var old_flush, s; + var beg, val; + if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) { + return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush; + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte( + s, + (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= level_flags << 6; + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + } + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees2._tr_align(s); + } else if (flush !== Z_BLOCK) { + trees2._tr_stored_block(s, 0, 0, false); + if (flush === Z_FULL_FLUSH) { + zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + status = strm.state.status; + if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) { + return err(strm, Z_STREAM_ERROR); + } + strm.state = null; + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) { + return Z_STREAM_ERROR; + } + if (wrap === 1) { + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils2.Buf8(s.w_size); + utils2.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + deflate.deflateInit = deflateInit; + deflate.deflateInit2 = deflateInit2; + deflate.deflateReset = deflateReset; + deflate.deflateResetKeep = deflateResetKeep; + deflate.deflateSetHeader = deflateSetHeader; + deflate.deflate = deflate$1; + deflate.deflateEnd = deflateEnd; + deflate.deflateSetDictionary = deflateSetDictionary; + deflate.deflateInfo = "pako deflate (from Nodeca project)"; + return deflate; +} +var inflate = {}; +var inffast; +var hasRequiredInffast; +function requireInffast() { + if (hasRequiredInffast) return inffast; + hasRequiredInffast = 1; + var BAD = 30; + var TYPE = 12; + inffast = function inflate_fast(strm, start) { + var state2; + var _in; + var last; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist2; + var from2; + var from_source; + var input, output; + state2 = strm.state; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state2.dmax; + wsize = state2.wsize; + whave = state2.whave; + wnext = state2.wnext; + s_window = state2.window; + hold = state2.hold; + bits = state2.bits; + lcode = state2.lencode; + dcode = state2.distcode; + lmask = (1 << state2.lenbits) - 1; + dmask = (1 << state2.distbits) - 1; + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + for (; ; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) { + output[_out++] = here & 65535; + } else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + for (; ; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist2 = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist2 += hold & (1 << op) - 1; + if (dist2 > dmax) { + strm.msg = "invalid distance too far back"; + state2.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist2 > op) { + op = dist2 - op; + if (op > whave) { + if (state2.sane) { + strm.msg = "invalid distance too far back"; + state2.mode = BAD; + break top; + } + } + from2 = 0; + from_source = s_window; + if (wnext === 0) { + from2 += wsize - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from2++]; + } while (--op); + from2 = _out - dist2; + from_source = output; + } + } else if (wnext < op) { + from2 += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from2++]; + } while (--op); + from2 = 0; + if (wnext < len) { + op = wnext; + len -= op; + do { + output[_out++] = s_window[from2++]; + } while (--op); + from2 = _out - dist2; + from_source = output; + } + } + } else { + from2 += wnext - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from2++]; + } while (--op); + from2 = _out - dist2; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from2++]; + output[_out++] = from_source[from2++]; + output[_out++] = from_source[from2++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from2++]; + if (len > 1) { + output[_out++] = from_source[from2++]; + } + } + } else { + from2 = _out - dist2; + do { + output[_out++] = output[from2++]; + output[_out++] = output[from2++]; + output[_out++] = output[from2++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from2++]; + if (len > 1) { + output[_out++] = output[from2++]; + } + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state2.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state2.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state2.mode = BAD; + break top; + } + break; + } + } while (_in < last && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state2.hold = hold; + state2.bits = bits; + return; + }; + return inffast; +} +var inftrees; +var hasRequiredInftrees; +function requireInftrees() { + if (hasRequiredInftrees) return inftrees; + hasRequiredInftrees = 1; + var utils2 = requireCommon$1(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + /* Length codes 257..285 base */ + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 15, + 17, + 19, + 23, + 27, + 31, + 35, + 43, + 51, + 59, + 67, + 83, + 99, + 115, + 131, + 163, + 195, + 227, + 258, + 0, + 0 + ]; + var lext = [ + /* Length codes 257..285 extra */ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + /* Distance codes 0..29 base */ + 1, + 2, + 3, + 4, + 5, + 7, + 9, + 13, + 17, + 25, + 33, + 49, + 65, + 97, + 129, + 193, + 257, + 385, + 513, + 769, + 1025, + 1537, + 2049, + 3073, + 4097, + 6145, + 8193, + 12289, + 16385, + 24577, + 0, + 0 + ]; + var dext = [ + /* Distance codes 0..29 extra */ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + inftrees = function inflate_table(type2, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min2 = 0, max2 = 0; + var root = 0; + var curr = 0; + var drop = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill; + var low; + var mask; + var next; + var base2 = null; + var base_index = 0; + var end; + var count = new utils2.Buf16(MAXBITS + 1); + var offs = new utils2.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + root = bits; + for (max2 = MAXBITS; max2 >= 1; max2--) { + if (count[max2] !== 0) { + break; + } + } + if (root > max2) { + root = max2; + } + if (max2 === 0) { + table[table_index++] = 1 << 24 | 64 << 16 | 0; + table[table_index++] = 1 << 24 | 64 << 16 | 0; + opts.bits = 1; + return 0; + } + for (min2 = 1; min2 < max2; min2++) { + if (count[min2] !== 0) { + break; + } + } + if (root < min2) { + root = min2; + } + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } + } + if (left > 0 && (type2 === CODES || max2 !== 1)) { + return -1; + } + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + if (type2 === CODES) { + base2 = extra = work; + end = 19; + } else if (type2 === LENS) { + base2 = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base2 = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min2; + next = table_index; + curr = root; + drop = 0; + low = -1; + used = 1 << root; + mask = used - 1; + if (type2 === LENS && used > ENOUGH_LENS || type2 === DISTS && used > ENOUGH_DISTS) { + return 1; + } + for (; ; ) { + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base2[base_index + work[sym]]; + } else { + here_op = 32 + 64; + here_val = 0; + } + incr = 1 << len - drop; + fill = 1 << curr; + min2 = fill; + do { + fill -= incr; + table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill !== 0); + incr = 1 << len - 1; + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + sym++; + if (--count[len] === 0) { + if (len === max2) { + break; + } + len = lens[lens_index + work[sym]]; + } + if (len > root && (huff & mask) !== low) { + if (drop === 0) { + drop = root; + } + next += min2; + curr = len - drop; + left = 1 << curr; + while (curr + drop < max2) { + left -= count[curr + drop]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + used += 1 << curr; + if (type2 === LENS && used > ENOUGH_LENS || type2 === DISTS && used > ENOUGH_DISTS) { + return 1; + } + low = huff & mask; + table[low] = root << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) { + table[next + huff] = len - drop << 24 | 64 << 16 | 0; + } + opts.bits = root; + return 0; + }; + return inftrees; +} +var hasRequiredInflate; +function requireInflate() { + if (hasRequiredInflate) return inflate; + hasRequiredInflate = 1; + var utils2 = requireCommon$1(); + var adler32 = requireAdler32(); + var crc32 = requireCrc32(); + var inflate_fast = requireInffast(); + var inflate_table = requireInftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var MAX_WBITS = 15; + var DEF_WBITS = MAX_WBITS; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + this.flags = 0; + this.dmax = 0; + this.check = 0; + this.total = 0; + this.head = null; + this.wbits = 0; + this.wsize = 0; + this.whave = 0; + this.wnext = 0; + this.window = null; + this.hold = 0; + this.bits = 0; + this.length = 0; + this.offset = 0; + this.extra = 0; + this.lencode = null; + this.distcode = null; + this.lenbits = 0; + this.distbits = 0; + this.ncode = 0; + this.nlen = 0; + this.ndist = 0; + this.have = 0; + this.next = null; + this.lens = new utils2.Buf16(320); + this.work = new utils2.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state2; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state2 = strm.state; + strm.total_in = strm.total_out = state2.total = 0; + strm.msg = ""; + if (state2.wrap) { + strm.adler = state2.wrap & 1; + } + state2.mode = HEAD; + state2.last = 0; + state2.havedict = 0; + state2.dmax = 32768; + state2.head = null; + state2.hold = 0; + state2.bits = 0; + state2.lencode = state2.lendyn = new utils2.Buf32(ENOUGH_LENS); + state2.distcode = state2.distdyn = new utils2.Buf32(ENOUGH_DISTS); + state2.sane = 1; + state2.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state2; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state2 = strm.state; + state2.wsize = 0; + state2.whave = 0; + state2.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state2; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state2 = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state2.window !== null && state2.wbits !== windowBits) { + state2.window = null; + } + state2.wrap = wrap; + state2.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state2; + if (!strm) { + return Z_STREAM_ERROR; + } + state2 = new InflateState(); + strm.state = state2; + state2.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null; + } + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix, distfix; + function fixedtables(state2) { + if (virgin) { + var sym; + lenfix = new utils2.Buf32(512); + distfix = new utils2.Buf32(32); + sym = 0; + while (sym < 144) { + state2.lens[sym++] = 8; + } + while (sym < 256) { + state2.lens[sym++] = 9; + } + while (sym < 280) { + state2.lens[sym++] = 7; + } + while (sym < 288) { + state2.lens[sym++] = 8; + } + inflate_table(LENS, state2.lens, 0, 288, lenfix, 0, state2.work, { bits: 9 }); + sym = 0; + while (sym < 32) { + state2.lens[sym++] = 5; + } + inflate_table(DISTS, state2.lens, 0, 32, distfix, 0, state2.work, { bits: 5 }); + virgin = false; + } + state2.lencode = lenfix; + state2.lenbits = 9; + state2.distcode = distfix; + state2.distbits = 5; + } + function updatewindow(strm, src2, end, copy) { + var dist2; + var state2 = strm.state; + if (state2.window === null) { + state2.wsize = 1 << state2.wbits; + state2.wnext = 0; + state2.whave = 0; + state2.window = new utils2.Buf8(state2.wsize); + } + if (copy >= state2.wsize) { + utils2.arraySet(state2.window, src2, end - state2.wsize, state2.wsize, 0); + state2.wnext = 0; + state2.whave = state2.wsize; + } else { + dist2 = state2.wsize - state2.wnext; + if (dist2 > copy) { + dist2 = copy; + } + utils2.arraySet(state2.window, src2, end - copy, dist2, state2.wnext); + copy -= dist2; + if (copy) { + utils2.arraySet(state2.window, src2, end - copy, copy, 0); + state2.wnext = copy; + state2.whave = state2.wsize; + } else { + state2.wnext += dist2; + if (state2.wnext === state2.wsize) { + state2.wnext = 0; + } + if (state2.whave < state2.wsize) { + state2.whave += dist2; + } + } + } + return 0; + } + function inflate$1(strm, flush) { + var state2; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy; + var from2; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils2.Buf8(4); + var opts; + var n; + var order = ( + /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] + ); + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { + return Z_STREAM_ERROR; + } + state2 = strm.state; + if (state2.mode === TYPE) { + state2.mode = TYPEDO; + } + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state2.hold; + bits = state2.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: + for (; ; ) { + switch (state2.mode) { + case HEAD: + if (state2.wrap === 0) { + state2.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state2.wrap & 2 && hold === 35615) { + state2.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state2.check = crc32(state2.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state2.mode = FLAGS; + break; + } + state2.flags = 0; + if (state2.head) { + state2.head.done = false; + } + if (!(state2.wrap & 1) || /* check if zlib header allowed */ + (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state2.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state2.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state2.wbits === 0) { + state2.wbits = len; + } else if (len > state2.wbits) { + strm.msg = "invalid window size"; + state2.mode = BAD; + break; + } + state2.dmax = 1 << len; + strm.adler = state2.check = 1; + state2.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.flags = hold; + if ((state2.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state2.mode = BAD; + break; + } + if (state2.flags & 57344) { + strm.msg = "unknown header flags set"; + state2.mode = BAD; + break; + } + if (state2.head) { + state2.head.text = hold >> 8 & 1; + } + if (state2.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state2.check = crc32(state2.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state2.mode = TIME; + /* falls through */ + case TIME: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state2.head) { + state2.head.time = hold; + } + if (state2.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state2.check = crc32(state2.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state2.mode = OS; + /* falls through */ + case OS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state2.head) { + state2.head.xflags = hold & 255; + state2.head.os = hold >> 8; + } + if (state2.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state2.check = crc32(state2.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state2.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state2.flags & 1024) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.length = hold; + if (state2.head) { + state2.head.extra_len = hold; + } + if (state2.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state2.check = crc32(state2.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state2.head) { + state2.head.extra = null; + } + state2.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state2.flags & 1024) { + copy = state2.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state2.head) { + len = state2.head.extra_len - state2.length; + if (!state2.head.extra) { + state2.head.extra = new Array(state2.head.extra_len); + } + utils2.arraySet( + state2.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + } + if (state2.flags & 512) { + state2.check = crc32(state2.check, input, copy, next); + } + have -= copy; + next += copy; + state2.length -= copy; + } + if (state2.length) { + break inf_leave; + } + } + state2.length = 0; + state2.mode = NAME; + /* falls through */ + case NAME: + if (state2.flags & 2048) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state2.head && len && state2.length < 65536) { + state2.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + if (state2.flags & 512) { + state2.check = crc32(state2.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state2.head) { + state2.head.name = null; + } + state2.length = 0; + state2.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state2.flags & 4096) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state2.head && len && state2.length < 65536) { + state2.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state2.flags & 512) { + state2.check = crc32(state2.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state2.head) { + state2.head.comment = null; + } + state2.mode = HCRC; + /* falls through */ + case HCRC: + if (state2.flags & 512) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state2.check & 65535)) { + strm.msg = "header crc mismatch"; + state2.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state2.head) { + state2.head.hcrc = state2.flags >> 9 & 1; + state2.head.done = true; + } + strm.adler = state2.check = 0; + state2.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state2.check = zswap32(hold); + hold = 0; + bits = 0; + state2.mode = DICT; + /* falls through */ + case DICT: + if (state2.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state2.hold = hold; + state2.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state2.check = 1; + state2.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case TYPEDO: + if (state2.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state2.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state2.mode = STORED; + break; + case 1: + fixedtables(state2); + state2.mode = LEN_; + if (flush === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state2.mode = TABLE; + break; + case 3: + strm.msg = "invalid block type"; + state2.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state2.mode = BAD; + break; + } + state2.length = hold & 65535; + hold = 0; + bits = 0; + state2.mode = COPY_; + if (flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case COPY_: + state2.mode = COPY; + /* falls through */ + case COPY: + copy = state2.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + utils2.arraySet(output, input, next, copy, put); + have -= copy; + next += copy; + left -= copy; + put += copy; + state2.length -= copy; + break; + } + state2.mode = TYPE; + break; + case TABLE: + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state2.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state2.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state2.nlen > 286 || state2.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state2.mode = BAD; + break; + } + state2.have = 0; + state2.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state2.have < state2.ncode) { + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.lens[order[state2.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state2.have < 19) { + state2.lens[order[state2.have++]] = 0; + } + state2.lencode = state2.lendyn; + state2.lenbits = 7; + opts = { bits: state2.lenbits }; + ret = inflate_table(CODES, state2.lens, 0, 19, state2.lencode, 0, state2.work, opts); + state2.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state2.mode = BAD; + break; + } + state2.have = 0; + state2.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state2.have < state2.nlen + state2.ndist) { + for (; ; ) { + here = state2.lencode[hold & (1 << state2.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state2.lens[state2.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state2.have === 0) { + strm.msg = "invalid bit length repeat"; + state2.mode = BAD; + break; + } + len = state2.lens[state2.have - 1]; + copy = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state2.have + copy > state2.nlen + state2.ndist) { + strm.msg = "invalid bit length repeat"; + state2.mode = BAD; + break; + } + while (copy--) { + state2.lens[state2.have++] = len; + } + } + } + if (state2.mode === BAD) { + break; + } + if (state2.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state2.mode = BAD; + break; + } + state2.lenbits = 9; + opts = { bits: state2.lenbits }; + ret = inflate_table(LENS, state2.lens, 0, state2.nlen, state2.lencode, 0, state2.work, opts); + state2.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state2.mode = BAD; + break; + } + state2.distbits = 6; + state2.distcode = state2.distdyn; + opts = { bits: state2.distbits }; + ret = inflate_table(DISTS, state2.lens, state2.nlen, state2.ndist, state2.distcode, 0, state2.work, opts); + state2.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state2.mode = BAD; + break; + } + state2.mode = LEN_; + if (flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case LEN_: + state2.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state2.hold = hold; + state2.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state2.hold; + bits = state2.bits; + if (state2.mode === TYPE) { + state2.back = -1; + } + break; + } + state2.back = 0; + for (; ; ) { + here = state2.lencode[hold & (1 << state2.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ; ) { + here = state2.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state2.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state2.back += here_bits; + state2.length = here_val; + if (here_op === 0) { + state2.mode = LIT; + break; + } + if (here_op & 32) { + state2.back = -1; + state2.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state2.mode = BAD; + break; + } + state2.extra = here_op & 15; + state2.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state2.extra) { + n = state2.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.length += hold & (1 << state2.extra) - 1; + hold >>>= state2.extra; + bits -= state2.extra; + state2.back += state2.extra; + } + state2.was = state2.length; + state2.mode = DIST; + /* falls through */ + case DIST: + for (; ; ) { + here = state2.distcode[hold & (1 << state2.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ; ) { + here = state2.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state2.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state2.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state2.mode = BAD; + break; + } + state2.offset = here_val; + state2.extra = here_op & 15; + state2.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state2.extra) { + n = state2.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state2.offset += hold & (1 << state2.extra) - 1; + hold >>>= state2.extra; + bits -= state2.extra; + state2.back += state2.extra; + } + if (state2.offset > state2.dmax) { + strm.msg = "invalid distance too far back"; + state2.mode = BAD; + break; + } + state2.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state2.offset > copy) { + copy = state2.offset - copy; + if (copy > state2.whave) { + if (state2.sane) { + strm.msg = "invalid distance too far back"; + state2.mode = BAD; + break; + } + } + if (copy > state2.wnext) { + copy -= state2.wnext; + from2 = state2.wsize - copy; + } else { + from2 = state2.wnext - copy; + } + if (copy > state2.length) { + copy = state2.length; + } + from_source = state2.window; + } else { + from_source = output; + from2 = put - state2.offset; + copy = state2.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state2.length -= copy; + do { + output[put++] = from_source[from2++]; + } while (--copy); + if (state2.length === 0) { + state2.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state2.length; + left--; + state2.mode = LEN; + break; + case CHECK: + if (state2.wrap) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state2.total += _out; + if (_out) { + strm.adler = state2.check = /*UPDATE(state.check, put - _out, _out);*/ + state2.flags ? crc32(state2.check, output, _out, put - _out) : adler32(state2.check, output, _out, put - _out); + } + _out = left; + if ((state2.flags ? hold : zswap32(hold)) !== state2.check) { + strm.msg = "incorrect data check"; + state2.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state2.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state2.wrap && state2.flags) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state2.total & 4294967295)) { + strm.msg = "incorrect length check"; + state2.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state2.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state2.hold = hold; + state2.bits = bits; + if (state2.wsize || _out !== strm.avail_out && state2.mode < BAD && (state2.mode < CHECK || flush !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state2.total += _out; + if (state2.wrap && _out) { + strm.adler = state2.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + state2.flags ? crc32(state2.check, output, _out, strm.next_out - _out) : adler32(state2.check, output, _out, strm.next_out - _out); + } + strm.data_type = state2.bits + (state2.last ? 64 : 0) + (state2.mode === TYPE ? 128 : 0) + (state2.mode === LEN_ || state2.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + var state2 = strm.state; + if (state2.window) { + state2.window = null; + } + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state2; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state2 = strm.state; + if ((state2.wrap & 2) === 0) { + return Z_STREAM_ERROR; + } + state2.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state2; + var dictid; + var ret; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state2 = strm.state; + if (state2.wrap !== 0 && state2.mode !== DICT) { + return Z_STREAM_ERROR; + } + if (state2.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state2.check) { + return Z_DATA_ERROR; + } + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state2.mode = MEM; + return Z_MEM_ERROR; + } + state2.havedict = 1; + return Z_OK; + } + inflate.inflateReset = inflateReset; + inflate.inflateReset2 = inflateReset2; + inflate.inflateResetKeep = inflateResetKeep; + inflate.inflateInit = inflateInit; + inflate.inflateInit2 = inflateInit2; + inflate.inflate = inflate$1; + inflate.inflateEnd = inflateEnd; + inflate.inflateGetHeader = inflateGetHeader; + inflate.inflateSetDictionary = inflateSetDictionary; + inflate.inflateInfo = "pako inflate (from Nodeca project)"; + return inflate; +} +var constants$4; +var hasRequiredConstants$4; +function requireConstants$4() { + if (hasRequiredConstants$4) return constants$4; + hasRequiredConstants$4 = 1; + constants$4 = { + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type + }; + return constants$4; +} +var hasRequiredBinding; +function requireBinding() { + if (hasRequiredBinding) return binding; + hasRequiredBinding = 1; + (function(exports) { + var assert2 = requireAssert(); + var Zstream = requireZstream(); + var zlib_deflate = requireDeflate(); + var zlib_inflate = requireInflate(); + var constants2 = requireConstants$4(); + for (var key2 in constants2) { + exports[key2] = constants2[key2]; + } + exports.NONE = 0; + exports.DEFLATE = 1; + exports.INFLATE = 2; + exports.GZIP = 3; + exports.GUNZIP = 4; + exports.DEFLATERAW = 5; + exports.INFLATERAW = 6; + exports.UNZIP = 7; + var GZIP_HEADER_ID1 = 31; + var GZIP_HEADER_ID2 = 139; + function Zlib(mode) { + if (typeof mode !== "number" || mode < exports.DEFLATE || mode > exports.UNZIP) { + throw new TypeError("Bad argument"); + } + this.dictionary = null; + this.err = 0; + this.flush = 0; + this.init_done = false; + this.level = 0; + this.memLevel = 0; + this.mode = mode; + this.strategy = 0; + this.windowBits = 0; + this.write_in_progress = false; + this.pending_close = false; + this.gzip_id_bytes_read = 0; + } + Zlib.prototype.close = function() { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + this.pending_close = false; + assert2(this.init_done, "close before init"); + assert2(this.mode <= exports.UNZIP); + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + this.mode = exports.NONE; + this.dictionary = null; + }; + Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); + }; + Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); + }; + Zlib.prototype._write = function(async2, flush, input, in_off, in_len, out, out_off, out_len) { + assert2.equal(arguments.length, 8); + assert2(this.init_done, "write before init"); + assert2(this.mode !== exports.NONE, "already finalized"); + assert2.equal(false, this.write_in_progress, "write already in progress"); + assert2.equal(false, this.pending_close, "close is pending"); + this.write_in_progress = true; + assert2.equal(false, flush === void 0, "must provide flush value"); + this.write_in_progress = true; + if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { + throw new Error("Invalid flush value"); + } + if (input == null) { + input = Buffer.alloc(0); + in_len = 0; + in_off = 0; + } + this.strm.avail_in = in_len; + this.strm.input = input; + this.strm.next_in = in_off; + this.strm.avail_out = out_len; + this.strm.output = out; + this.strm.next_out = out_off; + this.flush = flush; + if (!async2) { + this._process(); + if (this._checkError()) { + return this._afterSync(); + } + return; + } + var self2 = this; + process.nextTick(function() { + self2._process(); + self2._after(); + }); + return this; + }; + Zlib.prototype._afterSync = function() { + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + this.write_in_progress = false; + return [avail_in, avail_out]; + }; + Zlib.prototype._process = function() { + var next_expected_header_byte = null; + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports.UNZIP: + if (this.strm.avail_in > 0) { + next_expected_header_byte = this.strm.next_in; + } + switch (this.gzip_id_bytes_read) { + case 0: + if (next_expected_header_byte === null) { + break; + } + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { + this.gzip_id_bytes_read = 1; + next_expected_header_byte++; + if (this.strm.avail_in === 1) { + break; + } + } else { + this.mode = exports.INFLATE; + break; + } + // fallthrough + case 1: + if (next_expected_header_byte === null) { + break; + } + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { + this.gzip_id_bytes_read = 2; + this.mode = exports.GUNZIP; + } else { + this.mode = exports.INFLATE; + } + break; + default: + throw new Error("invalid number of gzip magic number bytes read"); + } + // fallthrough + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + this.err = zlib_inflate.inflate( + this.strm, + this.flush + // If data was encoded with dictionary + ); + if (this.err === exports.Z_NEED_DICT && this.dictionary) { + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports.Z_OK) { + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports.Z_DATA_ERROR) { + this.err = exports.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0) { + this.reset(); + this.err = zlib_inflate.inflate(this.strm, this.flush); + } + break; + default: + throw new Error("Unknown mode " + this.mode); + } + }; + Zlib.prototype._checkError = function() { + switch (this.err) { + case exports.Z_OK: + case exports.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { + this._error("unexpected end of file"); + return false; + } + break; + case exports.Z_STREAM_END: + break; + case exports.Z_NEED_DICT: + if (this.dictionary == null) { + this._error("Missing dictionary"); + } else { + this._error("Bad dictionary"); + } + return false; + default: + this._error("Zlib error"); + return false; + } + return true; + }; + Zlib.prototype._after = function() { + if (!this._checkError()) { + return; + } + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + this.write_in_progress = false; + this.callback(avail_in, avail_out); + if (this.pending_close) { + this.close(); + } + }; + Zlib.prototype._error = function(message) { + if (this.strm.msg) { + message = this.strm.msg; + } + this.onerror( + message, + this.err + // no hope of rescue. + ); + this.write_in_progress = false; + if (this.pending_close) { + this.close(); + } + }; + Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) { + assert2(arguments.length === 4 || arguments.length === 5, "init(windowBits, level, memLevel, strategy, [dictionary])"); + assert2(windowBits >= 8 && windowBits <= 15, "invalid windowBits"); + assert2(level >= -1 && level <= 9, "invalid compression level"); + assert2(memLevel >= 1 && memLevel <= 9, "invalid memlevel"); + assert2(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, "invalid strategy"); + this._init(level, windowBits, memLevel, strategy, dictionary); + this._setDictionary(); + }; + Zlib.prototype.params = function() { + throw new Error("deflateParams Not supported"); + }; + Zlib.prototype.reset = function() { + this._reset(); + this._setDictionary(); + }; + Zlib.prototype._init = function(level, windowBits, memLevel, strategy, dictionary) { + this.level = level; + this.windowBits = windowBits; + this.memLevel = memLevel; + this.strategy = strategy; + this.flush = exports.Z_NO_FLUSH; + this.err = exports.Z_OK; + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { + this.windowBits += 16; + } + if (this.mode === exports.UNZIP) { + this.windowBits += 32; + } + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + this.strm = new Zstream(); + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error("Unknown mode " + this.mode); + } + if (this.err !== exports.Z_OK) { + this._error("Init error"); + } + this.dictionary = dictionary; + this.write_in_progress = false; + this.init_done = true; + }; + Zlib.prototype._setDictionary = function() { + if (this.dictionary == null) { + return; + } + this.err = exports.Z_OK; + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + } + if (this.err !== exports.Z_OK) { + this._error("Failed to set dictionary"); + } + }; + Zlib.prototype._reset = function() { + this.err = exports.Z_OK; + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + case exports.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + case exports.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + } + if (this.err !== exports.Z_OK) { + this._error("Failed to reset stream"); + } + }; + exports.Zlib = Zlib; + })(binding); + return binding; +} +var hasRequiredLib; +function requireLib() { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + (function(exports) { + var Buffer2 = requireBuffer$2().Buffer; + var Transform = requireBrowser$h().Transform; + var binding2 = requireBinding(); + var util2 = requireUtil$5(); + var assert2 = requireAssert().ok; + var kMaxLength = requireBuffer$2().kMaxLength; + var kRangeErrorMessage = "Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes"; + binding2.Z_MIN_WINDOWBITS = 8; + binding2.Z_MAX_WINDOWBITS = 15; + binding2.Z_DEFAULT_WINDOWBITS = 15; + binding2.Z_MIN_CHUNK = 64; + binding2.Z_MAX_CHUNK = Infinity; + binding2.Z_DEFAULT_CHUNK = 16 * 1024; + binding2.Z_MIN_MEMLEVEL = 1; + binding2.Z_MAX_MEMLEVEL = 9; + binding2.Z_DEFAULT_MEMLEVEL = 8; + binding2.Z_MIN_LEVEL = -1; + binding2.Z_MAX_LEVEL = 9; + binding2.Z_DEFAULT_LEVEL = binding2.Z_DEFAULT_COMPRESSION; + var bkeys = Object.keys(binding2); + for (var bk = 0; bk < bkeys.length; bk++) { + var bkey = bkeys[bk]; + if (bkey.match(/^Z/)) { + Object.defineProperty(exports, bkey, { + enumerable: true, + value: binding2[bkey], + writable: false + }); + } + } + var codes = { + Z_OK: binding2.Z_OK, + Z_STREAM_END: binding2.Z_STREAM_END, + Z_NEED_DICT: binding2.Z_NEED_DICT, + Z_ERRNO: binding2.Z_ERRNO, + Z_STREAM_ERROR: binding2.Z_STREAM_ERROR, + Z_DATA_ERROR: binding2.Z_DATA_ERROR, + Z_MEM_ERROR: binding2.Z_MEM_ERROR, + Z_BUF_ERROR: binding2.Z_BUF_ERROR, + Z_VERSION_ERROR: binding2.Z_VERSION_ERROR + }; + var ckeys = Object.keys(codes); + for (var ck = 0; ck < ckeys.length; ck++) { + var ckey = ckeys[ck]; + codes[codes[ckey]] = ckey; + } + Object.defineProperty(exports, "codes", { + enumerable: true, + value: Object.freeze(codes), + writable: false + }); + exports.Deflate = Deflate; + exports.Inflate = Inflate; + exports.Gzip = Gzip; + exports.Gunzip = Gunzip; + exports.DeflateRaw = DeflateRaw; + exports.InflateRaw = InflateRaw; + exports.Unzip = Unzip; + exports.createDeflate = function(o) { + return new Deflate(o); + }; + exports.createInflate = function(o) { + return new Inflate(o); + }; + exports.createDeflateRaw = function(o) { + return new DeflateRaw(o); + }; + exports.createInflateRaw = function(o) { + return new InflateRaw(o); + }; + exports.createGzip = function(o) { + return new Gzip(o); + }; + exports.createGunzip = function(o) { + return new Gunzip(o); + }; + exports.createUnzip = function(o) { + return new Unzip(o); + }; + exports.deflate = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer2, callback); + }; + exports.deflateSync = function(buffer2, opts) { + return zlibBufferSync(new Deflate(opts), buffer2); + }; + exports.gzip = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer2, callback); + }; + exports.gzipSync = function(buffer2, opts) { + return zlibBufferSync(new Gzip(opts), buffer2); + }; + exports.deflateRaw = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer2, callback); + }; + exports.deflateRawSync = function(buffer2, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer2); + }; + exports.unzip = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer2, callback); + }; + exports.unzipSync = function(buffer2, opts) { + return zlibBufferSync(new Unzip(opts), buffer2); + }; + exports.inflate = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer2, callback); + }; + exports.inflateSync = function(buffer2, opts) { + return zlibBufferSync(new Inflate(opts), buffer2); + }; + exports.gunzip = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer2, callback); + }; + exports.gunzipSync = function(buffer2, opts) { + return zlibBufferSync(new Gunzip(opts), buffer2); + }; + exports.inflateRaw = function(buffer2, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer2, callback); + }; + exports.inflateRawSync = function(buffer2, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer2); + }; + function zlibBuffer(engine, buffer2, callback) { + var buffers = []; + var nread = 0; + engine.on("error", onError); + engine.on("end", onEnd); + engine.end(buffer2); + flow(); + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once("readable", flow); + } + function onError(err) { + engine.removeListener("end", onEnd); + engine.removeListener("readable", flow); + callback(err); + } + function onEnd() { + var buf; + var err = null; + if (nread >= kMaxLength) { + err = new RangeError(kRangeErrorMessage); + } else { + buf = Buffer2.concat(buffers, nread); + } + buffers = []; + engine.close(); + callback(err, buf); + } + } + function zlibBufferSync(engine, buffer2) { + if (typeof buffer2 === "string") buffer2 = Buffer2.from(buffer2); + if (!Buffer2.isBuffer(buffer2)) throw new TypeError("Not a string or buffer"); + var flushFlag = engine._finishFlushFlag; + return engine._processChunk(buffer2, flushFlag); + } + function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding2.DEFLATE); + } + function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding2.INFLATE); + } + function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding2.GZIP); + } + function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding2.GUNZIP); + } + function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding2.DEFLATERAW); + } + function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding2.INFLATERAW); + } + function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding2.UNZIP); + } + function isValidFlushFlag(flag) { + return flag === binding2.Z_NO_FLUSH || flag === binding2.Z_PARTIAL_FLUSH || flag === binding2.Z_SYNC_FLUSH || flag === binding2.Z_FULL_FLUSH || flag === binding2.Z_FINISH || flag === binding2.Z_BLOCK; + } + function Zlib(opts, mode) { + var _this = this; + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + Transform.call(this, opts); + if (opts.flush && !isValidFlushFlag(opts.flush)) { + throw new Error("Invalid flush flag: " + opts.flush); + } + if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { + throw new Error("Invalid flush flag: " + opts.finishFlush); + } + this._flushFlag = opts.flush || binding2.Z_NO_FLUSH; + this._finishFlushFlag = typeof opts.finishFlush !== "undefined" ? opts.finishFlush : binding2.Z_FINISH; + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error("Invalid chunk size: " + opts.chunkSize); + } + } + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error("Invalid windowBits: " + opts.windowBits); + } + } + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { + throw new Error("Invalid compression level: " + opts.level); + } + } + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error("Invalid memLevel: " + opts.memLevel); + } + } + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error("Invalid strategy: " + opts.strategy); + } + } + if (opts.dictionary) { + if (!Buffer2.isBuffer(opts.dictionary)) { + throw new Error("Invalid dictionary: it should be a Buffer instance"); + } + } + this._handle = new binding2.Zlib(mode); + var self2 = this; + this._hadError = false; + this._handle.onerror = function(message, errno) { + _close(self2); + self2._hadError = true; + var error2 = new Error(message); + error2.errno = errno; + error2.code = exports.codes[errno]; + self2.emit("error", error2); + }; + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === "number") level = opts.level; + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === "number") strategy = opts.strategy; + this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); + this._buffer = Buffer2.allocUnsafe(this._chunkSize); + this._offset = 0; + this._level = level; + this._strategy = strategy; + this.once("end", this.close); + Object.defineProperty(this, "_closed", { + get: function() { + return !_this._handle; + }, + configurable: true, + enumerable: true + }); + } + util2.inherits(Zlib, Transform); + Zlib.prototype.params = function(level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { + throw new RangeError("Invalid compression level: " + level); + } + if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError("Invalid strategy: " + strategy); + } + if (this._level !== level || this._strategy !== strategy) { + var self2 = this; + this.flush(binding2.Z_SYNC_FLUSH, function() { + assert2(self2._handle, "zlib binding closed"); + self2._handle.params(level, strategy); + if (!self2._hadError) { + self2._level = level; + self2._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } + }; + Zlib.prototype.reset = function() { + assert2(this._handle, "zlib binding closed"); + return this._handle.reset(); + }; + Zlib.prototype._flush = function(callback) { + this._transform(Buffer2.alloc(0), "", callback); + }; + Zlib.prototype.flush = function(kind, callback) { + var _this2 = this; + var ws2 = this._writableState; + if (typeof kind === "function" || kind === void 0 && !callback) { + callback = kind; + kind = binding2.Z_FULL_FLUSH; + } + if (ws2.ended) { + if (callback) process.nextTick(callback); + } else if (ws2.ending) { + if (callback) this.once("end", callback); + } else if (ws2.needDrain) { + if (callback) { + this.once("drain", function() { + return _this2.flush(kind, callback); + }); + } + } else { + this._flushFlag = kind; + this.write(Buffer2.alloc(0), "", callback); + } + }; + Zlib.prototype.close = function(callback) { + _close(this, callback); + process.nextTick(emitCloseNT, this); + }; + function _close(engine, callback) { + if (callback) process.nextTick(callback); + if (!engine._handle) return; + engine._handle.close(); + engine._handle = null; + } + function emitCloseNT(self2) { + self2.emit("close"); + } + Zlib.prototype._transform = function(chunk, encoding2, cb) { + var flushFlag; + var ws2 = this._writableState; + var ending = ws2.ending || ws2.ended; + var last = ending && (!chunk || ws2.length === chunk.length); + if (chunk !== null && !Buffer2.isBuffer(chunk)) return cb(new Error("invalid input")); + if (!this._handle) return cb(new Error("zlib binding closed")); + if (last) flushFlag = this._finishFlushFlag; + else { + flushFlag = this._flushFlag; + if (chunk.length >= ws2.length) { + this._flushFlag = this._opts.flush || binding2.Z_NO_FLUSH; + } + } + this._processChunk(chunk, flushFlag, cb); + }; + Zlib.prototype._processChunk = function(chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + var self2 = this; + var async2 = typeof cb === "function"; + if (!async2) { + var buffers = []; + var nread = 0; + var error2; + this.on("error", function(er) { + error2 = er; + }); + assert2(this._handle, "zlib binding closed"); + do { + var res = this._handle.writeSync( + flushFlag, + chunk, + // in + inOff, + // in_off + availInBefore, + // in_len + this._buffer, + // out + this._offset, + //out_off + availOutBefore + ); + } while (!this._hadError && callback(res[0], res[1])); + if (this._hadError) { + throw error2; + } + if (nread >= kMaxLength) { + _close(this); + throw new RangeError(kRangeErrorMessage); + } + var buf = Buffer2.concat(buffers, nread); + _close(this); + return buf; + } + assert2(this._handle, "zlib binding closed"); + var req = this._handle.write( + flushFlag, + chunk, + // in + inOff, + // in_off + availInBefore, + // in_len + this._buffer, + // out + this._offset, + //out_off + availOutBefore + ); + req.buffer = chunk; + req.callback = callback; + function callback(availInAfter, availOutAfter) { + if (this) { + this.buffer = null; + this.callback = null; + } + if (self2._hadError) return; + var have = availOutBefore - availOutAfter; + assert2(have >= 0, "have should not go down"); + if (have > 0) { + var out = self2._buffer.slice(self2._offset, self2._offset + have); + self2._offset += have; + if (async2) { + self2.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + if (availOutAfter === 0 || self2._offset >= self2._chunkSize) { + availOutBefore = self2._chunkSize; + self2._offset = 0; + self2._buffer = Buffer2.allocUnsafe(self2._chunkSize); + } + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + if (!async2) return true; + var newReq = self2._handle.write(flushFlag, chunk, inOff, availInBefore, self2._buffer, self2._offset, self2._chunkSize); + newReq.callback = callback; + newReq.buffer = chunk; + return; + } + if (!async2) return false; + cb(); + } + }; + util2.inherits(Deflate, Zlib); + util2.inherits(Inflate, Zlib); + util2.inherits(Gzip, Zlib); + util2.inherits(Gunzip, Zlib); + util2.inherits(DeflateRaw, Zlib); + util2.inherits(InflateRaw, Zlib); + util2.inherits(Unzip, Zlib); + })(lib); + return lib; +} +var chunkstream = { exports: {} }; +var hasRequiredChunkstream; +function requireChunkstream() { + if (hasRequiredChunkstream) return chunkstream.exports; + hasRequiredChunkstream = 1; + let util2 = requireUtil$5(); + let Stream2 = requireBrowser$h(); + let ChunkStream = chunkstream.exports = function() { + Stream2.call(this); + this._buffers = []; + this._buffered = 0; + this._reads = []; + this._paused = false; + this._encoding = "utf8"; + this.writable = true; + }; + util2.inherits(ChunkStream, Stream2); + ChunkStream.prototype.read = function(length, callback) { + this._reads.push({ + length: Math.abs(length), + // if length < 0 then at most this length + allowLess: length < 0, + func: callback + }); + process.nextTick( + (function() { + this._process(); + if (this._paused && this._reads && this._reads.length > 0) { + this._paused = false; + this.emit("drain"); + } + }).bind(this) + ); + }; + ChunkStream.prototype.write = function(data2, encoding2) { + if (!this.writable) { + this.emit("error", new Error("Stream not writable")); + return false; + } + let dataBuffer; + if (Buffer.isBuffer(data2)) { + dataBuffer = data2; + } else { + dataBuffer = Buffer.from(data2, encoding2 || this._encoding); + } + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + this._process(); + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + return this.writable && !this._paused; + }; + ChunkStream.prototype.end = function(data2, encoding2) { + if (data2) { + this.write(data2, encoding2); + } + this.writable = false; + if (!this._buffers) { + return; + } + if (this._buffers.length === 0) { + this._end(); + } else { + this._buffers.push(null); + this._process(); + } + }; + ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + ChunkStream.prototype._end = function() { + if (this._reads.length > 0) { + this.emit("error", new Error("Unexpected end of input")); + } + this.destroy(); + }; + ChunkStream.prototype.destroy = function() { + if (!this._buffers) { + return; + } + this.writable = false; + this._reads = null; + this._buffers = null; + this.emit("close"); + }; + ChunkStream.prototype._processReadAllowingLess = function(read2) { + this._reads.shift(); + let smallerBuf = this._buffers[0]; + if (smallerBuf.length > read2.length) { + this._buffered -= read2.length; + this._buffers[0] = smallerBuf.slice(read2.length); + read2.func.call(this, smallerBuf.slice(0, read2.length)); + } else { + this._buffered -= smallerBuf.length; + this._buffers.shift(); + read2.func.call(this, smallerBuf); + } + }; + ChunkStream.prototype._processRead = function(read2) { + this._reads.shift(); + let pos = 0; + let count = 0; + let data2 = Buffer.alloc(read2.length); + while (pos < read2.length) { + let buf = this._buffers[count++]; + let len = Math.min(buf.length, read2.length - pos); + buf.copy(data2, pos, 0, len); + pos += len; + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + if (count > 0) { + this._buffers.splice(0, count); + } + this._buffered -= read2.length; + read2.func.call(this, data2); + }; + ChunkStream.prototype._process = function() { + try { + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + let read2 = this._reads[0]; + if (read2.allowLess) { + this._processReadAllowingLess(read2); + } else if (this._buffered >= read2.length) { + this._processRead(read2); + } else { + break; + } + } + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } + }; + return chunkstream.exports; +} +var filterParseAsync = { exports: {} }; +var filterParse = { exports: {} }; +var interlace = {}; +var hasRequiredInterlace; +function requireInterlace() { + if (hasRequiredInterlace) return interlace; + hasRequiredInterlace = 1; + let imagePasses = [ + { + // pass 1 - 1px + x: [0], + y: [0] + }, + { + // pass 2 - 1px + x: [4], + y: [0] + }, + { + // pass 3 - 2px + x: [0, 4], + y: [4] + }, + { + // pass 4 - 4px + x: [2, 6], + y: [0, 4] + }, + { + // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6] + }, + { + // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6] + }, + { + // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7] + } + ]; + interlace.getImagePasses = function(width, height) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; + }; + interlace.getInterlaceIterator = function(width) { + return function(x, y, pass) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = (x - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = (y - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; + }; + return interlace; +} +var paethPredictor; +var hasRequiredPaethPredictor; +function requirePaethPredictor() { + if (hasRequiredPaethPredictor) return paethPredictor; + hasRequiredPaethPredictor = 1; + paethPredictor = function paethPredictor2(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; + }; + return paethPredictor; +} +var hasRequiredFilterParse; +function requireFilterParse() { + if (hasRequiredFilterParse) return filterParse.exports; + hasRequiredFilterParse = 1; + let interlaceUtils = requireInterlace(); + let paethPredictor2 = requirePaethPredictor(); + function getByteWidth(width, bpp, depth) { + let byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; + } + let Filter = filterParse.exports = function(bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace2 = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + this._imageIndex = 0; + this._images = []; + if (interlace2) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0 + }); + } + } else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height, + lineIndex: 0 + }); + } + if (depth === 8) { + this._xComparison = bpp; + } else if (depth === 16) { + this._xComparison = bpp * 2; + } else { + this._xComparison = 1; + } + }; + Filter.prototype.start = function() { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); + }; + Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } + }; + Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) { + let lastLine = this._lastLine; + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } + }; + Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } + }; + Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor2(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } + }; + Filter.prototype._reverseFilterLine = function(rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error("Unrecognised filter type - " + filter); + } + } + this.write(unfilteredLine); + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } else { + this._lastLine = unfilteredLine; + } + if (currentImage) { + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } else { + this._lastLine = null; + this.complete(); + } + }; + return filterParse.exports; +} +var hasRequiredFilterParseAsync; +function requireFilterParseAsync() { + if (hasRequiredFilterParseAsync) return filterParseAsync.exports; + hasRequiredFilterParseAsync = 1; + let util2 = requireUtil$5(); + let ChunkStream = requireChunkstream(); + let Filter = requireFilterParse(); + let FilterAsync = filterParseAsync.exports = function(bitmapInfo) { + ChunkStream.call(this); + let buffers = []; + let that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function(buffer2) { + buffers.push(buffer2); + }, + complete: function() { + that.emit("complete", Buffer.concat(buffers)); + } + }); + this._filter.start(); + }; + util2.inherits(FilterAsync, ChunkStream); + return filterParseAsync.exports; +} +var parser = { exports: {} }; +var constants$3; +var hasRequiredConstants$3; +function requireConstants$3() { + if (hasRequiredConstants$3) return constants$3; + hasRequiredConstants$3 = 1; + constants$3 = { + PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10], + TYPE_IHDR: 1229472850, + TYPE_IEND: 1229278788, + TYPE_IDAT: 1229209940, + TYPE_PLTE: 1347179589, + TYPE_tRNS: 1951551059, + // eslint-disable-line camelcase + TYPE_gAMA: 1732332865, + // eslint-disable-line camelcase + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, + // e.g. grayscale and alpha + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4 + }, + GAMMA_DIVISION: 1e5 + }; + return constants$3; +} +var crc = { exports: {} }; +var hasRequiredCrc; +function requireCrc() { + if (hasRequiredCrc) return crc.exports; + hasRequiredCrc = 1; + let crcTable = []; + (function() { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 3988292384 ^ currentCrc >>> 1; + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } + })(); + let CrcCalculator = crc.exports = function() { + this._crc = -1; + }; + CrcCalculator.prototype.write = function(data2) { + for (let i = 0; i < data2.length; i++) { + this._crc = crcTable[(this._crc ^ data2[i]) & 255] ^ this._crc >>> 8; + } + return true; + }; + CrcCalculator.prototype.crc32 = function() { + return this._crc ^ -1; + }; + CrcCalculator.crc32 = function(buf) { + let crc2 = -1; + for (let i = 0; i < buf.length; i++) { + crc2 = crcTable[(crc2 ^ buf[i]) & 255] ^ crc2 >>> 8; + } + return crc2 ^ -1; + }; + return crc.exports; +} +var hasRequiredParser; +function requireParser() { + if (hasRequiredParser) return parser.exports; + hasRequiredParser = 1; + let constants2 = requireConstants$3(); + let CrcCalculator = requireCrc(); + let Parser4 = parser.exports = function(options2, dependencies) { + this._options = options2; + options2.checkCRC = options2.checkCRC !== false; + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + this._palette = []; + this._colorType = 0; + this._chunks = {}; + this._chunks[constants2.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants2.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants2.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants2.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants2.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants2.TYPE_gAMA] = this._handleGAMA.bind(this); + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function() { + }; + }; + Parser4.prototype.start = function() { + this.read(constants2.PNG_SIGNATURE.length, this._parseSignature.bind(this)); + }; + Parser4.prototype._parseSignature = function(data2) { + let signature2 = constants2.PNG_SIGNATURE; + for (let i = 0; i < signature2.length; i++) { + if (data2[i] !== signature2[i]) { + this.error(new Error("Invalid file signature")); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); + }; + Parser4.prototype._parseChunkBegin = function(data2) { + let length = data2.readUInt32BE(0); + let type2 = data2.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data2[i]); + } + let ancillary = Boolean(data2[4] & 32); + if (!this._hasIHDR && type2 !== constants2.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); + if (this._chunks[type2]) { + return this._chunks[type2](length); + } + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } + this.read(length + 4, this._skipChunk.bind(this)); + }; + Parser4.prototype._skipChunk = function() { + this.read(8, this._parseChunkBegin.bind(this)); + }; + Parser4.prototype._handleChunkEnd = function() { + this.read(4, this._parseChunkEnd.bind(this)); + }; + Parser4.prototype._parseChunkEnd = function(data2) { + let fileCrc = data2.readInt32BE(0); + let calcCrc = this._crc.crc32(); + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; + } + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } + }; + Parser4.prototype._handleIHDR = function(length) { + this.read(length, this._parseIHDR.bind(this)); + }; + Parser4.prototype._parseIHDR = function(data2) { + this._crc.write(data2); + let width = data2.readUInt32BE(0); + let height = data2.readUInt32BE(4); + let depth = data2[8]; + let colorType = data2[9]; + let compr = data2[10]; + let filter = data2[11]; + let interlace2 = data2[12]; + if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) { + this.error(new Error("Unsupported bit depth " + depth)); + return; + } + if (!(colorType in constants2.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error("Unsupported color type")); + return; + } + if (compr !== 0) { + this.error(new Error("Unsupported compression method")); + return; + } + if (filter !== 0) { + this.error(new Error("Unsupported filter method")); + return; + } + if (interlace2 !== 0 && interlace2 !== 1) { + this.error(new Error("Unsupported interlace method")); + return; + } + this._colorType = colorType; + let bpp = constants2.COLORTYPE_TO_BPP_MAP[this._colorType]; + this._hasIHDR = true; + this.metadata({ + width, + height, + depth, + interlace: Boolean(interlace2), + palette: Boolean(colorType & constants2.COLORTYPE_PALETTE), + color: Boolean(colorType & constants2.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants2.COLORTYPE_ALPHA), + bpp, + colorType + }); + this._handleChunkEnd(); + }; + Parser4.prototype._handlePLTE = function(length) { + this.read(length, this._parsePLTE.bind(this)); + }; + Parser4.prototype._parsePLTE = function(data2) { + this._crc.write(data2); + let entries = Math.floor(data2.length / 3); + for (let i = 0; i < entries; i++) { + this._palette.push([data2[i * 3], data2[i * 3 + 1], data2[i * 3 + 2], 255]); + } + this.palette(this._palette); + this._handleChunkEnd(); + }; + Parser4.prototype._handleTRNS = function(length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); + }; + Parser4.prototype._parseTRNS = function(data2) { + this._crc.write(data2); + if (this._colorType === constants2.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error("Transparency chunk must be after palette")); + return; + } + if (data2.length > this._palette.length) { + this.error(new Error("More transparent colors than palette size")); + return; + } + for (let i = 0; i < data2.length; i++) { + this._palette[i][3] = data2[i]; + } + this.palette(this._palette); + } + if (this._colorType === constants2.COLORTYPE_GRAYSCALE) { + this.transColor([data2.readUInt16BE(0)]); + } + if (this._colorType === constants2.COLORTYPE_COLOR) { + this.transColor([ + data2.readUInt16BE(0), + data2.readUInt16BE(2), + data2.readUInt16BE(4) + ]); + } + this._handleChunkEnd(); + }; + Parser4.prototype._handleGAMA = function(length) { + this.read(length, this._parseGAMA.bind(this)); + }; + Parser4.prototype._parseGAMA = function(data2) { + this._crc.write(data2); + this.gamma(data2.readUInt32BE(0) / constants2.GAMMA_DIVISION); + this._handleChunkEnd(); + }; + Parser4.prototype._handleIDAT = function(length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); + }; + Parser4.prototype._parseIDAT = function(length, data2) { + this._crc.write(data2); + if (this._colorType === constants2.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) { + throw new Error("Expected palette not found"); + } + this.inflateData(data2); + let leftOverLength = length - data2.length; + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); + } + }; + Parser4.prototype._handleIEND = function(length) { + this.read(length, this._parseIEND.bind(this)); + }; + Parser4.prototype._parseIEND = function(data2) { + this._crc.write(data2); + this._hasIEND = true; + this._handleChunkEnd(); + if (this.finished) { + this.finished(); + } + }; + return parser.exports; +} +var bitmapper = {}; +var hasRequiredBitmapper; +function requireBitmapper() { + if (hasRequiredBitmapper) return bitmapper; + hasRequiredBitmapper = 1; + let interlaceUtils = requireInterlace(); + let pixelBppMapper = [ + // 0 - dummy entry + function() { + }, + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function(pxData, data2, pxPos, rawPos) { + if (rawPos === data2.length) { + throw new Error("Ran out of data"); + } + let pixel = data2[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = 255; + }, + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function(pxData, data2, pxPos, rawPos) { + if (rawPos + 1 >= data2.length) { + throw new Error("Ran out of data"); + } + let pixel = data2[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data2[rawPos + 1]; + }, + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function(pxData, data2, pxPos, rawPos) { + if (rawPos + 2 >= data2.length) { + throw new Error("Ran out of data"); + } + pxData[pxPos] = data2[rawPos]; + pxData[pxPos + 1] = data2[rawPos + 1]; + pxData[pxPos + 2] = data2[rawPos + 2]; + pxData[pxPos + 3] = 255; + }, + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function(pxData, data2, pxPos, rawPos) { + if (rawPos + 3 >= data2.length) { + throw new Error("Ran out of data"); + } + pxData[pxPos] = data2[rawPos]; + pxData[pxPos + 1] = data2[rawPos + 1]; + pxData[pxPos + 2] = data2[rawPos + 2]; + pxData[pxPos + 3] = data2[rawPos + 3]; + } + ]; + let pixelBppCustomMapper = [ + // 0 - dummy entry + function() { + }, + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function(pxData, pixelData, pxPos, maxBit) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function(pxData, pixelData, pxPos) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function(pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function(pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + } + ]; + function bitRetriever(data2, depth) { + let leftOver = []; + let i = 0; + function split() { + if (i === data2.length) { + throw new Error("Ran out of data"); + } + let byte = data2[i]; + i++; + let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error("unrecognised depth"); + case 16: + byte2 = data2[i]; + i++; + leftOver.push((byte << 8) + byte2); + break; + case 4: + byte2 = byte & 15; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = byte >> 2 & 3; + byte2 = byte >> 4 & 3; + byte1 = byte >> 6 & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = byte >> 1 & 1; + byte6 = byte >> 2 & 1; + byte5 = byte >> 3 & 1; + byte4 = byte >> 4 & 1; + byte3 = byte >> 5 & 1; + byte2 = byte >> 6 & 1; + byte1 = byte >> 7 & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + return { + get: function(count) { + while (leftOver.length < count) { + split(); + } + let returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function() { + leftOver.length = 0; + }, + end: function() { + if (i !== data2.length) { + throw new Error("extra data found"); + } + } + }; + } + function mapImage8Bit(image, pxData, getPxPos, bpp, data2, rawPos) { + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data2, pxPos, rawPos); + rawPos += bpp; + } + } + return rawPos; + } + function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } + } + bitmapper.dataToBitMap = function(data2, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace2 = bitmapInfo.interlace; + let bits; + if (depth !== 8) { + bits = bitRetriever(data2, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + if (interlace2) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function() { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width, height }]; + } + for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit( + images[imageIndex], + pxData, + getPxPos, + bpp, + data2, + rawPos + ); + } else { + mapImageCustomBit( + images[imageIndex], + pxData, + getPxPos, + bpp, + bits, + maxBit + ); + } + } + if (depth === 8) { + if (rawPos !== data2.length) { + throw new Error("extra data found"); + } + } else { + bits.end(); + } + return pxData; + }; + return bitmapper; +} +var formatNormaliser; +var hasRequiredFormatNormaliser; +function requireFormatNormaliser() { + if (hasRequiredFormatNormaliser) return formatNormaliser; + hasRequiredFormatNormaliser = 1; + function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } + } + function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let makeTrans = false; + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) { + makeTrans = true; + } + if (makeTrans) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } + } + function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + indata[pxPos + i] * maxOutSample / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } + } + formatNormaliser = function(indata, imageData, skipRescale = false) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + let outdata = indata; + if (colorType === 3) { + dePalette(indata, outdata, width, height, palette); + } else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + if (depth !== 8 && !skipRescale) { + if (depth === 16) { + outdata = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; + }; + return formatNormaliser; +} +var hasRequiredParserAsync; +function requireParserAsync() { + if (hasRequiredParserAsync) return parserAsync.exports; + hasRequiredParserAsync = 1; + let util2 = requireUtil$5(); + let zlib = requireLib(); + let ChunkStream = requireChunkstream(); + let FilterAsync = requireFilterParseAsync(); + let Parser4 = requireParser(); + let bitmapper2 = requireBitmapper(); + let formatNormaliser2 = requireFormatNormaliser(); + let ParserAsync = parserAsync.exports = function(options2) { + ChunkStream.call(this); + this._parser = new Parser4(options2, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, "gamma"), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this) + }); + this._options = options2; + this.writable = true; + this._parser.start(); + }; + util2.inherits(ParserAsync, ChunkStream); + ParserAsync.prototype._handleError = function(err) { + this.emit("error", err); + this.writable = false; + this.destroy(); + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + if (this._filter) { + this._filter.destroy(); + this._filter.on("error", function() { + }); + } + this.errord = true; + }; + ParserAsync.prototype._inflateData = function(data2) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + this._inflate.on("error", this.emit.bind(this, "error")); + this._filter.on("complete", this._complete.bind(this)); + this._inflate.pipe(this._filter); + } else { + let rowSize = (this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3) + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + this._inflate = zlib.createInflate({ chunkSize }); + let leftToInflate = imageSize; + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function(err) { + if (!leftToInflate) { + return; + } + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function(chunk) { + if (!leftToInflate) { + return; + } + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + leftToInflate -= chunk.length; + filterWrite(chunk); + }); + this._inflate.on("end", this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data2); + }; + ParserAsync.prototype._handleMetaData = function(metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + this._filter = new FilterAsync(this._bitmapInfo); + }; + ParserAsync.prototype._handleTransColor = function(transColor) { + this._bitmapInfo.transColor = transColor; + }; + ParserAsync.prototype._handlePalette = function(palette) { + this._bitmapInfo.palette = palette; + }; + ParserAsync.prototype._simpleTransparency = function() { + this._metaData.alpha = true; + }; + ParserAsync.prototype._headersFinished = function() { + this.emit("metadata", this._metaData); + }; + ParserAsync.prototype._finished = function() { + if (this.errord) { + return; + } + if (!this._inflate) { + this.emit("error", "No Inflate block"); + } else { + this._inflate.end(); + } + }; + ParserAsync.prototype._complete = function(filteredData) { + if (this.errord) { + return; + } + let normalisedBitmapData; + try { + let bitmapData = bitmapper2.dataToBitMap(filteredData, this._bitmapInfo); + normalisedBitmapData = formatNormaliser2( + bitmapData, + this._bitmapInfo, + this._options.skipRescale + ); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + this.emit("parsed", normalisedBitmapData); + }; + return parserAsync.exports; +} +var packerAsync = { exports: {} }; +var packer = { exports: {} }; +var bitpacker; +var hasRequiredBitpacker; +function requireBitpacker() { + if (hasRequiredBitpacker) return bitpacker; + hasRequiredBitpacker = 1; + let constants2 = requireConstants$3(); + bitpacker = function(dataIn, width, height, options2) { + let outHasAlpha = [constants2.COLORTYPE_COLOR_ALPHA, constants2.COLORTYPE_ALPHA].indexOf( + options2.colorType + ) !== -1; + if (options2.colorType === options2.inputColorType) { + let bigEndian = function() { + let buffer2 = new ArrayBuffer(2); + new DataView(buffer2).setInt16( + 0, + 256, + true + /* littleEndian */ + ); + return new Int16Array(buffer2)[0] !== 256; + }(); + if (options2.bitDepth === 8 || options2.bitDepth === 16 && bigEndian) { + return dataIn; + } + } + let data2 = options2.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + let maxValue = 255; + let inBpp = constants2.COLORTYPE_TO_BPP_MAP[options2.inputColorType]; + if (inBpp === 4 && !options2.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants2.COLORTYPE_TO_BPP_MAP[options2.colorType]; + if (options2.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + let inIndex = 0; + let outIndex = 0; + let bgColor = options2.bgColor || {}; + if (bgColor.red === void 0) { + bgColor.red = maxValue; + } + if (bgColor.green === void 0) { + bgColor.green = maxValue; + } + if (bgColor.blue === void 0) { + bgColor.blue = maxValue; + } + function getRGBA() { + let red; + let green; + let blue; + let alpha = maxValue; + switch (options2.inputColorType) { + case constants2.COLORTYPE_COLOR_ALPHA: + alpha = data2[inIndex + 3]; + red = data2[inIndex]; + green = data2[inIndex + 1]; + blue = data2[inIndex + 2]; + break; + case constants2.COLORTYPE_COLOR: + red = data2[inIndex]; + green = data2[inIndex + 1]; + blue = data2[inIndex + 2]; + break; + case constants2.COLORTYPE_ALPHA: + alpha = data2[inIndex + 1]; + red = data2[inIndex]; + green = red; + blue = red; + break; + case constants2.COLORTYPE_GRAYSCALE: + red = data2[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error( + "input color type:" + options2.inputColorType + " is not supported at present" + ); + } + if (options2.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), + maxValue + ); + green = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), + maxValue + ); + blue = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), + maxValue + ); + } + } + return { red, green, blue, alpha }; + } + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let rgba = getRGBA(); + switch (options2.colorType) { + case constants2.COLORTYPE_COLOR_ALPHA: + case constants2.COLORTYPE_COLOR: + if (options2.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants2.COLORTYPE_ALPHA: + case constants2.COLORTYPE_GRAYSCALE: { + let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options2.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + } + default: + throw new Error("unrecognised color Type " + options2.colorType); + } + inIndex += inBpp; + outIndex += outBpp; + } + } + return outData; + }; + return bitpacker; +} +var filterPack; +var hasRequiredFilterPack; +function requireFilterPack() { + if (hasRequiredFilterPack) return filterPack; + hasRequiredFilterPack = 1; + let paethPredictor2 = requirePaethPredictor(); + function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } + } + function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; + } + function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + rawData[rawPos + x] = val; + } + } + function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + sum += Math.abs(val); + } + return sum; + } + function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + rawData[rawPos + x] = val; + } + } + function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; + sum += Math.abs(val); + } + return sum; + } + function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - (left + up >> 1); + rawData[rawPos + x] = val; + } + } + function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - (left + up >> 1); + sum += Math.abs(val); + } + return sum; + } + function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor2(left, up, upleft); + rawData[rawPos + x] = val; + } + } + function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor2(left, up, upleft); + sum += Math.abs(val); + } + return sum; + } + let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth + }; + let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth + }; + filterPack = function(pxData, width, height, options2, bpp) { + let filterTypes; + if (!("filterType" in options2) || options2.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } else if (typeof options2.filterType === "number") { + filterTypes = [options2.filterType]; + } else { + throw new Error("unrecognised filter types"); + } + if (options2.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); + let sel = filterTypes[0]; + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + let min2 = Infinity; + for (let i = 0; i < filterTypes.length; i++) { + let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min2) { + sel = filterTypes[i]; + min2 = sum; + } + } + } + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; + }; + return filterPack; +} +var hasRequiredPacker; +function requirePacker() { + if (hasRequiredPacker) return packer.exports; + hasRequiredPacker = 1; + let constants2 = requireConstants$3(); + let CrcStream = requireCrc(); + let bitPacker = requireBitpacker(); + let filter = requireFilterPack(); + let zlib = requireLib(); + let Packer = packer.exports = function(options2) { + this._options = options2; + options2.deflateChunkSize = options2.deflateChunkSize || 32 * 1024; + options2.deflateLevel = options2.deflateLevel != null ? options2.deflateLevel : 9; + options2.deflateStrategy = options2.deflateStrategy != null ? options2.deflateStrategy : 3; + options2.inputHasAlpha = options2.inputHasAlpha != null ? options2.inputHasAlpha : true; + options2.deflateFactory = options2.deflateFactory || zlib.createDeflate; + options2.bitDepth = options2.bitDepth || 8; + options2.colorType = typeof options2.colorType === "number" ? options2.colorType : constants2.COLORTYPE_COLOR_ALPHA; + options2.inputColorType = typeof options2.inputColorType === "number" ? options2.inputColorType : constants2.COLORTYPE_COLOR_ALPHA; + if ([ + constants2.COLORTYPE_GRAYSCALE, + constants2.COLORTYPE_COLOR, + constants2.COLORTYPE_COLOR_ALPHA, + constants2.COLORTYPE_ALPHA + ].indexOf(options2.colorType) === -1) { + throw new Error( + "option color type:" + options2.colorType + " is not supported at present" + ); + } + if ([ + constants2.COLORTYPE_GRAYSCALE, + constants2.COLORTYPE_COLOR, + constants2.COLORTYPE_COLOR_ALPHA, + constants2.COLORTYPE_ALPHA + ].indexOf(options2.inputColorType) === -1) { + throw new Error( + "option input color type:" + options2.inputColorType + " is not supported at present" + ); + } + if (options2.bitDepth !== 8 && options2.bitDepth !== 16) { + throw new Error( + "option bit depth:" + options2.bitDepth + " is not supported at present" + ); + } + }; + Packer.prototype.getDeflateOptions = function() { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy + }; + }; + Packer.prototype.createDeflate = function() { + return this._options.deflateFactory(this.getDeflateOptions()); + }; + Packer.prototype.filterData = function(data2, width, height) { + let packedData = bitPacker(data2, width, height, this._options); + let bpp = constants2.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; + }; + Packer.prototype._packChunk = function(type2, data2) { + let len = data2 ? data2.length : 0; + let buf = Buffer.alloc(len + 12); + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type2, 4); + if (data2) { + data2.copy(buf, 8); + } + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; + }; + Packer.prototype.packGAMA = function(gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants2.GAMMA_DIVISION), 0); + return this._packChunk(constants2.TYPE_gAMA, buf); + }; + Packer.prototype.packIHDR = function(width, height) { + let buf = Buffer.alloc(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; + buf[9] = this._options.colorType; + buf[10] = 0; + buf[11] = 0; + buf[12] = 0; + return this._packChunk(constants2.TYPE_IHDR, buf); + }; + Packer.prototype.packIDAT = function(data2) { + return this._packChunk(constants2.TYPE_IDAT, data2); + }; + Packer.prototype.packIEND = function() { + return this._packChunk(constants2.TYPE_IEND, null); + }; + return packer.exports; +} +var hasRequiredPackerAsync; +function requirePackerAsync() { + if (hasRequiredPackerAsync) return packerAsync.exports; + hasRequiredPackerAsync = 1; + let util2 = requireUtil$5(); + let Stream2 = requireBrowser$h(); + let constants2 = requireConstants$3(); + let Packer = requirePacker(); + let PackerAsync = packerAsync.exports = function(opt) { + Stream2.call(this); + let options2 = opt || {}; + this._packer = new Packer(options2); + this._deflate = this._packer.createDeflate(); + this.readable = true; + }; + util2.inherits(PackerAsync, Stream2); + PackerAsync.prototype.pack = function(data2, width, height, gamma) { + this.emit("data", Buffer.from(constants2.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); + } + let filteredData = this._packer.filterData(data2, width, height); + this._deflate.on("error", this.emit.bind(this, "error")); + this._deflate.on( + "data", + (function(compressedData) { + this.emit("data", this._packer.packIDAT(compressedData)); + }).bind(this) + ); + this._deflate.on( + "end", + (function() { + this.emit("data", this._packer.packIEND()); + this.emit("end"); + }).bind(this) + ); + this._deflate.end(filteredData); + }; + return packerAsync.exports; +} +var pngSync = {}; +var syncInflate = { exports: {} }; +var hasRequiredSyncInflate; +function requireSyncInflate() { + if (hasRequiredSyncInflate) return syncInflate.exports; + hasRequiredSyncInflate = 1; + (function(module, exports) { + let assert2 = requireAssert().ok; + let zlib = requireLib(); + let util2 = requireUtil$5(); + let kMaxLength = requireBuffer$2().kMaxLength; + function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + zlib.Inflate.call(this, opts); + this._offset = this._offset === void 0 ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } + } + function createInflate(opts) { + return new Inflate(opts); + } + function _close(engine, callback) { + if (!engine._handle) { + return; + } + engine._handle.close(); + engine._handle = null; + } + Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + let self2 = this; + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; + let buffers = []; + let nread = 0; + let error2; + this.on("error", function(err) { + error2 = err; + }); + function handleChunk(availInAfter, availOutAfter) { + if (self2._hadError) { + return; + } + let have = availOutBefore - availOutAfter; + assert2(have >= 0, "have should not go down"); + if (have > 0) { + let out = self2._buffer.slice(self2._offset, self2._offset + have); + self2._offset += have; + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + if (leftToInflate === 0) { + return false; + } + } + if (availOutAfter === 0 || self2._offset >= self2._chunkSize) { + availOutBefore = self2._chunkSize; + self2._offset = 0; + self2._buffer = Buffer.allocUnsafe(self2._chunkSize); + } + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + return true; + } + return false; + } + assert2(this._handle, "zlib binding closed"); + let res; + do { + res = this._handle.writeSync( + flushFlag, + chunk, + // in + inOff, + // in_off + availInBefore, + // in_len + this._buffer, + // out + this._offset, + //out_off + availOutBefore + ); + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + if (this._hadError) { + throw error2; + } + if (nread >= kMaxLength) { + _close(this); + throw new RangeError( + "Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes" + ); + } + let buf = Buffer.concat(buffers, nread); + _close(this); + return buf; + }; + util2.inherits(Inflate, zlib.Inflate); + function zlibBufferSync(engine, buffer2) { + if (typeof buffer2 === "string") { + buffer2 = Buffer.from(buffer2); + } + if (!(buffer2 instanceof Buffer)) { + throw new TypeError("Not a string or buffer"); + } + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + return engine._processChunk(buffer2, flushFlag); + } + function inflateSync(buffer2, opts) { + return zlibBufferSync(new Inflate(opts), buffer2); + } + module.exports = exports = inflateSync; + exports.Inflate = Inflate; + exports.createInflate = createInflate; + exports.inflateSync = inflateSync; + })(syncInflate, syncInflate.exports); + return syncInflate.exports; +} +var syncReader = { exports: {} }; +var hasRequiredSyncReader; +function requireSyncReader() { + if (hasRequiredSyncReader) return syncReader.exports; + hasRequiredSyncReader = 1; + let SyncReader = syncReader.exports = function(buffer2) { + this._buffer = buffer2; + this._reads = []; + }; + SyncReader.prototype.read = function(length, callback) { + this._reads.push({ + length: Math.abs(length), + // if length < 0 then at most this length + allowLess: length < 0, + func: callback + }); + }; + SyncReader.prototype.process = function() { + while (this._reads.length > 0 && this._buffer.length) { + let read2 = this._reads[0]; + if (this._buffer.length && (this._buffer.length >= read2.length || read2.allowLess)) { + this._reads.shift(); + let buf = this._buffer; + this._buffer = buf.slice(read2.length); + read2.func.call(this, buf.slice(0, read2.length)); + } else { + break; + } + } + if (this._reads.length > 0) { + throw new Error("There are some read requests waitng on finished stream"); + } + if (this._buffer.length > 0) { + throw new Error("unrecognised content at end of stream"); + } + }; + return syncReader.exports; +} +var filterParseSync = {}; +var hasRequiredFilterParseSync; +function requireFilterParseSync() { + if (hasRequiredFilterParseSync) return filterParseSync; + hasRequiredFilterParseSync = 1; + let SyncReader = requireSyncReader(); + let Filter = requireFilterParse(); + filterParseSync.process = function(inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function(bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function() { + } + }); + filter.start(); + reader.process(); + return Buffer.concat(outBuffers); + }; + return filterParseSync; +} +var parserSync; +var hasRequiredParserSync; +function requireParserSync() { + if (hasRequiredParserSync) return parserSync; + hasRequiredParserSync = 1; + let hasSyncZlib = true; + let zlib = requireLib(); + let inflateSync = requireSyncInflate(); + if (!zlib.deflateSync) { + hasSyncZlib = false; + } + let SyncReader = requireSyncReader(); + let FilterSync = requireFilterParseSync(); + let Parser4 = requireParser(); + let bitmapper2 = requireBitmapper(); + let formatNormaliser2 = requireFormatNormaliser(); + parserSync = function(buffer2, options2) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + let err; + function handleError(_err_) { + err = _err_; + } + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + function handlePalette(palette) { + metaData.palette = palette; + } + function handleSimpleTransparency() { + metaData.alpha = true; + } + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + let inflateDataList = []; + function handleInflateData(inflatedData2) { + inflateDataList.push(inflatedData2); + } + let reader = new SyncReader(buffer2); + let parser2 = new Parser4(options2, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency + }); + parser2.start(); + reader.process(); + if (err) { + throw err; + } + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = (metaData.width * metaData.bpp * metaData.depth + 7 >> 3) + 1; + let imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { + chunkSize: imageSize, + maxLength: imageSize + }); + } + inflateData = null; + if (!inflatedData || !inflatedData.length) { + throw new Error("bad png - invalid inflate data response"); + } + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + let bitmapData = bitmapper2.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + let normalisedBitmapData = formatNormaliser2( + bitmapData, + metaData, + options2.skipRescale + ); + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + return metaData; + }; + return parserSync; +} +var packerSync; +var hasRequiredPackerSync; +function requirePackerSync() { + if (hasRequiredPackerSync) return packerSync; + hasRequiredPackerSync = 1; + let hasSyncZlib = true; + let zlib = requireLib(); + if (!zlib.deflateSync) { + hasSyncZlib = false; + } + let constants2 = requireConstants$3(); + let Packer = requirePacker(); + packerSync = function(metaData, opt) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + let options2 = opt || {}; + let packer2 = new Packer(options2); + let chunks = []; + chunks.push(Buffer.from(constants2.PNG_SIGNATURE)); + chunks.push(packer2.packIHDR(metaData.width, metaData.height)); + if (metaData.gamma) { + chunks.push(packer2.packGAMA(metaData.gamma)); + } + let filteredData = packer2.filterData( + metaData.data, + metaData.width, + metaData.height + ); + let compressedData = zlib.deflateSync( + filteredData, + packer2.getDeflateOptions() + ); + filteredData = null; + if (!compressedData || !compressedData.length) { + throw new Error("bad png - invalid compressed data response"); + } + chunks.push(packer2.packIDAT(compressedData)); + chunks.push(packer2.packIEND()); + return Buffer.concat(chunks); + }; + return packerSync; +} +var hasRequiredPngSync; +function requirePngSync() { + if (hasRequiredPngSync) return pngSync; + hasRequiredPngSync = 1; + let parse4 = requireParserSync(); + let pack = requirePackerSync(); + pngSync.read = function(buffer2, options2) { + return parse4(buffer2, options2 || {}); + }; + pngSync.write = function(png2, options2) { + return pack(png2, options2); + }; + return pngSync; +} +var hasRequiredPng; +function requirePng() { + if (hasRequiredPng) return png; + hasRequiredPng = 1; + let util2 = requireUtil$5(); + let Stream2 = requireBrowser$h(); + let Parser4 = requireParserAsync(); + let Packer = requirePackerAsync(); + let PNGSync = requirePngSync(); + let PNG2 = png.PNG = function(options2) { + Stream2.call(this); + options2 = options2 || {}; + this.width = options2.width | 0; + this.height = options2.height | 0; + this.data = this.width > 0 && this.height > 0 ? Buffer.alloc(4 * this.width * this.height) : null; + if (options2.fill && this.data) { + this.data.fill(0); + } + this.gamma = 0; + this.readable = this.writable = true; + this._parser = new Parser4(options2); + this._parser.on("error", this.emit.bind(this, "error")); + this._parser.on("close", this._handleClose.bind(this)); + this._parser.on("metadata", this._metadata.bind(this)); + this._parser.on("gamma", this._gamma.bind(this)); + this._parser.on( + "parsed", + (function(data2) { + this.data = data2; + this.emit("parsed", data2); + }).bind(this) + ); + this._packer = new Packer(options2); + this._packer.on("data", this.emit.bind(this, "data")); + this._packer.on("end", this.emit.bind(this, "end")); + this._parser.on("close", this._handleClose.bind(this)); + this._packer.on("error", this.emit.bind(this, "error")); + }; + util2.inherits(PNG2, Stream2); + PNG2.sync = PNGSync; + PNG2.prototype.pack = function() { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } + process.nextTick( + (function() { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }).bind(this) + ); + return this; + }; + PNG2.prototype.parse = function(data2, callback) { + if (callback) { + let onParsed, onError; + onParsed = (function(parsedData) { + this.removeListener("error", onError); + this.data = parsedData; + callback(null, this); + }).bind(this); + onError = (function(err) { + this.removeListener("parsed", onParsed); + callback(err, null); + }).bind(this); + this.once("parsed", onParsed); + this.once("error", onError); + } + this.end(data2); + return this; + }; + PNG2.prototype.write = function(data2) { + this._parser.write(data2); + return true; + }; + PNG2.prototype.end = function(data2) { + this._parser.end(data2); + }; + PNG2.prototype._metadata = function(metadata) { + this.width = metadata.width; + this.height = metadata.height; + this.emit("metadata", metadata); + }; + PNG2.prototype._gamma = function(gamma) { + this.gamma = gamma; + }; + PNG2.prototype._handleClose = function() { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } + }; + PNG2.bitblt = function(src2, dst, srcX, srcY, width, height, deltaX, deltaY) { + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + if (srcX > src2.width || srcY > src2.height || srcX + width > src2.width || srcY + height > src2.height) { + throw new Error("bitblt reading outside image"); + } + if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) { + throw new Error("bitblt writing outside image"); + } + for (let y = 0; y < height; y++) { + src2.data.copy( + dst.data, + (deltaY + y) * dst.width + deltaX << 2, + (srcY + y) * src2.width + srcX << 2, + (srcY + y) * src2.width + srcX + width << 2 + ); + } + }; + PNG2.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { + PNG2.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; + }; + PNG2.adjustGamma = function(src2) { + if (src2.gamma) { + for (let y = 0; y < src2.height; y++) { + for (let x = 0; x < src2.width; x++) { + let idx = src2.width * y + x << 2; + for (let i = 0; i < 3; i++) { + let sample = src2.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src2.gamma); + src2.data[idx + i] = Math.round(sample * 255); + } + } + } + src2.gamma = 0; + } + }; + PNG2.prototype.adjustGamma = function() { + PNG2.adjustGamma(this); + }; + return png; +} +var pngExports = requirePng(); +var commander = { exports: {} }; +var argument = {}; +var error = {}; +var hasRequiredError; +function requireError() { + if (hasRequiredError) return error; + hasRequiredError = 1; + class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {number} exitCode suggested exit code which could be used with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + this.nestedError = void 0; + } + } + class InvalidArgumentError extends CommanderError { + /** + * Constructs the InvalidArgumentError class + * @param {string} [message] explanation of why argument is invalid + * @constructor + */ + constructor(message) { + super(1, "commander.invalidArgument", message); + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + } + } + error.CommanderError = CommanderError; + error.InvalidArgumentError = InvalidArgumentError; + return error; +} +var hasRequiredArgument; +function requireArgument() { + if (hasRequiredArgument) return argument; + hasRequiredArgument = 1; + const { InvalidArgumentError } = requireError(); + class Argument { + /** + * Initialize a new command argument with the given name and description. + * The default is that the argument is required, and you can explicitly + * indicate this with <> around the name. Put [] around the name for an optional argument. + * + * @param {string} name + * @param {string} [description] + */ + constructor(name, description) { + this.description = description || ""; + this.variadic = false; + this.parseArg = void 0; + this.defaultValue = void 0; + this.defaultValueDescription = void 0; + this.argChoices = void 0; + switch (name[0]) { + case "<": + this.required = true; + this._name = name.slice(1, -1); + break; + case "[": + this.required = false; + this._name = name.slice(1, -1); + break; + default: + this.required = true; + this._name = name; + break; + } + if (this._name.length > 3 && this._name.slice(-3) === "...") { + this.variadic = true; + this._name = this._name.slice(0, -3); + } + } + /** + * Return argument name. + * + * @return {string} + */ + name() { + return this._name; + } + /** + * @api private + */ + _concatValue(value, previous) { + if (previous === this.defaultValue || !Array.isArray(previous)) { + return [value]; + } + return previous.concat(value); + } + /** + * Set the default value, and optionally supply the description to be displayed in the help. + * + * @param {any} value + * @param {string} [description] + * @return {Argument} + */ + default(value, description) { + this.defaultValue = value; + this.defaultValueDescription = description; + return this; + } + /** + * Set the custom handler for processing CLI command arguments into argument values. + * + * @param {Function} [fn] + * @return {Argument} + */ + argParser(fn) { + this.parseArg = fn; + return this; + } + /** + * Only allow option value to be one of choices. + * + * @param {string[]} values + * @return {Argument} + */ + choices(values) { + this.argChoices = values; + this.parseArg = (arg, previous) => { + if (!values.includes(arg)) { + throw new InvalidArgumentError(`Allowed choices are ${values.join(", ")}.`); + } + if (this.variadic) { + return this._concatValue(arg, previous); + } + return arg; + }; + return this; + } + /** + * Make option-argument required. + */ + argRequired() { + this.required = true; + return this; + } + /** + * Make option-argument optional. + */ + argOptional() { + this.required = false; + return this; + } + } + function humanReadableArgName(arg) { + const nameOutput = arg.name() + (arg.variadic === true ? "..." : ""); + return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]"; + } + argument.Argument = Argument; + argument.humanReadableArgName = humanReadableArgName; + return argument; +} +var command = {}; +var help = {}; +var hasRequiredHelp; +function requireHelp() { + if (hasRequiredHelp) return help; + hasRequiredHelp = 1; + const { humanReadableArgName } = requireArgument(); + class Help { + constructor() { + this.helpWidth = void 0; + this.sortSubcommands = false; + this.sortOptions = false; + } + /** + * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. + * + * @param {Command} cmd + * @returns {Command[]} + */ + visibleCommands(cmd) { + const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden); + if (cmd._hasImplicitHelpCommand()) { + const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/); + const helpCommand = cmd.createCommand(helpName).helpOption(false); + helpCommand.description(cmd._helpCommandDescription); + if (helpArgs) helpCommand.arguments(helpArgs); + visibleCommands.push(helpCommand); + } + if (this.sortSubcommands) { + visibleCommands.sort((a, b) => { + return a.name().localeCompare(b.name()); + }); + } + return visibleCommands; + } + /** + * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. + * + * @param {Command} cmd + * @returns {Option[]} + */ + visibleOptions(cmd) { + const visibleOptions = cmd.options.filter((option2) => !option2.hidden); + const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag); + const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag); + if (showShortHelpFlag || showLongHelpFlag) { + let helpOption; + if (!showShortHelpFlag) { + helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription); + } else if (!showLongHelpFlag) { + helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription); + } else { + helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription); + } + visibleOptions.push(helpOption); + } + if (this.sortOptions) { + const getSortKey = (option2) => { + return option2.short ? option2.short.replace(/^-/, "") : option2.long.replace(/^--/, ""); + }; + visibleOptions.sort((a, b) => { + return getSortKey(a).localeCompare(getSortKey(b)); + }); + } + return visibleOptions; + } + /** + * Get an array of the arguments if any have a description. + * + * @param {Command} cmd + * @returns {Argument[]} + */ + visibleArguments(cmd) { + if (cmd._argsDescription) { + cmd._args.forEach((argument2) => { + argument2.description = argument2.description || cmd._argsDescription[argument2.name()] || ""; + }); + } + if (cmd._args.find((argument2) => argument2.description)) { + return cmd._args; + } + return []; + } + /** + * Get the command term to show in the list of subcommands. + * + * @param {Command} cmd + * @returns {string} + */ + subcommandTerm(cmd) { + const args = cmd._args.map((arg) => humanReadableArgName(arg)).join(" "); + return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option + (args ? " " + args : ""); + } + /** + * Get the option term to show in the list of options. + * + * @param {Option} option + * @returns {string} + */ + optionTerm(option2) { + return option2.flags; + } + /** + * Get the argument term to show in the list of arguments. + * + * @param {Argument} argument + * @returns {string} + */ + argumentTerm(argument2) { + return argument2.name(); + } + /** + * Get the longest command term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ + longestSubcommandTermLength(cmd, helper2) { + return helper2.visibleCommands(cmd).reduce((max2, command2) => { + return Math.max(max2, helper2.subcommandTerm(command2).length); + }, 0); + } + /** + * Get the longest option term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ + longestOptionTermLength(cmd, helper2) { + return helper2.visibleOptions(cmd).reduce((max2, option2) => { + return Math.max(max2, helper2.optionTerm(option2).length); + }, 0); + } + /** + * Get the longest argument term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ + longestArgumentTermLength(cmd, helper2) { + return helper2.visibleArguments(cmd).reduce((max2, argument2) => { + return Math.max(max2, helper2.argumentTerm(argument2).length); + }, 0); + } + /** + * Get the command usage to be displayed at the top of the built-in help. + * + * @param {Command} cmd + * @returns {string} + */ + commandUsage(cmd) { + let cmdName = cmd._name; + if (cmd._aliases[0]) { + cmdName = cmdName + "|" + cmd._aliases[0]; + } + let parentCmdNames = ""; + for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + " " + parentCmdNames; + } + return parentCmdNames + cmdName + " " + cmd.usage(); + } + /** + * Get the description for the command. + * + * @param {Command} cmd + * @returns {string} + */ + commandDescription(cmd) { + return cmd.description(); + } + /** + * Get the command description to show in the list of subcommands. + * + * @param {Command} cmd + * @returns {string} + */ + subcommandDescription(cmd) { + return cmd.description(); + } + /** + * Get the option description to show in the list of options. + * + * @param {Option} option + * @return {string} + */ + optionDescription(option2) { + const extraInfo = []; + if (option2.argChoices && !option2.negate) { + extraInfo.push( + // use stringify to match the display of the default value + `choices: ${option2.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}` + ); + } + if (option2.defaultValue !== void 0 && !option2.negate) { + extraInfo.push(`default: ${option2.defaultValueDescription || JSON.stringify(option2.defaultValue)}`); + } + if (option2.envVar !== void 0) { + extraInfo.push(`env: ${option2.envVar}`); + } + if (extraInfo.length > 0) { + return `${option2.description} (${extraInfo.join(", ")})`; + } + return option2.description; + } + /** + * Get the argument description to show in the list of arguments. + * + * @param {Argument} argument + * @return {string} + */ + argumentDescription(argument2) { + const extraInfo = []; + if (argument2.argChoices) { + extraInfo.push( + // use stringify to match the display of the default value + `choices: ${argument2.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}` + ); + } + if (argument2.defaultValue !== void 0) { + extraInfo.push(`default: ${argument2.defaultValueDescription || JSON.stringify(argument2.defaultValue)}`); + } + if (extraInfo.length > 0) { + const extraDescripton = `(${extraInfo.join(", ")})`; + if (argument2.description) { + return `${argument2.description} ${extraDescripton}`; + } + return extraDescripton; + } + return argument2.description; + } + /** + * Generate the built-in help text. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {string} + */ + formatHelp(cmd, helper2) { + const termWidth = helper2.padWidth(cmd, helper2); + const helpWidth = helper2.helpWidth || 80; + const itemIndentWidth = 2; + const itemSeparatorWidth = 2; + function formatItem(term, description) { + if (description) { + const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; + return helper2.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth); + } + return term; + } + function formatList(textArray) { + return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth)); + } + let output = [`Usage: ${helper2.commandUsage(cmd)}`, ""]; + const commandDescription = helper2.commandDescription(cmd); + if (commandDescription.length > 0) { + output = output.concat([commandDescription, ""]); + } + const argumentList = helper2.visibleArguments(cmd).map((argument2) => { + return formatItem(helper2.argumentTerm(argument2), helper2.argumentDescription(argument2)); + }); + if (argumentList.length > 0) { + output = output.concat(["Arguments:", formatList(argumentList), ""]); + } + const optionList = helper2.visibleOptions(cmd).map((option2) => { + return formatItem(helper2.optionTerm(option2), helper2.optionDescription(option2)); + }); + if (optionList.length > 0) { + output = output.concat(["Options:", formatList(optionList), ""]); + } + const commandList = helper2.visibleCommands(cmd).map((cmd2) => { + return formatItem(helper2.subcommandTerm(cmd2), helper2.subcommandDescription(cmd2)); + }); + if (commandList.length > 0) { + output = output.concat(["Commands:", formatList(commandList), ""]); + } + return output.join("\n"); + } + /** + * Calculate the pad width from the maximum term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ + padWidth(cmd, helper2) { + return Math.max( + helper2.longestOptionTermLength(cmd, helper2), + helper2.longestSubcommandTermLength(cmd, helper2), + helper2.longestArgumentTermLength(cmd, helper2) + ); + } + /** + * Wrap the given string to width characters per line, with lines after the first indented. + * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @param {number} [minColumnWidth=40] + * @return {string} + * + */ + wrap(str, width, indent, minColumnWidth = 40) { + if (str.match(/[\n]\s+/)) return str; + const columnWidth = width - indent; + if (columnWidth < minColumnWidth) return str; + const leadingStr = str.substr(0, indent); + const columnText = str.substr(indent); + const indentString = " ".repeat(indent); + const regex = new RegExp(".{1," + (columnWidth - 1) + "}([\\s​]|$)|[^\\s​]+?([\\s​]|$)", "g"); + const lines = columnText.match(regex) || []; + return leadingStr + lines.map((line, i) => { + if (line.slice(-1) === "\n") { + line = line.slice(0, line.length - 1); + } + return (i > 0 ? indentString : "") + line.trimRight(); + }).join("\n"); + } + } + help.Help = Help; + return help; +} +var option = {}; +var hasRequiredOption; +function requireOption() { + if (hasRequiredOption) return option; + hasRequiredOption = 1; + const { InvalidArgumentError } = requireError(); + class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} [description] + */ + constructor(flags, description) { + this.flags = flags; + this.description = description || ""; + this.required = flags.includes("<"); + this.optional = flags.includes("["); + this.variadic = /\w\.\.\.[>\]]$/.test(flags); + this.mandatory = false; + const optionFlags = splitOptionFlags(flags); + this.short = optionFlags.shortFlag; + this.long = optionFlags.longFlag; + this.negate = false; + if (this.long) { + this.negate = this.long.startsWith("--no-"); + } + this.defaultValue = void 0; + this.defaultValueDescription = void 0; + this.envVar = void 0; + this.parseArg = void 0; + this.hidden = false; + this.argChoices = void 0; + } + /** + * Set the default value, and optionally supply the description to be displayed in the help. + * + * @param {any} value + * @param {string} [description] + * @return {Option} + */ + default(value, description) { + this.defaultValue = value; + this.defaultValueDescription = description; + return this; + } + /** + * Set environment variable to check for option value. + * Priority order of option values is default < env < cli + * + * @param {string} name + * @return {Option} + */ + env(name) { + this.envVar = name; + return this; + } + /** + * Set the custom handler for processing CLI option arguments into option values. + * + * @param {Function} [fn] + * @return {Option} + */ + argParser(fn) { + this.parseArg = fn; + return this; + } + /** + * Whether the option is mandatory and must have a value after parsing. + * + * @param {boolean} [mandatory=true] + * @return {Option} + */ + makeOptionMandatory(mandatory = true) { + this.mandatory = !!mandatory; + return this; + } + /** + * Hide option in help. + * + * @param {boolean} [hide=true] + * @return {Option} + */ + hideHelp(hide = true) { + this.hidden = !!hide; + return this; + } + /** + * @api private + */ + _concatValue(value, previous) { + if (previous === this.defaultValue || !Array.isArray(previous)) { + return [value]; + } + return previous.concat(value); + } + /** + * Only allow option value to be one of choices. + * + * @param {string[]} values + * @return {Option} + */ + choices(values) { + this.argChoices = values; + this.parseArg = (arg, previous) => { + if (!values.includes(arg)) { + throw new InvalidArgumentError(`Allowed choices are ${values.join(", ")}.`); + } + if (this.variadic) { + return this._concatValue(arg, previous); + } + return arg; + }; + return this; + } + /** + * Return option name. + * + * @return {string} + */ + name() { + if (this.long) { + return this.long.replace(/^--/, ""); + } + return this.short.replace(/^-/, ""); + } + /** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} + * @api private + */ + attributeName() { + return camelcase(this.name().replace(/^no-/, "")); + } + /** + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @api private + */ + is(arg) { + return this.short === arg || this.long === arg; + } + } + function camelcase(str) { + return str.split("-").reduce((str2, word) => { + return str2 + word[0].toUpperCase() + word.slice(1); + }); + } + function splitOptionFlags(flags) { + let shortFlag; + let longFlag; + const flagParts = flags.split(/[ |,]+/); + if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); + longFlag = flagParts.shift(); + if (!shortFlag && /^-[^-]$/.test(longFlag)) { + shortFlag = longFlag; + longFlag = void 0; + } + return { shortFlag, longFlag }; + } + option.Option = Option; + option.splitOptionFlags = splitOptionFlags; + return option; +} +var suggestSimilar = {}; +var hasRequiredSuggestSimilar; +function requireSuggestSimilar() { + if (hasRequiredSuggestSimilar) return suggestSimilar; + hasRequiredSuggestSimilar = 1; + const maxDistance = 3; + function editDistance(a, b) { + if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length); + const d = []; + for (let i = 0; i <= a.length; i++) { + d[i] = [i]; + } + for (let j = 0; j <= b.length; j++) { + d[0][j] = j; + } + for (let j = 1; j <= b.length; j++) { + for (let i = 1; i <= a.length; i++) { + let cost = 1; + if (a[i - 1] === b[j - 1]) { + cost = 0; + } else { + cost = 1; + } + d[i][j] = Math.min( + d[i - 1][j] + 1, + // deletion + d[i][j - 1] + 1, + // insertion + d[i - 1][j - 1] + cost + // substitution + ); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); + } + } + } + return d[a.length][b.length]; + } + function suggestSimilar$1(word, candidates) { + if (!candidates || candidates.length === 0) return ""; + candidates = Array.from(new Set(candidates)); + const searchingOptions = word.startsWith("--"); + if (searchingOptions) { + word = word.slice(2); + candidates = candidates.map((candidate) => candidate.slice(2)); + } + let similar = []; + let bestDistance = maxDistance; + const minSimilarity = 0.4; + candidates.forEach((candidate) => { + if (candidate.length <= 1) return; + const distance = editDistance(word, candidate); + const length = Math.max(word.length, candidate.length); + const similarity = (length - distance) / length; + if (similarity > minSimilarity) { + if (distance < bestDistance) { + bestDistance = distance; + similar = [candidate]; + } else if (distance === bestDistance) { + similar.push(candidate); + } + } + }); + similar.sort((a, b) => a.localeCompare(b)); + if (searchingOptions) { + similar = similar.map((candidate) => `--${candidate}`); + } + if (similar.length > 1) { + return ` +(Did you mean one of ${similar.join(", ")}?)`; + } + if (similar.length === 1) { + return ` +(Did you mean ${similar[0]}?)`; + } + return ""; + } + suggestSimilar.suggestSimilar = suggestSimilar$1; + return suggestSimilar; +} +var hasRequiredCommand; +function requireCommand() { + if (hasRequiredCommand) return command; + hasRequiredCommand = 1; + const EventEmitter2 = requireEvents().EventEmitter; + const childProcess = require$$1; + const path2 = requirePath(); + const fs2 = require$$2$1; + const { Argument, humanReadableArgName } = requireArgument(); + const { CommanderError } = requireError(); + const { Help } = requireHelp(); + const { Option, splitOptionFlags } = requireOption(); + const { suggestSimilar: suggestSimilar2 } = requireSuggestSimilar(); + class Command extends EventEmitter2 { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + */ + constructor(name) { + super(); + this.commands = []; + this.options = []; + this.parent = null; + this._allowUnknownOption = false; + this._allowExcessArguments = true; + this._args = []; + this.args = []; + this.rawArgs = []; + this.processedArgs = []; + this._scriptPath = null; + this._name = name || ""; + this._optionValues = {}; + this._optionValueSources = {}; + this._storeOptionsAsProperties = false; + this._actionHandler = null; + this._executableHandler = false; + this._executableFile = null; + this._defaultCommandName = null; + this._exitCallback = null; + this._aliases = []; + this._combineFlagAndOptionalValue = true; + this._description = ""; + this._argsDescription = void 0; + this._enablePositionalOptions = false; + this._passThroughOptions = false; + this._lifeCycleHooks = {}; + this._showHelpAfterError = false; + this._showSuggestionAfterError = false; + this._outputConfiguration = { + writeOut: (str) => process.stdout.write(str), + writeErr: (str) => process.stderr.write(str), + getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0, + getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0, + outputError: (str, write2) => write2(str) + }; + this._hidden = false; + this._hasHelpOption = true; + this._helpFlags = "-h, --help"; + this._helpDescription = "display help for command"; + this._helpShortFlag = "-h"; + this._helpLongFlag = "--help"; + this._addImplicitHelpCommand = void 0; + this._helpCommandName = "help"; + this._helpCommandnameAndArgs = "help [command]"; + this._helpCommandDescription = "display help for command"; + this._helpConfiguration = {}; + } + /** + * Copy settings that are useful to have in common across root command and subcommands. + * + * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) + * + * @param {Command} sourceCommand + * @return {Command} returns `this` for executable command + */ + copyInheritedSettings(sourceCommand) { + this._outputConfiguration = sourceCommand._outputConfiguration; + this._hasHelpOption = sourceCommand._hasHelpOption; + this._helpFlags = sourceCommand._helpFlags; + this._helpDescription = sourceCommand._helpDescription; + this._helpShortFlag = sourceCommand._helpShortFlag; + this._helpLongFlag = sourceCommand._helpLongFlag; + this._helpCommandName = sourceCommand._helpCommandName; + this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs; + this._helpCommandDescription = sourceCommand._helpCommandDescription; + this._helpConfiguration = sourceCommand._helpConfiguration; + this._exitCallback = sourceCommand._exitCallback; + this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; + this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue; + this._allowExcessArguments = sourceCommand._allowExcessArguments; + this._enablePositionalOptions = sourceCommand._enablePositionalOptions; + this._showHelpAfterError = sourceCommand._showHelpAfterError; + this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; + return this; + } + /** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * @example + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or `this` for executable command + */ + command(nameAndArgs, actionOptsOrExecDesc, execOpts) { + let desc = actionOptsOrExecDesc; + let opts = execOpts; + if (typeof desc === "object" && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); + const cmd = this.createCommand(name); + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; + } + if (opts.isDefault) this._defaultCommandName = cmd._name; + cmd._hidden = !!(opts.noHelp || opts.hidden); + cmd._executableFile = opts.executableFile || null; + if (args) cmd.arguments(args); + this.commands.push(cmd); + cmd.parent = this; + cmd.copyInheritedSettings(this); + if (desc) return this; + return cmd; + } + /** + * Factory routine to create a new unattached command. + * + * See .command() for creating an attached subcommand, which uses this routine to + * create the command. You can override createCommand to customise subcommands. + * + * @param {string} [name] + * @return {Command} new command + */ + createCommand(name) { + return new Command(name); + } + /** + * You can customise the help with a subclass of Help by overriding createHelp, + * or by overriding Help properties using configureHelp(). + * + * @return {Help} + */ + createHelp() { + return Object.assign(new Help(), this.configureHelp()); + } + /** + * You can customise the help by overriding Help properties using configureHelp(), + * or with a subclass of Help by overriding createHelp(). + * + * @param {Object} [configuration] - configuration options + * @return {Command|Object} `this` command for chaining, or stored configuration + */ + configureHelp(configuration) { + if (configuration === void 0) return this._helpConfiguration; + this._helpConfiguration = configuration; + return this; + } + /** + * The default output goes to stdout and stderr. You can customise this for special + * applications. You can also customise the display of errors by overriding outputError. + * + * The configuration properties are all functions: + * + * // functions to change where being written, stdout and stderr + * writeOut(str) + * writeErr(str) + * // matching functions to specify width for wrapping help + * getOutHelpWidth() + * getErrHelpWidth() + * // functions based on what is being written out + * outputError(str, write) // used for displaying errors, and not used for displaying help + * + * @param {Object} [configuration] - configuration options + * @return {Command|Object} `this` command for chaining, or stored configuration + */ + configureOutput(configuration) { + if (configuration === void 0) return this._outputConfiguration; + Object.assign(this._outputConfiguration, configuration); + return this; + } + /** + * Display the help or a custom message after an error occurs. + * + * @param {boolean|string} [displayHelp] + * @return {Command} `this` command for chaining + */ + showHelpAfterError(displayHelp = true) { + if (typeof displayHelp !== "string") displayHelp = !!displayHelp; + this._showHelpAfterError = displayHelp; + return this; + } + /** + * Display suggestion of similar commands for unknown commands, or options for unknown options. + * + * @param {boolean} [displaySuggestion] + * @return {Command} `this` command for chaining + */ + showSuggestionAfterError(displaySuggestion = true) { + this._showSuggestionAfterError = !!displaySuggestion; + return this; + } + /** + * Add a prepared subcommand. + * + * See .command() for creating an attached subcommand which inherits settings from its parent. + * + * @param {Command} cmd - new subcommand + * @param {Object} [opts] - configuration options + * @return {Command} `this` command for chaining + */ + addCommand(cmd, opts) { + if (!cmd._name) throw new Error("Command passed to .addCommand() must have a name"); + function checkExplicitNames(commandArray) { + commandArray.forEach((cmd2) => { + if (cmd2._executableHandler && !cmd2._executableFile) { + throw new Error(`Must specify executableFile for deeply nested executable: ${cmd2.name()}`); + } + checkExplicitNames(cmd2.commands); + }); + } + checkExplicitNames(cmd.commands); + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; + this.commands.push(cmd); + cmd.parent = this; + return this; + } + /** + * Factory routine to create a new unattached argument. + * + * See .argument() for creating an attached argument, which uses this routine to + * create the argument. You can override createArgument to return a custom argument. + * + * @param {string} name + * @param {string} [description] + * @return {Argument} new argument + */ + createArgument(name, description) { + return new Argument(name, description); + } + /** + * Define argument syntax for command. + * + * The default is that the argument is required, and you can explicitly + * indicate this with <> around the name. Put [] around the name for an optional argument. + * + * @example + * program.argument(''); + * program.argument('[output-file]'); + * + * @param {string} name + * @param {string} [description] + * @param {Function|*} [fn] - custom argument processing function + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + */ + argument(name, description, fn, defaultValue) { + const argument2 = this.createArgument(name, description); + if (typeof fn === "function") { + argument2.default(defaultValue).argParser(fn); + } else { + argument2.default(fn); + } + this.addArgument(argument2); + return this; + } + /** + * Define argument syntax for command, adding multiple at once (without descriptions). + * + * See also .argument(). + * + * @example + * program.arguments(' [env]'); + * + * @param {string} names + * @return {Command} `this` command for chaining + */ + arguments(names) { + names.split(/ +/).forEach((detail) => { + this.argument(detail); + }); + return this; + } + /** + * Define argument syntax for command, adding a prepared argument. + * + * @param {Argument} argument + * @return {Command} `this` command for chaining + */ + addArgument(argument2) { + const previousArgument = this._args.slice(-1)[0]; + if (previousArgument && previousArgument.variadic) { + throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`); + } + if (argument2.required && argument2.defaultValue !== void 0 && argument2.parseArg === void 0) { + throw new Error(`a default value for a required argument is never used: '${argument2.name()}'`); + } + this._args.push(argument2); + return this; + } + /** + * Override default decision whether to add implicit help command. + * + * addHelpCommand() // force on + * addHelpCommand(false); // force off + * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details + * + * @return {Command} `this` command for chaining + */ + addHelpCommand(enableOrNameAndArgs, description) { + if (enableOrNameAndArgs === false) { + this._addImplicitHelpCommand = false; + } else { + this._addImplicitHelpCommand = true; + if (typeof enableOrNameAndArgs === "string") { + this._helpCommandName = enableOrNameAndArgs.split(" ")[0]; + this._helpCommandnameAndArgs = enableOrNameAndArgs; + } + this._helpCommandDescription = description || this._helpCommandDescription; + } + return this; + } + /** + * @return {boolean} + * @api private + */ + _hasImplicitHelpCommand() { + if (this._addImplicitHelpCommand === void 0) { + return this.commands.length && !this._actionHandler && !this._findCommand("help"); + } + return this._addImplicitHelpCommand; + } + /** + * Add hook for life cycle event. + * + * @param {string} event + * @param {Function} listener + * @return {Command} `this` command for chaining + */ + hook(event, listener) { + const allowedValues = ["preAction", "postAction"]; + if (!allowedValues.includes(event)) { + throw new Error(`Unexpected value for event passed to hook : '${event}'. +Expecting one of '${allowedValues.join("', '")}'`); + } + if (this._lifeCycleHooks[event]) { + this._lifeCycleHooks[event].push(listener); + } else { + this._lifeCycleHooks[event] = [listener]; + } + return this; + } + /** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} `this` command for chaining + */ + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = (err) => { + if (err.code !== "commander.executeSubCommandAsync") { + throw err; + } + }; + } + return this; + } + /** + * Call process.exit, and _exitCallback if defined. + * + * @param {number} exitCode exit code for using with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @return never + * @api private + */ + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + } + process.exit(exitCode); + } + /** + * Register callback `fn` for the command. + * + * @example + * program + * .command('serve') + * .description('start service') + * .action(function() { + * // do work here + * }); + * + * @param {Function} fn + * @return {Command} `this` command for chaining + */ + action(fn) { + const listener = (args) => { + const expectedArgsCount = this._args.length; + const actionArgs = args.slice(0, expectedArgsCount); + if (this._storeOptionsAsProperties) { + actionArgs[expectedArgsCount] = this; + } else { + actionArgs[expectedArgsCount] = this.opts(); + } + actionArgs.push(this); + return fn.apply(this, actionArgs); + }; + this._actionHandler = listener; + return this; + } + /** + * Factory routine to create a new unattached option. + * + * See .option() for creating an attached option, which uses this routine to + * create the option. You can override createOption to return a custom option. + * + * @param {string} flags + * @param {string} [description] + * @return {Option} new option + */ + createOption(flags, description) { + return new Option(flags, description); + } + /** + * Add an option. + * + * @param {Option} option + * @return {Command} `this` command for chaining + */ + addOption(option2) { + const oname = option2.name(); + const name = option2.attributeName(); + let defaultValue = option2.defaultValue; + if (option2.negate || option2.optional || option2.required || typeof defaultValue === "boolean") { + if (option2.negate) { + const positiveLongFlag = option2.long.replace(/^--no-/, "--"); + defaultValue = this._findOption(positiveLongFlag) ? this.getOptionValue(name) : true; + } + if (defaultValue !== void 0) { + this.setOptionValueWithSource(name, defaultValue, "default"); + } + } + this.options.push(option2); + const handleOptionValue = (val, invalidValueMessage, valueSource) => { + const oldValue = this.getOptionValue(name); + if (val !== null && option2.parseArg) { + try { + val = option2.parseArg(val, oldValue === void 0 ? defaultValue : oldValue); + } catch (err) { + if (err.code === "commander.invalidArgument") { + const message = `${invalidValueMessage} ${err.message}`; + this._displayError(err.exitCode, err.code, message); + } + throw err; + } + } else if (val !== null && option2.variadic) { + val = option2._concatValue(val, oldValue); + } + if (typeof oldValue === "boolean" || typeof oldValue === "undefined") { + if (val == null) { + this.setOptionValueWithSource(name, option2.negate ? false : defaultValue || true, valueSource); + } else { + this.setOptionValueWithSource(name, val, valueSource); + } + } else if (val !== null) { + this.setOptionValueWithSource(name, option2.negate ? false : val, valueSource); + } + }; + this.on("option:" + oname, (val) => { + const invalidValueMessage = `error: option '${option2.flags}' argument '${val}' is invalid.`; + handleOptionValue(val, invalidValueMessage, "cli"); + }); + if (option2.envVar) { + this.on("optionEnv:" + oname, (val) => { + const invalidValueMessage = `error: option '${option2.flags}' value '${val}' from env '${option2.envVar}' is invalid.`; + handleOptionValue(val, invalidValueMessage, "env"); + }); + } + return this; + } + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @api private + */ + _optionEx(config, flags, description, fn, defaultValue) { + const option2 = this.createOption(flags, description); + option2.makeOptionMandatory(!!config.mandatory); + if (typeof fn === "function") { + option2.default(defaultValue).argParser(fn); + } else if (fn instanceof RegExp) { + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; + }; + option2.default(defaultValue).argParser(fn); + } else { + option2.default(fn); + } + return this.addOption(option2); + } + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string contains the short and/or long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @example + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} [description] + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + */ + option(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); + } + /** + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. + * + * @param {string} flags + * @param {string} [description] + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + */ + requiredOption(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); + } + /** + * Alter parsing of short flags with optional values. + * + * @example + * // for `.option('-f,--flag [value]'): + * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour + * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` + * + * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag. + */ + combineFlagAndOptionalValue(combine = true) { + this._combineFlagAndOptionalValue = !!combine; + return this; + } + /** + * Allow unknown options on the command line. + * + * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown + * for unknown options. + */ + allowUnknownOption(allowUnknown = true) { + this._allowUnknownOption = !!allowUnknown; + return this; + } + /** + * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. + * + * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown + * for excess arguments. + */ + allowExcessArguments(allowExcess = true) { + this._allowExcessArguments = !!allowExcess; + return this; + } + /** + * Enable positional options. Positional means global options are specified before subcommands which lets + * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. + * The default behaviour is non-positional and global options may appear anywhere on the command line. + * + * @param {Boolean} [positional=true] + */ + enablePositionalOptions(positional = true) { + this._enablePositionalOptions = !!positional; + return this; + } + /** + * Pass through options that come after command-arguments rather than treat them as command-options, + * so actual command-options come before command-arguments. Turning this on for a subcommand requires + * positional options to have been enabled on the program (parent commands). + * The default behaviour is non-positional and options may appear before or after command-arguments. + * + * @param {Boolean} [passThrough=true] + * for unknown options. + */ + passThroughOptions(passThrough = true) { + this._passThroughOptions = !!passThrough; + if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) { + throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)"); + } + return this; + } + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} [storeAsProperties=true] + * @return {Command} `this` command for chaining + */ + storeOptionsAsProperties(storeAsProperties = true) { + this._storeOptionsAsProperties = !!storeAsProperties; + if (this.options.length) { + throw new Error("call .storeOptionsAsProperties() before adding options"); + } + return this; + } + /** + * Retrieve option value. + * + * @param {string} key + * @return {Object} value + */ + getOptionValue(key2) { + if (this._storeOptionsAsProperties) { + return this[key2]; + } + return this._optionValues[key2]; + } + /** + * Store option value. + * + * @param {string} key + * @param {Object} value + * @return {Command} `this` command for chaining + */ + setOptionValue(key2, value) { + if (this._storeOptionsAsProperties) { + this[key2] = value; + } else { + this._optionValues[key2] = value; + } + return this; + } + /** + * Store option value and where the value came from. + * + * @param {string} key + * @param {Object} value + * @param {string} source - expected values are default/config/env/cli + * @return {Command} `this` command for chaining + */ + setOptionValueWithSource(key2, value, source2) { + this.setOptionValue(key2, value); + this._optionValueSources[key2] = source2; + return this; + } + /** + * Get source of option value. + * Expected values are default | config | env | cli + * + * @param {string} key + * @return {string} + */ + getOptionValueSource(key2) { + return this._optionValueSources[key2]; + } + /** + * Get user arguments implied or explicit arguments. + * Side-effects: set _scriptPath if args included application, and use that to set implicit command name. + * + * @api private + */ + _prepareUserArgs(argv, parseOptions2) { + if (argv !== void 0 && !Array.isArray(argv)) { + throw new Error("first parameter to parse must be array or undefined"); + } + parseOptions2 = parseOptions2 || {}; + if (argv === void 0) { + argv = process.argv; + if (process.versions && process.versions.electron) { + parseOptions2.from = "electron"; + } + } + this.rawArgs = argv.slice(); + let userArgs; + switch (parseOptions2.from) { + case void 0: + case "node": + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + break; + case "electron": + if (process.defaultApp) { + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + } else { + userArgs = argv.slice(1); + } + break; + case "user": + userArgs = argv.slice(0); + break; + default: + throw new Error(`unexpected parse option { from: '${parseOptions2.from}' }`); + } + if (!this._scriptPath && require.main) { + this._scriptPath = require.main.filename; + } + this._name = this._name || this._scriptPath && path2.basename(this._scriptPath, path2.extname(this._scriptPath)); + return userArgs; + } + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * @example + * program.parse(process.argv); + * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] - optional, defaults to process.argv + * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron + * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' + * @return {Command} `this` command for chaining + */ + parse(argv, parseOptions2) { + const userArgs = this._prepareUserArgs(argv, parseOptions2); + this._parseCommand([], userArgs); + return this; + } + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * @example + * await program.parseAsync(process.argv); + * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions + * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] + * @param {Object} [parseOptions] + * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' + * @return {Promise} + */ + async parseAsync(argv, parseOptions2) { + const userArgs = this._prepareUserArgs(argv, parseOptions2); + await this._parseCommand([], userArgs); + return this; + } + /** + * Execute a sub-command executable. + * + * @api private + */ + _executeSubCommand(subcommand, args) { + args = args.slice(); + let launchWithNode = false; + const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"]; + this._checkForMissingMandatoryOptions(); + let scriptPath = this._scriptPath; + if (!scriptPath && require.main) { + scriptPath = require.main.filename; + } + let baseDir; + try { + const resolvedLink = fs2.realpathSync(scriptPath); + baseDir = path2.dirname(resolvedLink); + } catch (e) { + baseDir = "."; + } + let bin = path2.basename(scriptPath, path2.extname(scriptPath)) + "-" + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; + } + const localBin = path2.join(baseDir, bin); + if (fs2.existsSync(localBin)) { + bin = localBin; + } else { + sourceExt.forEach((ext) => { + if (fs2.existsSync(`${localBin}${ext}`)) { + bin = `${localBin}${ext}`; + } + }); + } + launchWithNode = sourceExt.includes(path2.extname(bin)); + let proc; + if (process.platform !== "win32") { + if (launchWithNode) { + args.unshift(bin); + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" }); + } else { + proc = childProcess.spawn(bin, args, { stdio: "inherit" }); + } + } else { + args.unshift(bin); + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" }); + } + const signals2 = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"]; + signals2.forEach((signal) => { + process.on(signal, () => { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on("close", process.exit.bind(process)); + } else { + proc.on("close", () => { + exitCallback(new CommanderError(process.exitCode || 0, "commander.executeSubCommandAsync", "(close)")); + }); + } + proc.on("error", (err) => { + if (err.code === "ENOENT") { + const executableMissing = `'${bin}' does not exist + - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead + - if the default executable name is not suitable, use the executableFile option to supply a custom name`; + throw new Error(executableMissing); + } else if (err.code === "EACCES") { + throw new Error(`'${bin}' not executable`); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)"); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); + this.runningCommand = proc; + } + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this.help({ error: true }); + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + return subCommand._parseCommand(operands, unknown); + } + } + /** + * Check this.args against expected this._args. + * + * @api private + */ + _checkNumberOfArguments() { + this._args.forEach((arg, i) => { + if (arg.required && this.args[i] == null) { + this.missingArgument(arg.name()); + } + }); + if (this._args.length > 0 && this._args[this._args.length - 1].variadic) { + return; + } + if (this.args.length > this._args.length) { + this._excessArguments(this.args); + } + } + /** + * Process this.args using this._args and save as this.processedArgs! + * + * @api private + */ + _processArguments() { + const myParseArg = (argument2, value, previous) => { + let parsedValue = value; + if (value !== null && argument2.parseArg) { + try { + parsedValue = argument2.parseArg(value, previous); + } catch (err) { + if (err.code === "commander.invalidArgument") { + const message = `error: command-argument value '${value}' is invalid for argument '${argument2.name()}'. ${err.message}`; + this._displayError(err.exitCode, err.code, message); + } + throw err; + } + } + return parsedValue; + }; + this._checkNumberOfArguments(); + const processedArgs = []; + this._args.forEach((declaredArg, index2) => { + let value = declaredArg.defaultValue; + if (declaredArg.variadic) { + if (index2 < this.args.length) { + value = this.args.slice(index2); + if (declaredArg.parseArg) { + value = value.reduce((processed, v) => { + return myParseArg(declaredArg, v, processed); + }, declaredArg.defaultValue); + } + } else if (value === void 0) { + value = []; + } + } else if (index2 < this.args.length) { + value = this.args[index2]; + if (declaredArg.parseArg) { + value = myParseArg(declaredArg, value, declaredArg.defaultValue); + } + } + processedArgs[index2] = value; + }); + this.processedArgs = processedArgs; + } + /** + * Once we have a promise we chain, but call synchronously until then. + * + * @param {Promise|undefined} promise + * @param {Function} fn + * @return {Promise|undefined} + * @api private + */ + _chainOrCall(promise, fn) { + if (promise && promise.then && typeof promise.then === "function") { + return promise.then(() => fn()); + } + return fn(); + } + /** + * + * @param {Promise|undefined} promise + * @param {string} event + * @return {Promise|undefined} + * @api private + */ + _chainOrCallHooks(promise, event) { + let result = promise; + const hooks = []; + getCommandAndParents(this).reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => { + hookedCommand._lifeCycleHooks[event].forEach((callback) => { + hooks.push({ hookedCommand, callback }); + }); + }); + if (event === "postAction") { + hooks.reverse(); + } + hooks.forEach((hookDetail) => { + result = this._chainOrCall(result, () => { + return hookDetail.callback(hookDetail.hookedCommand, this); + }); + }); + return result; + } + /** + * Process arguments in context of this command. + * Returns action result, in case it is a promise. + * + * @api private + */ + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + this._parseOptionsEnv(); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); + if (operands && this._findCommand(operands[0])) { + return this._dispatchSubcommand(operands[0], operands.slice(1), unknown); + } + if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) { + if (operands.length === 1) { + this.help(); + } + return this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); + } + if (this._defaultCommandName) { + outputHelpIfRequested(this, unknown); + return this._dispatchSubcommand(this._defaultCommandName, operands, unknown); + } + if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { + this.help({ error: true }); + } + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + const checkForUnknownOptions = () => { + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } + }; + const commandEvent = `command:${this.name()}`; + if (this._actionHandler) { + checkForUnknownOptions(); + this._processArguments(); + let actionResult; + actionResult = this._chainOrCallHooks(actionResult, "preAction"); + actionResult = this._chainOrCall(actionResult, () => this._actionHandler(this.processedArgs)); + if (this.parent) this.parent.emit(commandEvent, operands, unknown); + actionResult = this._chainOrCallHooks(actionResult, "postAction"); + return actionResult; + } + if (this.parent && this.parent.listenerCount(commandEvent)) { + checkForUnknownOptions(); + this._processArguments(); + this.parent.emit(commandEvent, operands, unknown); + } else if (operands.length) { + if (this._findCommand("*")) { + return this._dispatchSubcommand("*", operands, unknown); + } + if (this.listenerCount("command:*")) { + this.emit("command:*", operands, unknown); + } else if (this.commands.length) { + this.unknownCommand(); + } else { + checkForUnknownOptions(); + this._processArguments(); + } + } else if (this.commands.length) { + checkForUnknownOptions(); + this.help({ error: true }); + } else { + checkForUnknownOptions(); + this._processArguments(); + } + } + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return void 0; + return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name)); + } + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ + _findOption(arg) { + return this.options.find((option2) => option2.is(arg)); + } + /** + * Display an error message if a mandatory option does not have a value. + * Lazy calling after checking for help flags from leaf subcommand. + * + * @api private + */ + _checkForMissingMandatoryOptions() { + for (let cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } + } + /** + * Parse options from `argv` removing known options, + * and return argv split into operands and unknown arguments. + * + * Examples: + * + * argv => operands, unknown + * --known kkk op => [op], [] + * op --known kkk => [op], [] + * sub --unknown uuu op => [sub], [--unknown uuu op] + * sub -- --unknown uuu op => [sub --unknown uuu op], [] + * + * @param {String[]} argv + * @return {{operands: String[], unknown: String[]}} + */ + parseOptions(argv) { + const operands = []; + const unknown = []; + let dest = operands; + const args = argv.slice(); + function maybeOption(arg) { + return arg.length > 1 && arg[0] === "-"; + } + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); + if (arg === "--") { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; + if (maybeOption(arg)) { + const option2 = this._findOption(arg); + if (option2) { + if (option2.required) { + const value = args.shift(); + if (value === void 0) this.optionMissingArgument(option2); + this.emit(`option:${option2.name()}`, value); + } else if (option2.optional) { + let value = null; + if (args.length > 0 && !maybeOption(args[0])) { + value = args.shift(); + } + this.emit(`option:${option2.name()}`, value); + } else { + this.emit(`option:${option2.name()}`); + } + activeVariadicOption = option2.variadic ? option2 : null; + continue; + } + } + if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") { + const option2 = this._findOption(`-${arg[1]}`); + if (option2) { + if (option2.required || option2.optional && this._combineFlagAndOptionalValue) { + this.emit(`option:${option2.name()}`, arg.slice(2)); + } else { + this.emit(`option:${option2.name()}`); + args.unshift(`-${arg.slice(2)}`); + } + continue; + } + } + if (/^--[^=]+=/.test(arg)) { + const index2 = arg.indexOf("="); + const option2 = this._findOption(arg.slice(0, index2)); + if (option2 && (option2.required || option2.optional)) { + this.emit(`option:${option2.name()}`, arg.slice(index2 + 1)); + continue; + } + } + if (maybeOption(arg)) { + dest = unknown; + } + if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) { + if (this._findCommand(arg)) { + operands.push(arg); + if (args.length > 0) unknown.push(...args); + break; + } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) { + operands.push(arg); + if (args.length > 0) operands.push(...args); + break; + } else if (this._defaultCommandName) { + unknown.push(arg); + if (args.length > 0) unknown.push(...args); + break; + } + } + if (this._passThroughOptions) { + dest.push(arg); + if (args.length > 0) dest.push(...args); + break; + } + dest.push(arg); + } + return { operands, unknown }; + } + /** + * Return an object containing options as key-value pairs + * + * @return {Object} + */ + opts() { + if (this._storeOptionsAsProperties) { + const result = {}; + const len = this.options.length; + for (let i = 0; i < len; i++) { + const key2 = this.options[i].attributeName(); + result[key2] = key2 === this._versionOptionName ? this._version : this[key2]; + } + return result; + } + return this._optionValues; + } + /** + * Internal bottleneck for handling of parsing errors. + * + * @api private + */ + _displayError(exitCode, code, message) { + this._outputConfiguration.outputError(`${message} +`, this._outputConfiguration.writeErr); + if (typeof this._showHelpAfterError === "string") { + this._outputConfiguration.writeErr(`${this._showHelpAfterError} +`); + } else if (this._showHelpAfterError) { + this._outputConfiguration.writeErr("\n"); + this.outputHelp({ error: true }); + } + this._exit(exitCode, code, message); + } + /** + * Apply any option related environment variables, if option does + * not have a value from cli or client code. + * + * @api private + */ + _parseOptionsEnv() { + this.options.forEach((option2) => { + if (option2.envVar && option2.envVar in define_process_env_default) { + const optionKey = option2.attributeName(); + if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) { + if (option2.required || option2.optional) { + this.emit(`optionEnv:${option2.name()}`, define_process_env_default[option2.envVar]); + } else { + this.emit(`optionEnv:${option2.name()}`); + } + } + } + }); + } + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + this._displayError(1, "commander.missingArgument", message); + } + /** + * `Option` is missing an argument. + * + * @param {Option} option + * @api private + */ + optionMissingArgument(option2) { + const message = `error: option '${option2.flags}' argument missing`; + this._displayError(1, "commander.optionMissingArgument", message); + } + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ + missingMandatoryOptionValue(option2) { + const message = `error: required option '${option2.flags}' not specified`; + this._displayError(1, "commander.missingMandatoryOptionValue", message); + } + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ + unknownOption(flag) { + if (this._allowUnknownOption) return; + let suggestion = ""; + if (flag.startsWith("--") && this._showSuggestionAfterError) { + let candidateFlags = []; + let command2 = this; + do { + const moreFlags = command2.createHelp().visibleOptions(command2).filter((option2) => option2.long).map((option2) => option2.long); + candidateFlags = candidateFlags.concat(moreFlags); + command2 = command2.parent; + } while (command2 && !command2._enablePositionalOptions); + suggestion = suggestSimilar2(flag, candidateFlags); + } + const message = `error: unknown option '${flag}'${suggestion}`; + this._displayError(1, "commander.unknownOption", message); + } + /** + * Excess arguments, more than expected. + * + * @param {string[]} receivedArgs + * @api private + */ + _excessArguments(receivedArgs) { + if (this._allowExcessArguments) return; + const expected = this._args.length; + const s = expected === 1 ? "" : "s"; + const forSubcommand = this.parent ? ` for '${this.name()}'` : ""; + const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; + this._displayError(1, "commander.excessArguments", message); + } + /** + * Unknown command. + * + * @api private + */ + unknownCommand() { + const unknownName = this.args[0]; + let suggestion = ""; + if (this._showSuggestionAfterError) { + const candidateNames = []; + this.createHelp().visibleCommands(this).forEach((command2) => { + candidateNames.push(command2.name()); + if (command2.alias()) candidateNames.push(command2.alias()); + }); + suggestion = suggestSimilar2(unknownName, candidateNames); + } + const message = `error: unknown command '${unknownName}'${suggestion}`; + this._displayError(1, "commander.unknownCommand", message); + } + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {string} str + * @param {string} [flags] + * @param {string} [description] + * @return {this | string} `this` command for chaining, or version string if no arguments + */ + version(str, flags, description) { + if (str === void 0) return this._version; + this._version = str; + flags = flags || "-V, --version"; + description = description || "output the version number"; + const versionOption = this.createOption(flags, description); + this._versionOptionName = versionOption.attributeName(); + this.options.push(versionOption); + this.on("option:" + versionOption.name(), () => { + this._outputConfiguration.writeOut(`${str} +`); + this._exit(0, "commander.version", str); + }); + return this; + } + /** + * Set the description to `str`. + * + * @param {string} [str] + * @param {Object} [argsDescription] + * @return {string|Command} + */ + description(str, argsDescription) { + if (str === void 0 && argsDescription === void 0) return this._description; + this._description = str; + if (argsDescription) { + this._argsDescription = argsDescription; + } + return this; + } + /** + * Set an alias for the command. + * + * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. + * + * @param {string} [alias] + * @return {string|Command} + */ + alias(alias) { + if (alias === void 0) return this._aliases[0]; + let command2 = this; + if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { + command2 = this.commands[this.commands.length - 1]; + } + if (alias === command2._name) throw new Error("Command alias can't be the same as its name"); + command2._aliases.push(alias); + return this; + } + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + */ + aliases(aliases2) { + if (aliases2 === void 0) return this._aliases; + aliases2.forEach((alias) => this.alias(alias)); + return this; + } + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + */ + usage(str) { + if (str === void 0) { + if (this._usage) return this._usage; + const args = this._args.map((arg) => { + return humanReadableArgName(arg); + }); + return [].concat( + this.options.length || this._hasHelpOption ? "[options]" : [], + this.commands.length ? "[command]" : [], + this._args.length ? args : [] + ).join(" "); + } + this._usage = str; + return this; + } + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {string|Command} + */ + name(str) { + if (str === void 0) return this._name; + this._name = str; + return this; + } + /** + * Return program help documentation. + * + * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout + * @return {string} + */ + helpInformation(contextOptions) { + const helper2 = this.createHelp(); + if (helper2.helpWidth === void 0) { + helper2.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth(); + } + return helper2.formatHelp(this, helper2); + } + /** + * @api private + */ + _getHelpContext(contextOptions) { + contextOptions = contextOptions || {}; + const context = { error: !!contextOptions.error }; + let write2; + if (context.error) { + write2 = (arg) => this._outputConfiguration.writeErr(arg); + } else { + write2 = (arg) => this._outputConfiguration.writeOut(arg); + } + context.write = contextOptions.write || write2; + context.command = this; + return context; + } + /** + * Output help information for this command. + * + * Outputs built-in help, and custom text added using `.addHelpText()`. + * + * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout + */ + outputHelp(contextOptions) { + let deprecatedCallback; + if (typeof contextOptions === "function") { + deprecatedCallback = contextOptions; + contextOptions = void 0; + } + const context = this._getHelpContext(contextOptions); + getCommandAndParents(this).reverse().forEach((command2) => command2.emit("beforeAllHelp", context)); + this.emit("beforeHelp", context); + let helpInformation = this.helpInformation(context); + if (deprecatedCallback) { + helpInformation = deprecatedCallback(helpInformation); + if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) { + throw new Error("outputHelp callback must return a string or a Buffer"); + } + } + context.write(helpInformation); + this.emit(this._helpLongFlag); + this.emit("afterHelp", context); + getCommandAndParents(this).forEach((command2) => command2.emit("afterAllHelp", context)); + } + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. Pass in false to + * disable the built-in help option. + * + * @param {string | boolean} [flags] + * @param {string} [description] + * @return {Command} `this` command for chaining + */ + helpOption(flags, description) { + if (typeof flags === "boolean") { + this._hasHelpOption = flags; + return this; + } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; + const helpFlags = splitOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; + return this; + } + /** + * Output help information and exit. + * + * Outputs built-in help, and custom text added using `.addHelpText()`. + * + * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout + */ + help(contextOptions) { + this.outputHelp(contextOptions); + let exitCode = process.exitCode || 0; + if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) { + exitCode = 1; + } + this._exit(exitCode, "commander.help", "(outputHelp)"); + } + /** + * Add additional text to be displayed with the built-in help. + * + * Position is 'before' or 'after' to affect just this command, + * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. + * + * @param {string} position - before or after built-in help + * @param {string | Function} text - string to add, or a function returning a string + * @return {Command} `this` command for chaining + */ + addHelpText(position, text) { + const allowedValues = ["beforeAll", "before", "after", "afterAll"]; + if (!allowedValues.includes(position)) { + throw new Error(`Unexpected value for position to addHelpText. +Expecting one of '${allowedValues.join("', '")}'`); + } + const helpEvent = `${position}Help`; + this.on(helpEvent, (context) => { + let helpStr; + if (typeof text === "function") { + helpStr = text({ error: context.error, command: context.command }); + } else { + helpStr = text; + } + if (helpStr) { + context.write(`${helpStr} +`); + } + }); + return this; + } + } + function outputHelpIfRequested(cmd, args) { + const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); + if (helpOption) { + cmd.outputHelp(); + cmd._exit(0, "commander.helpDisplayed", "(outputHelp)"); + } + } + function incrementNodeInspectorPort(args) { + return args.map((arg) => { + if (!arg.startsWith("--inspect")) { + return arg; + } + let debugOption; + let debugHost = "127.0.0.1"; + let debugPort = "9229"; + let match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + debugPort = match[3]; + } else { + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; + } + if (debugOption && debugPort !== "0") { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + return arg; + }); + } + function getCommandAndParents(startCommand) { + const result = []; + for (let command2 = startCommand; command2; command2 = command2.parent) { + result.push(command2); + } + return result; + } + command.Command = Command; + return command; +} +var hasRequiredCommander; +function requireCommander() { + if (hasRequiredCommander) return commander.exports; + hasRequiredCommander = 1; + (function(module, exports) { + const { Argument } = requireArgument(); + const { Command } = requireCommand(); + const { CommanderError, InvalidArgumentError } = requireError(); + const { Help } = requireHelp(); + const { Option } = requireOption(); + exports = module.exports = new Command(); + exports.program = exports; + exports.Argument = Argument; + exports.Command = Command; + exports.CommanderError = CommanderError; + exports.Help = Help; + exports.InvalidArgumentError = InvalidArgumentError; + exports.InvalidOptionArgumentError = InvalidArgumentError; + exports.Option = Option; + })(commander, commander.exports); + return commander.exports; +} +var commanderExports = requireCommander(); +var nodeProgress = { exports: {} }; +/*! + * node-progress + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ +var hasRequiredNodeProgress; +function requireNodeProgress() { + if (hasRequiredNodeProgress) return nodeProgress.exports; + hasRequiredNodeProgress = 1; + (function(module, exports) { + module.exports = ProgressBar; + function ProgressBar(fmt, options2) { + this.stream = options2.stream || process.stderr; + if (typeof options2 == "number") { + var total = options2; + options2 = {}; + options2.total = total; + } else { + options2 = options2 || {}; + if ("string" != typeof fmt) throw new Error("format required"); + if ("number" != typeof options2.total) throw new Error("total required"); + } + this.fmt = fmt; + this.curr = options2.curr || 0; + this.total = options2.total; + this.width = options2.width || this.total; + this.clear = options2.clear; + this.chars = { + complete: options2.complete || "=", + incomplete: options2.incomplete || "-", + head: options2.head || (options2.complete || "=") + }; + this.renderThrottle = options2.renderThrottle !== 0 ? options2.renderThrottle || 16 : 0; + this.lastRender = -Infinity; + this.callback = options2.callback || function() { + }; + this.tokens = {}; + this.lastDraw = ""; + } + ProgressBar.prototype.tick = function(len, tokens) { + if (len !== 0) + len = len || 1; + if ("object" == typeof len) tokens = len, len = 1; + if (tokens) this.tokens = tokens; + if (0 == this.curr) this.start = /* @__PURE__ */ new Date(); + this.curr += len; + this.render(); + if (this.curr >= this.total) { + this.render(void 0, true); + this.complete = true; + this.terminate(); + this.callback(this); + return; + } + }; + ProgressBar.prototype.render = function(tokens, force) { + force = force !== void 0 ? force : false; + if (tokens) this.tokens = tokens; + if (!this.stream.isTTY) return; + var now = Date.now(); + var delta = now - this.lastRender; + if (!force && delta < this.renderThrottle) { + return; + } else { + this.lastRender = now; + } + var ratio = this.curr / this.total; + ratio = Math.min(Math.max(ratio, 0), 1); + var percent = Math.floor(ratio * 100); + var incomplete, complete, completeLength; + var elapsed = /* @__PURE__ */ new Date() - this.start; + var eta = percent == 100 ? 0 : elapsed * (this.total / this.curr - 1); + var rate = this.curr / (elapsed / 1e3); + var str = this.fmt.replace(":current", this.curr).replace(":total", this.total).replace(":elapsed", isNaN(elapsed) ? "0.0" : (elapsed / 1e3).toFixed(1)).replace(":eta", isNaN(eta) || !isFinite(eta) ? "0.0" : (eta / 1e3).toFixed(1)).replace(":percent", percent.toFixed(0) + "%").replace(":rate", Math.round(rate)); + var availableSpace = Math.max(0, this.stream.columns - str.replace(":bar", "").length); + if (availableSpace && process.platform === "win32") { + availableSpace = availableSpace - 1; + } + var width = Math.min(this.width, availableSpace); + completeLength = Math.round(width * ratio); + complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete); + incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete); + if (completeLength > 0) + complete = complete.slice(0, -1) + this.chars.head; + str = str.replace(":bar", complete + incomplete); + if (this.tokens) for (var key2 in this.tokens) str = str.replace(":" + key2, this.tokens[key2]); + if (this.lastDraw !== str) { + this.stream.cursorTo(0); + this.stream.write(str); + this.stream.clearLine(1); + this.lastDraw = str; + } + }; + ProgressBar.prototype.update = function(ratio, tokens) { + var goal = Math.floor(ratio * this.total); + var delta = goal - this.curr; + this.tick(delta, tokens); + }; + ProgressBar.prototype.interrupt = function(message) { + this.stream.clearLine(); + this.stream.cursorTo(0); + this.stream.write(message); + this.stream.write("\n"); + this.stream.write(this.lastDraw); + }; + ProgressBar.prototype.terminate = function() { + if (this.clear) { + if (this.stream.clearLine) { + this.stream.clearLine(); + this.stream.cursorTo(0); + } + } else { + this.stream.write("\n"); + } + }; + })(nodeProgress); + return nodeProgress.exports; +} +var progress$2; +var hasRequiredProgress; +function requireProgress() { + if (hasRequiredProgress) return progress$2; + hasRequiredProgress = 1; + progress$2 = requireNodeProgress(); + return progress$2; +} +var progressExports = requireProgress(); +const progressLibrary = /* @__PURE__ */ getDefaultExportFromCjs(progressExports); +var agent = {}; +function noop$1() { +} +const promises = { + lookup: noop$1() +}; +const dns = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: promises, + promises +}, Symbol.toStringTag, { value: "Module" })); +const require$$0$3 = /* @__PURE__ */ getAugmentedNamespace(dns); +var build = {}; +var socksclient = {}; +var smartbuffer = {}; +var utils = {}; +var hasRequiredUtils; +function requireUtils() { + if (hasRequiredUtils) return utils; + hasRequiredUtils = 1; + Object.defineProperty(utils, "__esModule", { value: true }); + const buffer_1 = requireBuffer$2(); + const ERRORS = { + INVALID_ENCODING: "Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.", + INVALID_SMARTBUFFER_SIZE: "Invalid size provided. Size must be a valid integer greater than zero.", + INVALID_SMARTBUFFER_BUFFER: "Invalid Buffer provided in SmartBufferOptions.", + INVALID_SMARTBUFFER_OBJECT: "Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.", + INVALID_OFFSET: "An invalid offset value was provided.", + INVALID_OFFSET_NON_NUMBER: "An invalid offset value was provided. A numeric value is required.", + INVALID_LENGTH: "An invalid length value was provided.", + INVALID_LENGTH_NON_NUMBER: "An invalid length value was provived. A numeric value is required.", + INVALID_TARGET_OFFSET: "Target offset is beyond the bounds of the internal SmartBuffer data.", + INVALID_TARGET_LENGTH: "Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.", + INVALID_READ_BEYOND_BOUNDS: "Attempted to read beyond the bounds of the managed data.", + INVALID_WRITE_BEYOND_BOUNDS: "Attempted to write beyond the bounds of the managed data." + }; + utils.ERRORS = ERRORS; + function checkEncoding(encoding2) { + if (!buffer_1.Buffer.isEncoding(encoding2)) { + throw new Error(ERRORS.INVALID_ENCODING); + } + } + utils.checkEncoding = checkEncoding; + function isFiniteInteger(value) { + return typeof value === "number" && isFinite(value) && isInteger(value); + } + utils.isFiniteInteger = isFiniteInteger; + function checkOffsetOrLengthValue(value, offset2) { + if (typeof value === "number") { + if (!isFiniteInteger(value) || value < 0) { + throw new Error(offset2 ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); + } + } else { + throw new Error(offset2 ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); + } + } + function checkLengthValue(length) { + checkOffsetOrLengthValue(length, false); + } + utils.checkLengthValue = checkLengthValue; + function checkOffsetValue(offset2) { + checkOffsetOrLengthValue(offset2, true); + } + utils.checkOffsetValue = checkOffsetValue; + function checkTargetOffset(offset2, buff) { + if (offset2 < 0 || offset2 > buff.length) { + throw new Error(ERRORS.INVALID_TARGET_OFFSET); + } + } + utils.checkTargetOffset = checkTargetOffset; + function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; + } + function bigIntAndBufferInt64Check(bufferMethod) { + if (typeof BigInt === "undefined") { + throw new Error("Platform does not support JS BigInt type."); + } + if (typeof buffer_1.Buffer.prototype[bufferMethod] === "undefined") { + throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); + } + } + utils.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; + return utils; +} +var hasRequiredSmartbuffer; +function requireSmartbuffer() { + if (hasRequiredSmartbuffer) return smartbuffer; + hasRequiredSmartbuffer = 1; + Object.defineProperty(smartbuffer, "__esModule", { value: true }); + const utils_1 = requireUtils(); + const DEFAULT_SMARTBUFFER_SIZE = 4096; + const DEFAULT_SMARTBUFFER_ENCODING = "utf8"; + class SmartBuffer { + /** + * Creates a new SmartBuffer instance. + * + * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. + */ + constructor(options2) { + this.length = 0; + this._encoding = DEFAULT_SMARTBUFFER_ENCODING; + this._writeOffset = 0; + this._readOffset = 0; + if (SmartBuffer.isSmartBufferOptions(options2)) { + if (options2.encoding) { + utils_1.checkEncoding(options2.encoding); + this._encoding = options2.encoding; + } + if (options2.size) { + if (utils_1.isFiniteInteger(options2.size) && options2.size > 0) { + this._buff = Buffer.allocUnsafe(options2.size); + } else { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); + } + } else if (options2.buff) { + if (Buffer.isBuffer(options2.buff)) { + this._buff = options2.buff; + this.length = options2.buff.length; + } else { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); + } + } else { + this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); + } + } else { + if (typeof options2 !== "undefined") { + throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); + } + this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); + } + } + /** + * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. + * + * @param size { Number } The size of the internal Buffer. + * @param encoding { String } The BufferEncoding to use for strings. + * + * @return { SmartBuffer } + */ + static fromSize(size, encoding2) { + return new this({ + size, + encoding: encoding2 + }); + } + /** + * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. + * + * @param buffer { Buffer } The Buffer to use as the internal Buffer value. + * @param encoding { String } The BufferEncoding to use for strings. + * + * @return { SmartBuffer } + */ + static fromBuffer(buff, encoding2) { + return new this({ + buff, + encoding: encoding2 + }); + } + /** + * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. + * + * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. + */ + static fromOptions(options2) { + return new this(options2); + } + /** + * Type checking function that determines if an object is a SmartBufferOptions object. + */ + static isSmartBufferOptions(options2) { + const castOptions = options2; + return castOptions && (castOptions.encoding !== void 0 || castOptions.size !== void 0 || castOptions.buff !== void 0); + } + // Signed integers + /** + * Reads an Int8 value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt8(offset2) { + return this._readNumberValue(Buffer.prototype.readInt8, 1, offset2); + } + /** + * Reads an Int16BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt16BE(offset2) { + return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset2); + } + /** + * Reads an Int16LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt16LE(offset2) { + return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset2); + } + /** + * Reads an Int32BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt32BE(offset2) { + return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset2); + } + /** + * Reads an Int32LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readInt32LE(offset2) { + return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset2); + } + /** + * Reads a BigInt64BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigInt64BE(offset2) { + utils_1.bigIntAndBufferInt64Check("readBigInt64BE"); + return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset2); + } + /** + * Reads a BigInt64LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigInt64LE(offset2) { + utils_1.bigIntAndBufferInt64Check("readBigInt64LE"); + return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset2); + } + /** + * Writes an Int8 value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt8(value, offset2) { + this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset2); + return this; + } + /** + * Inserts an Int8 value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt8(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset2); + } + /** + * Writes an Int16BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt16BE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset2); + } + /** + * Inserts an Int16BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt16BE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset2); + } + /** + * Writes an Int16LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt16LE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset2); + } + /** + * Inserts an Int16LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt16LE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset2); + } + /** + * Writes an Int32BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt32BE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset2); + } + /** + * Inserts an Int32BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt32BE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset2); + } + /** + * Writes an Int32LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeInt32LE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset2); + } + /** + * Inserts an Int32LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertInt32LE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset2); + } + /** + * Writes a BigInt64BE value to the current write position (or at optional offset). + * + * @param value { BigInt } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigInt64BE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"); + return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset2); + } + /** + * Inserts a BigInt64BE value at the given offset value. + * + * @param value { BigInt } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigInt64BE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"); + return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset2); + } + /** + * Writes a BigInt64LE value to the current write position (or at optional offset). + * + * @param value { BigInt } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigInt64LE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"); + return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset2); + } + /** + * Inserts a Int64LE value at the given offset value. + * + * @param value { BigInt } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigInt64LE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"); + return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset2); + } + // Unsigned Integers + /** + * Reads an UInt8 value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt8(offset2) { + return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset2); + } + /** + * Reads an UInt16BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt16BE(offset2) { + return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset2); + } + /** + * Reads an UInt16LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt16LE(offset2) { + return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset2); + } + /** + * Reads an UInt32BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt32BE(offset2) { + return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset2); + } + /** + * Reads an UInt32LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readUInt32LE(offset2) { + return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset2); + } + /** + * Reads a BigUInt64BE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigUInt64BE(offset2) { + utils_1.bigIntAndBufferInt64Check("readBigUInt64BE"); + return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset2); + } + /** + * Reads a BigUInt64LE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { BigInt } + */ + readBigUInt64LE(offset2) { + utils_1.bigIntAndBufferInt64Check("readBigUInt64LE"); + return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset2); + } + /** + * Writes an UInt8 value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt8(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset2); + } + /** + * Inserts an UInt8 value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt8(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset2); + } + /** + * Writes an UInt16BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt16BE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset2); + } + /** + * Inserts an UInt16BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt16BE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset2); + } + /** + * Writes an UInt16LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt16LE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset2); + } + /** + * Inserts an UInt16LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt16LE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset2); + } + /** + * Writes an UInt32BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt32BE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset2); + } + /** + * Inserts an UInt32BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt32BE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset2); + } + /** + * Writes an UInt32LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeUInt32LE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset2); + } + /** + * Inserts an UInt32LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertUInt32LE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset2); + } + /** + * Writes a BigUInt64BE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigUInt64BE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"); + return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset2); + } + /** + * Inserts a BigUInt64BE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigUInt64BE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"); + return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset2); + } + /** + * Writes a BigUInt64LE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeBigUInt64LE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"); + return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset2); + } + /** + * Inserts a BigUInt64LE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertBigUInt64LE(value, offset2) { + utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"); + return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset2); + } + // Floating Point + /** + * Reads an FloatBE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readFloatBE(offset2) { + return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset2); + } + /** + * Reads an FloatLE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readFloatLE(offset2) { + return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset2); + } + /** + * Writes a FloatBE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeFloatBE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset2); + } + /** + * Inserts a FloatBE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertFloatBE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset2); + } + /** + * Writes a FloatLE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeFloatLE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset2); + } + /** + * Inserts a FloatLE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertFloatLE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset2); + } + // Double Floating Point + /** + * Reads an DoublEBE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readDoubleBE(offset2) { + return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset2); + } + /** + * Reads an DoubleLE value from the current read position or an optionally provided offset. + * + * @param offset { Number } The offset to read data from (optional) + * @return { Number } + */ + readDoubleLE(offset2) { + return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset2); + } + /** + * Writes a DoubleBE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeDoubleBE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset2); + } + /** + * Inserts a DoubleBE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertDoubleBE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset2); + } + /** + * Writes a DoubleLE value to the current write position (or at optional offset). + * + * @param value { Number } The value to write. + * @param offset { Number } The offset to write the value at. + * + * @return this + */ + writeDoubleLE(value, offset2) { + return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset2); + } + /** + * Inserts a DoubleLE value at the given offset value. + * + * @param value { Number } The value to insert. + * @param offset { Number } The offset to insert the value at. + * + * @return this + */ + insertDoubleLE(value, offset2) { + return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset2); + } + // Strings + /** + * Reads a String from the current read position. + * + * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for + * the string (Defaults to instance level encoding). + * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). + * + * @return { String } + */ + readString(arg1, encoding2) { + let lengthVal; + if (typeof arg1 === "number") { + utils_1.checkLengthValue(arg1); + lengthVal = Math.min(arg1, this.length - this._readOffset); + } else { + encoding2 = arg1; + lengthVal = this.length - this._readOffset; + } + if (typeof encoding2 !== "undefined") { + utils_1.checkEncoding(encoding2); + } + const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding2 || this._encoding); + this._readOffset += lengthVal; + return value; + } + /** + * Inserts a String + * + * @param value { String } The String value to insert. + * @param offset { Number } The offset to insert the string at. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + insertString(value, offset2, encoding2) { + utils_1.checkOffsetValue(offset2); + return this._handleString(value, true, offset2, encoding2); + } + /** + * Writes a String + * + * @param value { String } The String value to write. + * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + writeString(value, arg2, encoding2) { + return this._handleString(value, false, arg2, encoding2); + } + /** + * Reads a null-terminated String from the current read position. + * + * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). + * + * @return { String } + */ + readStringNT(encoding2) { + if (typeof encoding2 !== "undefined") { + utils_1.checkEncoding(encoding2); + } + let nullPos = this.length; + for (let i = this._readOffset; i < this.length; i++) { + if (this._buff[i] === 0) { + nullPos = i; + break; + } + } + const value = this._buff.slice(this._readOffset, nullPos); + this._readOffset = nullPos + 1; + return value.toString(encoding2 || this._encoding); + } + /** + * Inserts a null-terminated String. + * + * @param value { String } The String value to write. + * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + insertStringNT(value, offset2, encoding2) { + utils_1.checkOffsetValue(offset2); + this.insertString(value, offset2, encoding2); + this.insertUInt8(0, offset2 + value.length); + return this; + } + /** + * Writes a null-terminated String. + * + * @param value { String } The String value to write. + * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + * + * @return this + */ + writeStringNT(value, arg2, encoding2) { + this.writeString(value, arg2, encoding2); + this.writeUInt8(0, typeof arg2 === "number" ? arg2 + value.length : this.writeOffset); + return this; + } + // Buffers + /** + * Reads a Buffer from the internal read position. + * + * @param length { Number } The length of data to read as a Buffer. + * + * @return { Buffer } + */ + readBuffer(length) { + if (typeof length !== "undefined") { + utils_1.checkLengthValue(length); + } + const lengthVal = typeof length === "number" ? length : this.length; + const endPoint = Math.min(this.length, this._readOffset + lengthVal); + const value = this._buff.slice(this._readOffset, endPoint); + this._readOffset = endPoint; + return value; + } + /** + * Writes a Buffer to the current write position. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + insertBuffer(value, offset2) { + utils_1.checkOffsetValue(offset2); + return this._handleBuffer(value, true, offset2); + } + /** + * Writes a Buffer to the current write position. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + writeBuffer(value, offset2) { + return this._handleBuffer(value, false, offset2); + } + /** + * Reads a null-terminated Buffer from the current read poisiton. + * + * @return { Buffer } + */ + readBufferNT() { + let nullPos = this.length; + for (let i = this._readOffset; i < this.length; i++) { + if (this._buff[i] === 0) { + nullPos = i; + break; + } + } + const value = this._buff.slice(this._readOffset, nullPos); + this._readOffset = nullPos + 1; + return value; + } + /** + * Inserts a null-terminated Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + insertBufferNT(value, offset2) { + utils_1.checkOffsetValue(offset2); + this.insertBuffer(value, offset2); + this.insertUInt8(0, offset2 + value.length); + return this; + } + /** + * Writes a null-terminated Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + * + * @return this + */ + writeBufferNT(value, offset2) { + if (typeof offset2 !== "undefined") { + utils_1.checkOffsetValue(offset2); + } + this.writeBuffer(value, offset2); + this.writeUInt8(0, typeof offset2 === "number" ? offset2 + value.length : this._writeOffset); + return this; + } + /** + * Clears the SmartBuffer instance to its original empty state. + */ + clear() { + this._writeOffset = 0; + this._readOffset = 0; + this.length = 0; + return this; + } + /** + * Gets the remaining data left to be read from the SmartBuffer instance. + * + * @return { Number } + */ + remaining() { + return this.length - this._readOffset; + } + /** + * Gets the current read offset value of the SmartBuffer instance. + * + * @return { Number } + */ + get readOffset() { + return this._readOffset; + } + /** + * Sets the read offset value of the SmartBuffer instance. + * + * @param offset { Number } - The offset value to set. + */ + set readOffset(offset2) { + utils_1.checkOffsetValue(offset2); + utils_1.checkTargetOffset(offset2, this); + this._readOffset = offset2; + } + /** + * Gets the current write offset value of the SmartBuffer instance. + * + * @return { Number } + */ + get writeOffset() { + return this._writeOffset; + } + /** + * Sets the write offset value of the SmartBuffer instance. + * + * @param offset { Number } - The offset value to set. + */ + set writeOffset(offset2) { + utils_1.checkOffsetValue(offset2); + utils_1.checkTargetOffset(offset2, this); + this._writeOffset = offset2; + } + /** + * Gets the currently set string encoding of the SmartBuffer instance. + * + * @return { BufferEncoding } The string Buffer encoding currently set. + */ + get encoding() { + return this._encoding; + } + /** + * Sets the string encoding of the SmartBuffer instance. + * + * @param encoding { BufferEncoding } The string Buffer encoding to set. + */ + set encoding(encoding2) { + utils_1.checkEncoding(encoding2); + this._encoding = encoding2; + } + /** + * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) + * + * @return { Buffer } The Buffer value. + */ + get internalBuffer() { + return this._buff; + } + /** + * Gets the value of the internal managed Buffer (Includes managed data only) + * + * @param { Buffer } + */ + toBuffer() { + return this._buff.slice(0, this.length); + } + /** + * Gets the String value of the internal managed Buffer + * + * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). + */ + toString(encoding2) { + const encodingVal = typeof encoding2 === "string" ? encoding2 : this._encoding; + utils_1.checkEncoding(encodingVal); + return this._buff.toString(encodingVal, 0, this.length); + } + /** + * Destroys the SmartBuffer instance. + */ + destroy() { + this.clear(); + return this; + } + /** + * Handles inserting and writing strings. + * + * @param value { String } The String value to insert. + * @param isInsert { Boolean } True if inserting a string, false if writing. + * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. + * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). + */ + _handleString(value, isInsert, arg3, encoding2) { + let offsetVal = this._writeOffset; + let encodingVal = this._encoding; + if (typeof arg3 === "number") { + offsetVal = arg3; + } else if (typeof arg3 === "string") { + utils_1.checkEncoding(arg3); + encodingVal = arg3; + } + if (typeof encoding2 === "string") { + utils_1.checkEncoding(encoding2); + encodingVal = encoding2; + } + const byteLength = Buffer.byteLength(value, encodingVal); + if (isInsert) { + this.ensureInsertable(byteLength, offsetVal); + } else { + this._ensureWriteable(byteLength, offsetVal); + } + this._buff.write(value, offsetVal, byteLength, encodingVal); + if (isInsert) { + this._writeOffset += byteLength; + } else { + if (typeof arg3 === "number") { + this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); + } else { + this._writeOffset += byteLength; + } + } + return this; + } + /** + * Handles writing or insert of a Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + */ + _handleBuffer(value, isInsert, offset2) { + const offsetVal = typeof offset2 === "number" ? offset2 : this._writeOffset; + if (isInsert) { + this.ensureInsertable(value.length, offsetVal); + } else { + this._ensureWriteable(value.length, offsetVal); + } + value.copy(this._buff, offsetVal); + if (isInsert) { + this._writeOffset += value.length; + } else { + if (typeof offset2 === "number") { + this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); + } else { + this._writeOffset += value.length; + } + } + return this; + } + /** + * Ensures that the internal Buffer is large enough to read data. + * + * @param length { Number } The length of the data that needs to be read. + * @param offset { Number } The offset of the data that needs to be read. + */ + ensureReadable(length, offset2) { + let offsetVal = this._readOffset; + if (typeof offset2 !== "undefined") { + utils_1.checkOffsetValue(offset2); + offsetVal = offset2; + } + if (offsetVal < 0 || offsetVal + length > this.length) { + throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); + } + } + /** + * Ensures that the internal Buffer is large enough to insert data. + * + * @param dataLength { Number } The length of the data that needs to be written. + * @param offset { Number } The offset of the data to be written. + */ + ensureInsertable(dataLength, offset2) { + utils_1.checkOffsetValue(offset2); + this._ensureCapacity(this.length + dataLength); + if (offset2 < this.length) { + this._buff.copy(this._buff, offset2 + dataLength, offset2, this._buff.length); + } + if (offset2 + dataLength > this.length) { + this.length = offset2 + dataLength; + } else { + this.length += dataLength; + } + } + /** + * Ensures that the internal Buffer is large enough to write data. + * + * @param dataLength { Number } The length of the data that needs to be written. + * @param offset { Number } The offset of the data to be written (defaults to writeOffset). + */ + _ensureWriteable(dataLength, offset2) { + const offsetVal = typeof offset2 === "number" ? offset2 : this._writeOffset; + this._ensureCapacity(offsetVal + dataLength); + if (offsetVal + dataLength > this.length) { + this.length = offsetVal + dataLength; + } + } + /** + * Ensures that the internal Buffer is large enough to write at least the given amount of data. + * + * @param minLength { Number } The minimum length of the data needs to be written. + */ + _ensureCapacity(minLength) { + const oldLength = this._buff.length; + if (minLength > oldLength) { + let data2 = this._buff; + let newLength = oldLength * 3 / 2 + 1; + if (newLength < minLength) { + newLength = minLength; + } + this._buff = Buffer.allocUnsafe(newLength); + data2.copy(this._buff, 0, 0, oldLength); + } + } + /** + * Reads a numeric number value using the provided function. + * + * @typeparam T { number | bigint } The type of the value to be read + * + * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. + * @param byteSize { Number } The number of bytes read. + * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. + * + * @returns { T } the number value + */ + _readNumberValue(func, byteSize, offset2) { + this.ensureReadable(byteSize, offset2); + const value = func.call(this._buff, typeof offset2 === "number" ? offset2 : this._readOffset); + if (typeof offset2 === "undefined") { + this._readOffset += byteSize; + } + return value; + } + /** + * Inserts a numeric number value based on the given offset and value. + * + * @typeparam T { number | bigint } The type of the value to be written + * + * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. + * @param byteSize { Number } The number of bytes written. + * @param value { T } The number value to write. + * @param offset { Number } the offset to write the number at (REQUIRED). + * + * @returns SmartBuffer this buffer + */ + _insertNumberValue(func, byteSize, value, offset2) { + utils_1.checkOffsetValue(offset2); + this.ensureInsertable(byteSize, offset2); + func.call(this._buff, value, offset2); + this._writeOffset += byteSize; + return this; + } + /** + * Writes a numeric number value based on the given offset and value. + * + * @typeparam T { number | bigint } The type of the value to be written + * + * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. + * @param byteSize { Number } The number of bytes written. + * @param value { T } The number value to write. + * @param offset { Number } the offset to write the number at (REQUIRED). + * + * @returns SmartBuffer this buffer + */ + _writeNumberValue(func, byteSize, value, offset2) { + if (typeof offset2 === "number") { + if (offset2 < 0) { + throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); + } + utils_1.checkOffsetValue(offset2); + } + const offsetVal = typeof offset2 === "number" ? offset2 : this._writeOffset; + this._ensureWriteable(byteSize, offsetVal); + func.call(this._buff, value, offsetVal); + if (typeof offset2 === "number") { + this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); + } else { + this._writeOffset += byteSize; + } + return this; + } + } + smartbuffer.SmartBuffer = SmartBuffer; + return smartbuffer; +} +var constants$2 = {}; +var hasRequiredConstants$2; +function requireConstants$2() { + if (hasRequiredConstants$2) return constants$2; + hasRequiredConstants$2 = 1; + Object.defineProperty(constants$2, "__esModule", { value: true }); + constants$2.SOCKS5_NO_ACCEPTABLE_AUTH = constants$2.SOCKS5_CUSTOM_AUTH_END = constants$2.SOCKS5_CUSTOM_AUTH_START = constants$2.SOCKS_INCOMING_PACKET_SIZES = constants$2.SocksClientState = constants$2.Socks5Response = constants$2.Socks5HostType = constants$2.Socks5Auth = constants$2.Socks4Response = constants$2.SocksCommand = constants$2.ERRORS = constants$2.DEFAULT_TIMEOUT = void 0; + const DEFAULT_TIMEOUT = 3e4; + constants$2.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; + const ERRORS = { + InvalidSocksCommand: "An invalid SOCKS command was provided. Valid options are connect, bind, and associate.", + InvalidSocksCommandForOperation: "An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.", + InvalidSocksCommandChain: "An invalid SOCKS command was provided. Chaining currently only supports the connect command.", + InvalidSocksClientOptionsDestination: "An invalid destination host was provided.", + InvalidSocksClientOptionsExistingSocket: "An invalid existing socket was provided. This should be an instance of stream.Duplex.", + InvalidSocksClientOptionsProxy: "Invalid SOCKS proxy details were provided.", + InvalidSocksClientOptionsTimeout: "An invalid timeout value was provided. Please enter a value above 0 (in ms).", + InvalidSocksClientOptionsProxiesLength: "At least two socks proxies must be provided for chaining.", + InvalidSocksClientOptionsCustomAuthRange: "Custom auth must be a value between 0x80 and 0xFE.", + InvalidSocksClientOptionsCustomAuthOptions: "When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.", + NegotiationError: "Negotiation error", + SocketClosed: "Socket closed", + ProxyConnectionTimedOut: "Proxy connection timed out", + InternalError: "SocksClient internal error (this should not happen)", + InvalidSocks4HandshakeResponse: "Received invalid Socks4 handshake response", + Socks4ProxyRejectedConnection: "Socks4 Proxy rejected connection", + InvalidSocks4IncomingConnectionResponse: "Socks4 invalid incoming connection response", + Socks4ProxyRejectedIncomingBoundConnection: "Socks4 Proxy rejected incoming bound connection", + InvalidSocks5InitialHandshakeResponse: "Received invalid Socks5 initial handshake response", + InvalidSocks5IntiailHandshakeSocksVersion: "Received invalid Socks5 initial handshake (invalid socks version)", + InvalidSocks5InitialHandshakeNoAcceptedAuthType: "Received invalid Socks5 initial handshake (no accepted authentication type)", + InvalidSocks5InitialHandshakeUnknownAuthType: "Received invalid Socks5 initial handshake (unknown authentication type)", + Socks5AuthenticationFailed: "Socks5 Authentication failed", + InvalidSocks5FinalHandshake: "Received invalid Socks5 final handshake response", + InvalidSocks5FinalHandshakeRejected: "Socks5 proxy rejected connection", + InvalidSocks5IncomingConnectionResponse: "Received invalid Socks5 incoming connection response", + Socks5ProxyRejectedIncomingBoundConnection: "Socks5 Proxy rejected incoming bound connection" + }; + constants$2.ERRORS = ERRORS; + const SOCKS_INCOMING_PACKET_SIZES = { + Socks5InitialHandshakeResponse: 2, + Socks5UserPassAuthenticationResponse: 2, + // Command response + incoming connection (bind) + Socks5ResponseHeader: 5, + // We need at least 5 to read the hostname length, then we wait for the address+port information. + Socks5ResponseIPv4: 10, + // 4 header + 4 ip + 2 port + Socks5ResponseIPv6: 22, + // 4 header + 16 ip + 2 port + Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7, + // 4 header + 1 host length + host + 2 port + // Command response + incoming connection (bind) + Socks4Response: 8 + // 2 header + 2 port + 4 ip + }; + constants$2.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES; + var SocksCommand; + (function(SocksCommand2) { + SocksCommand2[SocksCommand2["connect"] = 1] = "connect"; + SocksCommand2[SocksCommand2["bind"] = 2] = "bind"; + SocksCommand2[SocksCommand2["associate"] = 3] = "associate"; + })(SocksCommand || (constants$2.SocksCommand = SocksCommand = {})); + var Socks4Response; + (function(Socks4Response2) { + Socks4Response2[Socks4Response2["Granted"] = 90] = "Granted"; + Socks4Response2[Socks4Response2["Failed"] = 91] = "Failed"; + Socks4Response2[Socks4Response2["Rejected"] = 92] = "Rejected"; + Socks4Response2[Socks4Response2["RejectedIdent"] = 93] = "RejectedIdent"; + })(Socks4Response || (constants$2.Socks4Response = Socks4Response = {})); + var Socks5Auth; + (function(Socks5Auth2) { + Socks5Auth2[Socks5Auth2["NoAuth"] = 0] = "NoAuth"; + Socks5Auth2[Socks5Auth2["GSSApi"] = 1] = "GSSApi"; + Socks5Auth2[Socks5Auth2["UserPass"] = 2] = "UserPass"; + })(Socks5Auth || (constants$2.Socks5Auth = Socks5Auth = {})); + const SOCKS5_CUSTOM_AUTH_START = 128; + constants$2.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START; + const SOCKS5_CUSTOM_AUTH_END = 254; + constants$2.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END; + const SOCKS5_NO_ACCEPTABLE_AUTH = 255; + constants$2.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH; + var Socks5Response; + (function(Socks5Response2) { + Socks5Response2[Socks5Response2["Granted"] = 0] = "Granted"; + Socks5Response2[Socks5Response2["Failure"] = 1] = "Failure"; + Socks5Response2[Socks5Response2["NotAllowed"] = 2] = "NotAllowed"; + Socks5Response2[Socks5Response2["NetworkUnreachable"] = 3] = "NetworkUnreachable"; + Socks5Response2[Socks5Response2["HostUnreachable"] = 4] = "HostUnreachable"; + Socks5Response2[Socks5Response2["ConnectionRefused"] = 5] = "ConnectionRefused"; + Socks5Response2[Socks5Response2["TTLExpired"] = 6] = "TTLExpired"; + Socks5Response2[Socks5Response2["CommandNotSupported"] = 7] = "CommandNotSupported"; + Socks5Response2[Socks5Response2["AddressNotSupported"] = 8] = "AddressNotSupported"; + })(Socks5Response || (constants$2.Socks5Response = Socks5Response = {})); + var Socks5HostType; + (function(Socks5HostType2) { + Socks5HostType2[Socks5HostType2["IPv4"] = 1] = "IPv4"; + Socks5HostType2[Socks5HostType2["Hostname"] = 3] = "Hostname"; + Socks5HostType2[Socks5HostType2["IPv6"] = 4] = "IPv6"; + })(Socks5HostType || (constants$2.Socks5HostType = Socks5HostType = {})); + var SocksClientState; + (function(SocksClientState2) { + SocksClientState2[SocksClientState2["Created"] = 0] = "Created"; + SocksClientState2[SocksClientState2["Connecting"] = 1] = "Connecting"; + SocksClientState2[SocksClientState2["Connected"] = 2] = "Connected"; + SocksClientState2[SocksClientState2["SentInitialHandshake"] = 3] = "SentInitialHandshake"; + SocksClientState2[SocksClientState2["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse"; + SocksClientState2[SocksClientState2["SentAuthentication"] = 5] = "SentAuthentication"; + SocksClientState2[SocksClientState2["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse"; + SocksClientState2[SocksClientState2["SentFinalHandshake"] = 7] = "SentFinalHandshake"; + SocksClientState2[SocksClientState2["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse"; + SocksClientState2[SocksClientState2["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection"; + SocksClientState2[SocksClientState2["Established"] = 10] = "Established"; + SocksClientState2[SocksClientState2["Disconnected"] = 11] = "Disconnected"; + SocksClientState2[SocksClientState2["Error"] = 99] = "Error"; + })(SocksClientState || (constants$2.SocksClientState = SocksClientState = {})); + return constants$2; +} +var helpers$1 = {}; +var util = {}; +var hasRequiredUtil; +function requireUtil() { + if (hasRequiredUtil) return util; + hasRequiredUtil = 1; + Object.defineProperty(util, "__esModule", { value: true }); + util.shuffleArray = util.SocksClientError = void 0; + class SocksClientError extends Error { + constructor(message, options2) { + super(message); + this.options = options2; + } + } + util.SocksClientError = SocksClientError; + function shuffleArray(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + } + util.shuffleArray = shuffleArray; + return util; +} +var ipAddress = {}; +var ipv4 = {}; +var common = {}; +var hasRequiredCommon; +function requireCommon() { + if (hasRequiredCommon) return common; + hasRequiredCommon = 1; + Object.defineProperty(common, "__esModule", { value: true }); + common.isCorrect = common.isInSubnet = void 0; + function isInSubnet(address) { + if (this.subnetMask < address.subnetMask) { + return false; + } + if (this.mask(address.subnetMask) === address.mask()) { + return true; + } + return false; + } + common.isInSubnet = isInSubnet; + function isCorrect(defaultBits) { + return function() { + if (this.addressMinusSuffix !== this.correctForm()) { + return false; + } + if (this.subnetMask === defaultBits && !this.parsedSubnet) { + return true; + } + return this.parsedSubnet === String(this.subnetMask); + }; + } + common.isCorrect = isCorrect; + return common; +} +var constants$1 = {}; +var hasRequiredConstants$1; +function requireConstants$1() { + if (hasRequiredConstants$1) return constants$1; + hasRequiredConstants$1 = 1; + Object.defineProperty(constants$1, "__esModule", { value: true }); + constants$1.RE_SUBNET_STRING = constants$1.RE_ADDRESS = constants$1.GROUPS = constants$1.BITS = void 0; + constants$1.BITS = 32; + constants$1.GROUPS = 4; + constants$1.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; + constants$1.RE_SUBNET_STRING = /\/\d{1,2}$/; + return constants$1; +} +var addressError = {}; +var hasRequiredAddressError; +function requireAddressError() { + if (hasRequiredAddressError) return addressError; + hasRequiredAddressError = 1; + Object.defineProperty(addressError, "__esModule", { value: true }); + addressError.AddressError = void 0; + class AddressError extends Error { + constructor(message, parseMessage) { + super(message); + this.name = "AddressError"; + if (parseMessage !== null) { + this.parseMessage = parseMessage; + } + } + } + addressError.AddressError = AddressError; + return addressError; +} +var jsbn$1 = { exports: {} }; +var jsbn = jsbn$1.exports; +var hasRequiredJsbn; +function requireJsbn() { + if (hasRequiredJsbn) return jsbn$1.exports; + hasRequiredJsbn = 1; + (function(module, exports) { + (function() { + var dbits; + var canary = 244837814094590; + var j_lm = (canary & 16777215) == 15715070; + function BigInteger(a, b, c) { + if (a != null) + if ("number" == typeof a) this.fromNumber(a, b, c); + else if (b == null && "string" != typeof a) this.fromString(a, 256); + else this.fromString(a, b); + } + function nbi() { + return new BigInteger(null); + } + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 67108864); + w[j++] = v & 67108863; + } + return c; + } + function am2(i, x, w, j, c, n) { + var xl = x & 32767, xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 32767; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 32767) << 15) + w[j] + (c & 1073741823); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 1073741823; + } + return c; + } + function am3(i, x, w, j, c, n) { + var xl = x & 16383, xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 16383; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 16383) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 268435455; + } + return c; + } + var inBrowser = typeof navigator !== "undefined"; + if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (inBrowser && j_lm && navigator.appName != "Netscape") { + BigInteger.prototype.am = am1; + dbits = 26; + } else { + BigInteger.prototype.am = am3; + dbits = 28; + } + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = (1 << dbits) - 1; + BigInteger.prototype.DV = 1 << dbits; + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + var BI_RC = new Array(); + var rr, vv; + rr = "0".charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = "a".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = "A".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + function int2char(n) { + return BI_RM.charAt(n); + } + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return c == null ? -1 : c; + } + function bnpCopyTo(r) { + for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; + } + function bnpFromInt(x) { + this.t = 1; + this.s = x < 0 ? -1 : 0; + if (x > 0) this[0] = x; + else if (x < -1) this[0] = x + this.DV; + else this.t = 0; + } + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + function bnpFromString(s, b) { + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 256) k = 8; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while (--i >= 0) { + var x = k == 8 ? s[i] & 255 : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if (sh == 0) + this[this.t++] = x; + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; + this[this.t++] = x >> this.DB - sh; + } else + this[this.t - 1] |= x << sh; + sh += k; + if (sh >= this.DB) sh -= this.DB; + } + if (k == 8 && (s[0] & 128) != 0) { + this.s = -1; + if (sh > 0) this[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; + } + this.clamp(); + if (mi) BigInteger.ZERO.subTo(this, this); + } + function bnpClamp() { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) --this.t; + } + function bnToString(b) { + if (this.s < 0) return "-" + this.negate().toString(b); + var k; + if (b == 16) k = 4; + else if (b == 8) k = 3; + else if (b == 2) k = 1; + else if (b == 32) k = 5; + else if (b == 4) k = 2; + else return this.toRadix(b); + var km = (1 << k) - 1, d, m = false, r = "", i = this.t; + var p = this.DB - i * this.DB % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & (1 << p) - 1) << k - p; + d |= this[--i] >> (p += this.DB - k); + } else { + d = this[i] >> (p -= k) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) m = true; + if (m) r += int2char(d); + } + } + return m ? r : "0"; + } + function bnNegate() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + } + function bnAbs() { + return this.s < 0 ? this.negate() : this; + } + function bnCompareTo(a) { + var r = this.s - a.s; + if (r != 0) return r; + var i = this.t; + r = i - a.t; + if (r != 0) return this.s < 0 ? -r : r; + while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r; + return 0; + } + function nbits(x) { + var r = 1, t2; + if ((t2 = x >>> 16) != 0) { + x = t2; + r += 16; + } + if ((t2 = x >> 8) != 0) { + x = t2; + r += 8; + } + if ((t2 = x >> 4) != 0) { + x = t2; + r += 4; + } + if ((t2 = x >> 2) != 0) { + x = t2; + r += 2; + } + if ((t2 = x >> 1) != 0) { + x = t2; + r += 1; + } + return r; + } + function bnBitLength() { + if (this.t <= 0) return 0; + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); + } + function bnpDLShiftTo(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]; + for (i = n - 1; i >= 0; --i) r[i] = 0; + r.t = this.t + n; + r.s = this.s; + } + function bnpDRShiftTo(n, r) { + for (var i = n; i < this.t; ++i) r[i - n] = this[i]; + r.t = Math.max(this.t - n, 0); + r.s = this.s; + } + function bnpLShiftTo(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; + for (i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = this[i] >> cbs | c; + c = (this[i] & bm) << bs; + } + for (i = ds - 1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + } + function bnpRShiftTo(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; + r.t = this.t - ds; + r.clamp(); + } + function bnpSubTo(a, r) { + var i = 0, c = 0, m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = c < 0 ? -1 : 0; + if (c < -1) r[i++] = this.DV + c; + else if (c > 0) r[i++] = c; + r.t = i; + r.clamp(); + } + function bnpMultiplyTo(a, r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + r.s = 0; + r.clamp(); + if (this.s != a.s) BigInteger.ZERO.subTo(r, r); + } + function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) r[i] = 0; + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + r.s = 0; + r.clamp(); + } + function bnpDivRemTo(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) return; + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) q.fromInt(0); + if (r != null) this.copyTo(r); + return; + } + if (r == null) r = nbi(); + var y = nbi(), ts = this.s, ms2 = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) return; + var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; + var i = r.t, j = i - ys, t2 = q == null ? nbi() : q; + y.dlShiftTo(j, t2); + if (r.compareTo(t2) >= 0) { + r[r.t++] = 1; + r.subTo(t2, r); + } + BigInteger.ONE.dlShiftTo(ys, t2); + t2.subTo(y, y); + while (y.t < ys) y[y.t++] = 0; + while (--j >= 0) { + var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { + y.dlShiftTo(j, t2); + r.subTo(t2, r); + while (r[i] < --qd) r.subTo(t2, r); + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms2) BigInteger.ZERO.subTo(q, q); + } + r.t = ys; + r.clamp(); + if (nsh > 0) r.rShiftTo(nsh, r); + if (ts < 0) BigInteger.ZERO.subTo(r, r); + } + function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); + return r; + } + function Classic(m) { + this.m = m; + } + function cConvert(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { + return x; + } + function cReduce(x) { + x.divRemTo(this.m, null, x); + } + function cMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + function cSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; + function bnpInvDigit() { + if (this.t < 1) return 0; + var x = this[0]; + if ((x & 1) == 0) return 0; + var y = x & 3; + y = y * (2 - (x & 15) * y) & 15; + y = y * (2 - (x & 255) * y) & 255; + y = y * (2 - ((x & 65535) * y & 65535)) & 65535; + y = y * (2 - x * y % this.DV) % this.DV; + return y > 0 ? this.DV - y : -y; + } + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 32767; + this.mph = this.mp >> 15; + this.um = (1 << m.DB - 15) - 1; + this.mt2 = 2 * m.t; + } + function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); + return r; + } + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + function montReduce(x) { + while (x.t <= this.mt2) + x[x.t++] = 0; + for (var i = 0; i < this.m.t; ++i) { + var j = x[i] & 32767; + var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM; + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + function montSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + function montMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; + function bnpIsEven() { + return (this.t > 0 ? this[0] & 1 : this.s) == 0; + } + function bnpExp(e, z2) { + if (e > 4294967295 || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z2.convert(this), i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z2.sqrTo(r, r2); + if ((e & 1 << i) > 0) z2.mulTo(r2, g, r); + else { + var t2 = r; + r = r2; + r2 = t2; + } + } + return z2.revert(r); + } + function bnModPowInt(e, m) { + var z2; + if (e < 256 || m.isEven()) z2 = new Classic(m); + else z2 = new Montgomery(m); + return this.exp(e, z2); + } + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + function bnClone() { + var r = nbi(); + this.copyTo(r); + return r; + } + function bnIntValue() { + if (this.s < 0) { + if (this.t == 1) return this[0] - this.DV; + else if (this.t == 0) return -1; + } else if (this.t == 1) return this[0]; + else if (this.t == 0) return 0; + return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0]; + } + function bnByteValue() { + return this.t == 0 ? this.s : this[0] << 24 >> 24; + } + function bnShortValue() { + return this.t == 0 ? this.s : this[0] << 16 >> 16; + } + function bnpChunkSize(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + } + function bnSigNum() { + if (this.s < 0) return -1; + else if (this.t <= 0 || this.t == 1 && this[0] <= 0) return 0; + else return 1; + } + function bnpToRadix(b) { + if (b == null) b = 10; + if (this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a), y = nbi(), z2 = nbi(), r = ""; + this.divRemTo(d, y, z2); + while (y.signum() > 0) { + r = (a + z2.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z2); + } + return z2.intValue().toString(b) + r; + } + function bnpFromRadix(s, b) { + this.fromInt(0); + if (b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b, cs), mi = false, j = 0, w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) BigInteger.ZERO.subTo(this, this); + } + function bnpFromNumber(a, b, c) { + if ("number" == typeof b) { + if (a < 2) this.fromInt(1); + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + if (this.isEven()) this.dAddOffset(1, 0); + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } else { + var x = new Array(), t2 = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t2 > 0) x[0] &= (1 << t2) - 1; + else x[0] = 0; + this.fromString(x, 256); + } + } + function bnToByteArray() { + var i = this.t, r = new Array(); + r[0] = this.s; + var p = this.DB - i * this.DB % 8, d, k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) + r[k++] = d | this.s << this.DB - p; + while (i >= 0) { + if (p < 8) { + d = (this[i] & (1 << p) - 1) << 8 - p; + d |= this[--i] >> (p += this.DB - 8); + } else { + d = this[i] >> (p -= 8) & 255; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 128) != 0) d |= -256; + if (k == 0 && (this.s & 128) != (d & 128)) ++k; + if (k > 0 || d != this.s) r[k++] = d; + } + } + return r; + } + function bnEquals(a) { + return this.compareTo(a) == 0; + } + function bnMin(a) { + return this.compareTo(a) < 0 ? this : a; + } + function bnMax(a) { + return this.compareTo(a) > 0 ? this : a; + } + function bnpBitwiseTo(a, op, r) { + var i, f, m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]); + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) r[i] = op(this[i], f); + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) r[i] = op(f, a[i]); + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + } + function op_and(x, y) { + return x & y; + } + function bnAnd(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + } + function op_or(x, y) { + return x | y; + } + function bnOr(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + } + function op_xor(x, y) { + return x ^ y; + } + function bnXor(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + } + function op_andnot(x, y) { + return x & ~y; + } + function bnAndNot(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + } + function bnNot() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; + } + function bnShiftLeft(n) { + var r = nbi(); + if (n < 0) this.rShiftTo(-n, r); + else this.lShiftTo(n, r); + return r; + } + function bnShiftRight(n) { + var r = nbi(); + if (n < 0) this.lShiftTo(-n, r); + else this.rShiftTo(n, r); + return r; + } + function lbit(x) { + if (x == 0) return -1; + var r = 0; + if ((x & 65535) == 0) { + x >>= 16; + r += 16; + } + if ((x & 255) == 0) { + x >>= 8; + r += 8; + } + if ((x & 15) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) ++r; + return r; + } + function bnGetLowestSetBit() { + for (var i = 0; i < this.t; ++i) + if (this[i] != 0) return i * this.DB + lbit(this[i]); + if (this.s < 0) return this.t * this.DB; + return -1; + } + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + function bnBitCount() { + var r = 0, x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x); + return r; + } + function bnTestBit(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) return this.s != 0; + return (this[j] & 1 << n % this.DB) != 0; + } + function bnpChangeBit(n, op) { + var r = BigInteger.ONE.shiftLeft(n); + this.bitwiseTo(r, op, r); + return r; + } + function bnSetBit(n) { + return this.changeBit(n, op_or); + } + function bnClearBit(n) { + return this.changeBit(n, op_andnot); + } + function bnFlipBit(n) { + return this.changeBit(n, op_xor); + } + function bnpAddTo(a, r) { + var i = 0, c = 0, m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] + a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = c < 0 ? -1 : 0; + if (c > 0) r[i++] = c; + else if (c < -1) r[i++] = this.DV + c; + r.t = i; + r.clamp(); + } + function bnAdd(a) { + var r = nbi(); + this.addTo(a, r); + return r; + } + function bnSubtract(a) { + var r = nbi(); + this.subTo(a, r); + return r; + } + function bnMultiply(a) { + var r = nbi(); + this.multiplyTo(a, r); + return r; + } + function bnSquare() { + var r = nbi(); + this.squareTo(r); + return r; + } + function bnDivide(a) { + var r = nbi(); + this.divRemTo(a, r, null); + return r; + } + function bnRemainder(a) { + var r = nbi(); + this.divRemTo(a, null, r); + return r; + } + function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a, q, r); + return new Array(q, r); + } + function bnpDMultiply(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + } + function bnpDAddOffset(n, w) { + if (n == 0) return; + while (this.t <= w) this[this.t++] = 0; + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) this[this.t++] = 0; + ++this[w]; + } + } + function NullExp() { + } + function nNop(x) { + return x; + } + function nMulTo(x, y, r) { + x.multiplyTo(y, r); + } + function nSqrTo(x, r) { + x.squareTo(r); + } + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + function bnPow(e) { + return this.exp(e, new NullExp()); + } + function bnpMultiplyLowerTo(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; + r.t = i; + while (i > 0) r[--i] = 0; + var j; + for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i); + r.clamp(); + } + function bnpMultiplyUpperTo(a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; + while (--i >= 0) r[i] = 0; + for (i = Math.max(n - this.t, 0); i < a.t; ++i) + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + r.clamp(); + r.drShiftTo(1, r); + } + function Barrett(m) { + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + function barrettConvert(x) { + if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); + else if (x.compareTo(this.m) < 0) return x; + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + } + function barrettRevert(x) { + return x; + } + function barrettReduce(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); + } + function barrettSqrTo(x, r) { + x.squareTo(r); + this.reduce(r); + } + function barrettMulTo(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + } + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + function bnModPow(e, m) { + var i = e.bitLength(), k, r = nbv(1), z2; + if (i <= 0) return r; + else if (i < 18) k = 1; + else if (i < 48) k = 3; + else if (i < 144) k = 4; + else if (i < 768) k = 5; + else k = 6; + if (i < 8) + z2 = new Classic(m); + else if (m.isEven()) + z2 = new Barrett(m); + else + z2 = new Montgomery(m); + var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; + g[1] = z2.convert(this); + if (k > 1) { + var g2 = nbi(); + z2.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z2.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + var j = e.t - 1, w, is1 = true, r2 = nbi(), t2; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) w = e[j] >> i - k1 & km; + else { + w = (e[j] & (1 << i + 1) - 1) << k1 - i; + if (j > 0) w |= e[j - 1] >> this.DB + i - k1; + } + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z2.sqrTo(r, r2); + z2.sqrTo(r2, r); + n -= 2; + } + if (n > 0) z2.sqrTo(r, r2); + else { + t2 = r; + r = r2; + r2 = t2; + } + z2.mulTo(r2, g[w], r); + } + while (j >= 0 && (e[j] & 1 << i) == 0) { + z2.sqrTo(r, r2); + t2 = r; + r = r2; + r2 = t2; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z2.revert(r); + } + function bnGCD(a) { + var x = this.s < 0 ? this.negate() : this.clone(); + var y = a.s < 0 ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t2 = x; + x = y; + y = t2; + } + var i = x.getLowestSetBit(), g = y.getLowestSetBit(); + if (g < 0) return x; + if (i < g) g = i; + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); + if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) y.lShiftTo(g, y); + return y; + } + function bnpModInt(n) { + if (n <= 0) return 0; + var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; + if (this.t > 0) + if (d == 0) r = this[0] % n; + else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n; + return r; + } + function bnModInverse(m) { + var ac = m.isEven(); + if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } else if (!b.isEven()) b.subTo(m, b); + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) d.subTo(m, d); + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) a.subTo(c, a); + b.subTo(d, b); + } else { + v.subTo(u, v); + if (ac) c.subTo(a, c); + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if (d.compareTo(m) >= 0) return d.subtract(m); + if (d.signum() < 0) d.addTo(m, d); + else return d; + if (d.signum() < 0) return d.add(m); + else return d; + } + var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + function bnIsProbablePrime(t2) { + var i, x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) + if (x[0] == lowprimes[i]) return true; + return false; + } + if (x.isEven()) return false; + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i], j = i + 1; + while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while (i < j) if (m % lowprimes[i++] == 0) return false; + } + return x.millerRabin(t2); + } + function bnpMillerRabin(t2) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) return false; + var r = n1.shiftRight(k); + t2 = t2 + 1 >> 1; + if (t2 > lowprimes.length) t2 = lowprimes.length; + var a = nbi(); + for (var i = 0; i < t2; ++i) { + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) return false; + } + if (y.compareTo(n1) != 0) return false; + } + } + return true; + } + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + BigInteger.prototype.square = bnSquare; + BigInteger.prototype.Barrett = Barrett; + var rng_state; + var rng_pool; + var rng_pptr; + function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= x >> 8 & 255; + rng_pool[rng_pptr++] ^= x >> 16 & 255; + rng_pool[rng_pptr++] ^= x >> 24 & 255; + if (rng_pptr >= rng_psize) rng_pptr -= rng_psize; + } + function rng_seed_time() { + rng_seed_int((/* @__PURE__ */ new Date()).getTime()); + } + if (rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + if (typeof window !== "undefined" && window.crypto) { + if (window.crypto.getRandomValues) { + var ua = new Uint8Array(32); + window.crypto.getRandomValues(ua); + for (t = 0; t < 32; ++t) + rng_pool[rng_pptr++] = ua[t]; + } else if (navigator.appName == "Netscape" && navigator.appVersion < "5") { + var z = window.crypto.random(32); + for (t = 0; t < z.length; ++t) + rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; + } + } + while (rng_pptr < rng_psize) { + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; + } + rng_pptr = 0; + rng_seed_time(); + } + function rng_get_byte() { + if (rng_state == null) { + rng_seed_time(); + rng_state = prng_newstate(); + rng_state.init(rng_pool); + for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) + rng_pool[rng_pptr] = 0; + rng_pptr = 0; + } + return rng_state.next(); + } + function rng_get_bytes(ba) { + var i; + for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); + } + function SecureRandom() { + } + SecureRandom.prototype.nextBytes = rng_get_bytes; + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); + } + function ARC4init(key2) { + var i, j, t2; + for (i = 0; i < 256; ++i) + this.S[i] = i; + j = 0; + for (i = 0; i < 256; ++i) { + j = j + this.S[i] + key2[i % key2.length] & 255; + t2 = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t2; + } + this.i = 0; + this.j = 0; + } + function ARC4next() { + var t2; + this.i = this.i + 1 & 255; + this.j = this.j + this.S[this.i] & 255; + t2 = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t2; + return this.S[t2 + this.S[this.i] & 255]; + } + Arcfour.prototype.init = ARC4init; + Arcfour.prototype.next = ARC4next; + function prng_newstate() { + return new Arcfour(); + } + var rng_psize = 256; + { + module.exports = { + default: BigInteger, + BigInteger, + SecureRandom + }; + } + }).call(jsbn); + })(jsbn$1); + return jsbn$1.exports; +} +var sprintf = {}; +var hasRequiredSprintf; +function requireSprintf() { + if (hasRequiredSprintf) return sprintf; + hasRequiredSprintf = 1; + (function(exports) { + !function() { + var re2 = { + not_type: /[^T]/, + not_primitive: /[^v]/, + number: /[diefg]/, + numeric_arg: /[bcdiefguxX]/, + 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 sprintf2(key2) { + return sprintf_format(sprintf_parse(key2), arguments); + } + function vsprintf(fmt, argv) { + return sprintf2.apply(null, [fmt].concat(argv || [])); + } + function sprintf_format(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, arg, output = "", i, k, ph, pad, pad_character, pad_length, is_positive, sign2; + for (i = 0; i < tree_length; i++) { + if (typeof parse_tree[i] === "string") { + output += parse_tree[i]; + } else if (typeof parse_tree[i] === "object") { + ph = parse_tree[i]; + if (ph.keys) { + arg = argv[cursor]; + for (k = 0; k < ph.keys.length; k++) { + if (arg == void 0) { + throw new Error(sprintf2('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1])); + } + arg = arg[ph.keys[k]]; + } + } else if (ph.param_no) { + arg = argv[ph.param_no]; + } else { + arg = argv[cursor++]; + } + if (re2.not_type.test(ph.type) && re2.not_primitive.test(ph.type) && arg instanceof Function) { + arg = arg(); + } + if (re2.numeric_arg.test(ph.type) && (typeof arg !== "number" && isNaN(arg))) { + throw new TypeError(sprintf2("[sprintf] expecting number but found %T", arg)); + } + if (re2.number.test(ph.type)) { + is_positive = arg >= 0; + } + switch (ph.type) { + case "b": + arg = parseInt(arg, 10).toString(2); + break; + case "c": + arg = String.fromCharCode(parseInt(arg, 10)); + break; + case "d": + case "i": + arg = parseInt(arg, 10); + break; + case "j": + arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0); + break; + case "e": + arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential(); + break; + case "f": + arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg); + break; + case "g": + arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg); + break; + case "o": + arg = (parseInt(arg, 10) >>> 0).toString(8); + break; + case "s": + arg = String(arg); + arg = ph.precision ? arg.substring(0, ph.precision) : arg; + break; + case "t": + arg = String(!!arg); + arg = ph.precision ? arg.substring(0, ph.precision) : arg; + break; + case "T": + arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase(); + arg = ph.precision ? arg.substring(0, ph.precision) : arg; + break; + case "u": + arg = parseInt(arg, 10) >>> 0; + break; + case "v": + arg = arg.valueOf(); + arg = ph.precision ? arg.substring(0, ph.precision) : arg; + break; + case "x": + arg = (parseInt(arg, 10) >>> 0).toString(16); + break; + case "X": + arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase(); + break; + } + if (re2.json.test(ph.type)) { + output += arg; + } else { + if (re2.number.test(ph.type) && (!is_positive || ph.sign)) { + sign2 = is_positive ? "+" : "-"; + arg = arg.toString().replace(re2.sign, ""); + } else { + sign2 = ""; + } + pad_character = ph.pad_char ? ph.pad_char === "0" ? "0" : ph.pad_char.charAt(1) : " "; + pad_length = ph.width - (sign2 + arg).length; + pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : "" : ""; + output += ph.align ? sign2 + arg + pad : pad_character === "0" ? sign2 + pad + arg : pad + sign2 + arg; + } + } + } + return output; + } + var sprintf_cache = /* @__PURE__ */ Object.create(null); + function sprintf_parse(fmt) { + if (sprintf_cache[fmt]) { + return sprintf_cache[fmt]; + } + var _fmt = fmt, match, parse_tree = [], arg_names = 0; + while (_fmt) { + if ((match = re2.text.exec(_fmt)) !== null) { + parse_tree.push(match[0]); + } else if ((match = re2.modulo.exec(_fmt)) !== null) { + parse_tree.push("%"); + } else if ((match = re2.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1; + var field_list = [], replacement_field = match[2], field_match = []; + if ((field_match = re2.key.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re2.key_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } else if ((field_match = re2.index_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } else { + throw new SyntaxError("[sprintf] failed to parse named argument key"); + } + } + } else { + throw new SyntaxError("[sprintf] failed to parse named argument key"); + } + match[2] = field_list; + } else { + arg_names |= 2; + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported"); + } + parse_tree.push( + { + placeholder: match[0], + param_no: match[1], + keys: match[2], + sign: match[3], + pad_char: match[4], + align: match[5], + width: match[6], + precision: match[7], + type: match[8] + } + ); + } else { + throw new SyntaxError("[sprintf] unexpected placeholder"); + } + _fmt = _fmt.substring(match[0].length); + } + return sprintf_cache[fmt] = parse_tree; + } + { + exports["sprintf"] = sprintf2; + exports["vsprintf"] = vsprintf; + } + if (typeof window !== "undefined") { + window["sprintf"] = sprintf2; + window["vsprintf"] = vsprintf; + } + }(); + })(sprintf); + return sprintf; +} +var hasRequiredIpv4; +function requireIpv4() { + if (hasRequiredIpv4) return ipv4; + hasRequiredIpv4 = 1; + var __createBinding = ipv4 && ipv4.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = ipv4 && ipv4.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = ipv4 && ipv4.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(ipv4, "__esModule", { value: true }); + ipv4.Address4 = void 0; + const common2 = __importStar(requireCommon()); + const constants2 = __importStar(requireConstants$1()); + const address_error_1 = requireAddressError(); + const jsbn_1 = requireJsbn(); + const sprintf_js_1 = requireSprintf(); + class Address4 { + constructor(address) { + this.groups = constants2.GROUPS; + this.parsedAddress = []; + this.parsedSubnet = ""; + this.subnet = "/32"; + this.subnetMask = 32; + this.v4 = true; + this.isCorrect = common2.isCorrect(constants2.BITS); + this.isInSubnet = common2.isInSubnet; + this.address = address; + const subnet = constants2.RE_SUBNET_STRING.exec(address); + if (subnet) { + this.parsedSubnet = subnet[0].replace("/", ""); + this.subnetMask = parseInt(this.parsedSubnet, 10); + this.subnet = `/${this.subnetMask}`; + if (this.subnetMask < 0 || this.subnetMask > constants2.BITS) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + address = address.replace(constants2.RE_SUBNET_STRING, ""); + } + this.addressMinusSuffix = address; + this.parsedAddress = this.parse(address); + } + static isValid(address) { + try { + new Address4(address); + return true; + } catch (e) { + return false; + } + } + /* + * Parses a v4 address + */ + parse(address) { + const groups = address.split("."); + if (!address.match(constants2.RE_ADDRESS)) { + throw new address_error_1.AddressError("Invalid IPv4 address."); + } + return groups; + } + /** + * Returns the correct form of an address + * @memberof Address4 + * @instance + * @returns {String} + */ + correctForm() { + return this.parsedAddress.map((part) => parseInt(part, 10)).join("."); + } + /** + * Converts a hex string to an IPv4 address object + * @memberof Address4 + * @static + * @param {string} hex - a hex string to convert + * @returns {Address4} + */ + static fromHex(hex) { + const padded = hex.replace(/:/g, "").padStart(8, "0"); + const groups = []; + let i; + for (i = 0; i < 8; i += 2) { + const h = padded.slice(i, i + 2); + groups.push(parseInt(h, 16)); + } + return new Address4(groups.join(".")); + } + /** + * Converts an integer into a IPv4 address object + * @memberof Address4 + * @static + * @param {integer} integer - a number to convert + * @returns {Address4} + */ + static fromInteger(integer) { + return Address4.fromHex(integer.toString(16)); + } + /** + * Return an address from in-addr.arpa form + * @memberof Address4 + * @static + * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address + * @returns {Adress4} + * @example + * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) + * address.correctForm(); // '192.0.2.42' + */ + static fromArpa(arpaFormAddress) { + const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ""); + const address = leader.split(".").reverse().join("."); + return new Address4(address); + } + /** + * Converts an IPv4 address object to a hex string + * @memberof Address4 + * @instance + * @returns {String} + */ + toHex() { + return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)("%02x", parseInt(part, 10))).join(":"); + } + /** + * Converts an IPv4 address object to an array of bytes + * @memberof Address4 + * @instance + * @returns {Array} + */ + toArray() { + return this.parsedAddress.map((part) => parseInt(part, 10)); + } + /** + * Converts an IPv4 address object to an IPv6 address group + * @memberof Address4 + * @instance + * @returns {String} + */ + toGroup6() { + const output = []; + let i; + for (i = 0; i < constants2.GROUPS; i += 2) { + const hex = (0, sprintf_js_1.sprintf)("%02x%02x", parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10)); + output.push((0, sprintf_js_1.sprintf)("%x", parseInt(hex, 16))); + } + return output.join(":"); + } + /** + * Returns the address as a BigInteger + * @memberof Address4 + * @instance + * @returns {BigInteger} + */ + bigInteger() { + return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)("%02x", parseInt(n, 10))).join(""), 16); + } + /** + * Helper function getting start address. + * @memberof Address4 + * @instance + * @returns {BigInteger} + */ + _startAddress() { + return new jsbn_1.BigInteger(this.mask() + "0".repeat(constants2.BITS - this.subnetMask), 2); + } + /** + * The first address in the range given by this address' subnet. + * Often referred to as the Network Address. + * @memberof Address4 + * @instance + * @returns {Address4} + */ + startAddress() { + return Address4.fromBigInteger(this._startAddress()); + } + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + * @memberof Address4 + * @instance + * @returns {Address4} + */ + startAddressExclusive() { + const adjust = new jsbn_1.BigInteger("1"); + return Address4.fromBigInteger(this._startAddress().add(adjust)); + } + /** + * Helper function getting end address. + * @memberof Address4 + * @instance + * @returns {BigInteger} + */ + _endAddress() { + return new jsbn_1.BigInteger(this.mask() + "1".repeat(constants2.BITS - this.subnetMask), 2); + } + /** + * The last address in the range given by this address' subnet + * Often referred to as the Broadcast + * @memberof Address4 + * @instance + * @returns {Address4} + */ + endAddress() { + return Address4.fromBigInteger(this._endAddress()); + } + /** + * The last host address in the range given by this address's subnet ie + * the last address prior to the Broadcast Address + * @memberof Address4 + * @instance + * @returns {Address4} + */ + endAddressExclusive() { + const adjust = new jsbn_1.BigInteger("1"); + return Address4.fromBigInteger(this._endAddress().subtract(adjust)); + } + /** + * Converts a BigInteger to a v4 address object + * @memberof Address4 + * @static + * @param {BigInteger} bigInteger - a BigInteger to convert + * @returns {Address4} + */ + static fromBigInteger(bigInteger) { + return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); + } + /** + * Returns the first n bits of the address, defaulting to the + * subnet mask + * @memberof Address4 + * @instance + * @returns {String} + */ + mask(mask) { + if (mask === void 0) { + mask = this.subnetMask; + } + return this.getBitsBase2(0, mask); + } + /** + * Returns the bits in the given range as a base-2 string + * @memberof Address4 + * @instance + * @returns {string} + */ + getBitsBase2(start, end) { + return this.binaryZeroPad().slice(start, end); + } + /** + * Return the reversed ip6.arpa form of the address + * @memberof Address4 + * @param {Object} options + * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix + * @instance + * @returns {String} + */ + reverseForm(options2) { + if (!options2) { + options2 = {}; + } + const reversed = this.correctForm().split(".").reverse().join("."); + if (options2.omitSuffix) { + return reversed; + } + return (0, sprintf_js_1.sprintf)("%s.in-addr.arpa.", reversed); + } + /** + * Returns true if the given address is a multicast address + * @memberof Address4 + * @instance + * @returns {boolean} + */ + isMulticast() { + return this.isInSubnet(new Address4("224.0.0.0/4")); + } + /** + * Returns a zero-padded base-2 string representation of the address + * @memberof Address4 + * @instance + * @returns {string} + */ + binaryZeroPad() { + return this.bigInteger().toString(2).padStart(constants2.BITS, "0"); + } + /** + * Groups an IPv4 address for inclusion at the end of an IPv6 address + * @returns {String} + */ + groupForV6() { + const segments = this.parsedAddress; + return this.address.replace(constants2.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join("."), segments.slice(2, 4).join("."))); + } + } + ipv4.Address4 = Address4; + return ipv4; +} +var ipv6 = {}; +var constants = {}; +var hasRequiredConstants; +function requireConstants() { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + Object.defineProperty(constants, "__esModule", { value: true }); + constants.RE_URL_WITH_PORT = constants.RE_URL = constants.RE_ZONE_STRING = constants.RE_SUBNET_STRING = constants.RE_BAD_ADDRESS = constants.RE_BAD_CHARACTERS = constants.TYPES = constants.SCOPES = constants.GROUPS = constants.BITS = void 0; + constants.BITS = 128; + constants.GROUPS = 8; + constants.SCOPES = { + 0: "Reserved", + 1: "Interface local", + 2: "Link local", + 4: "Admin local", + 5: "Site local", + 8: "Organization local", + 14: "Global", + 15: "Reserved" + }; + constants.TYPES = { + "ff01::1/128": "Multicast (All nodes on this interface)", + "ff01::2/128": "Multicast (All routers on this interface)", + "ff02::1/128": "Multicast (All nodes on this link)", + "ff02::2/128": "Multicast (All routers on this link)", + "ff05::2/128": "Multicast (All routers in this site)", + "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)", + "ff02::6/128": "Multicast (OSPFv3 AllDR routers)", + "ff02::9/128": "Multicast (RIP routers)", + "ff02::a/128": "Multicast (EIGRP routers)", + "ff02::d/128": "Multicast (PIM routers)", + "ff02::16/128": "Multicast (MLDv2 reports)", + "ff01::fb/128": "Multicast (mDNSv6)", + "ff02::fb/128": "Multicast (mDNSv6)", + "ff05::fb/128": "Multicast (mDNSv6)", + "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)", + "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)", + "ff02::1:3/128": "Multicast (All DHCP servers on this link)", + "ff05::1:3/128": "Multicast (All DHCP servers in this site)", + "::/128": "Unspecified", + "::1/128": "Loopback", + "ff00::/8": "Multicast", + "fe80::/10": "Link-local unicast" + }; + constants.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; + constants.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; + constants.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; + constants.RE_ZONE_STRING = /%.*$/; + constants.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/); + constants.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/); + return constants; +} +var helpers = {}; +var hasRequiredHelpers$1; +function requireHelpers$1() { + if (hasRequiredHelpers$1) return helpers; + hasRequiredHelpers$1 = 1; + Object.defineProperty(helpers, "__esModule", { value: true }); + helpers.simpleGroup = helpers.spanLeadingZeroes = helpers.spanAll = helpers.spanAllZeroes = void 0; + const sprintf_js_1 = requireSprintf(); + function spanAllZeroes(s) { + return s.replace(/(0+)/g, '$1'); + } + helpers.spanAllZeroes = spanAllZeroes; + function spanAll(s, offset2 = 0) { + const letters = s.split(""); + return letters.map( + (n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset2, spanAllZeroes(n)) + // XXX Use #base-2 .value-0 instead? + ).join(""); + } + helpers.spanAll = spanAll; + function spanLeadingZeroesSimple(group) { + return group.replace(/^(0+)/, '$1'); + } + function spanLeadingZeroes(address) { + const groups = address.split(":"); + return groups.map((g) => spanLeadingZeroesSimple(g)).join(":"); + } + helpers.spanLeadingZeroes = spanLeadingZeroes; + function simpleGroup(addressString, offset2 = 0) { + const groups = addressString.split(":"); + return groups.map((g, i) => { + if (/group-v4/.test(g)) { + return g; + } + return (0, sprintf_js_1.sprintf)('%s', i + offset2, spanLeadingZeroesSimple(g)); + }); + } + helpers.simpleGroup = simpleGroup; + return helpers; +} +var regularExpressions = {}; +var hasRequiredRegularExpressions; +function requireRegularExpressions() { + if (hasRequiredRegularExpressions) return regularExpressions; + hasRequiredRegularExpressions = 1; + var __createBinding = regularExpressions && regularExpressions.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = regularExpressions && regularExpressions.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = regularExpressions && regularExpressions.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(regularExpressions, "__esModule", { value: true }); + regularExpressions.possibleElisions = regularExpressions.simpleRegularExpression = regularExpressions.ADDRESS_BOUNDARY = regularExpressions.padGroup = regularExpressions.groupPossibilities = void 0; + const v6 = __importStar(requireConstants()); + const sprintf_js_1 = requireSprintf(); + function groupPossibilities(possibilities) { + return (0, sprintf_js_1.sprintf)("(%s)", possibilities.join("|")); + } + regularExpressions.groupPossibilities = groupPossibilities; + function padGroup(group) { + if (group.length < 4) { + return (0, sprintf_js_1.sprintf)("0{0,%d}%s", 4 - group.length, group); + } + return group; + } + regularExpressions.padGroup = padGroup; + regularExpressions.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]"; + function simpleRegularExpression(groups) { + const zeroIndexes = []; + groups.forEach((group, i) => { + const groupInteger = parseInt(group, 16); + if (groupInteger === 0) { + zeroIndexes.push(i); + } + }); + const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => { + if (i === zeroIndex) { + const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : ""; + return groupPossibilities([padGroup(group), elision]); + } + return padGroup(group); + }).join(":")); + possibilities.push(groups.map(padGroup).join(":")); + return groupPossibilities(possibilities); + } + regularExpressions.simpleRegularExpression = simpleRegularExpression; + function possibleElisions(elidedGroups, moreLeft, moreRight) { + const left = moreLeft ? "" : ":"; + const right = moreRight ? "" : ":"; + const possibilities = []; + if (!moreLeft && !moreRight) { + possibilities.push("::"); + } + if (moreLeft && moreRight) { + possibilities.push(""); + } + if (moreRight && !moreLeft || !moreRight && moreLeft) { + possibilities.push(":"); + } + possibilities.push((0, sprintf_js_1.sprintf)("%s(:0{1,4}){1,%d}", left, elidedGroups - 1)); + possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){1,%d}%s", elidedGroups - 1, right)); + possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){%d}0{1,4}", elidedGroups - 1)); + for (let groups = 1; groups < elidedGroups - 1; groups++) { + for (let position = 1; position < elidedGroups - groups; position++) { + possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}", position, elidedGroups - position - groups - 1)); + } + } + return groupPossibilities(possibilities); + } + regularExpressions.possibleElisions = possibleElisions; + return regularExpressions; +} +var hasRequiredIpv6; +function requireIpv6() { + if (hasRequiredIpv6) return ipv6; + hasRequiredIpv6 = 1; + var __createBinding = ipv6 && ipv6.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = ipv6 && ipv6.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = ipv6 && ipv6.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(ipv6, "__esModule", { value: true }); + ipv6.Address6 = void 0; + const common2 = __importStar(requireCommon()); + const constants4 = __importStar(requireConstants$1()); + const constants6 = __importStar(requireConstants()); + const helpers2 = __importStar(requireHelpers$1()); + const ipv4_1 = requireIpv4(); + const regular_expressions_1 = requireRegularExpressions(); + const address_error_1 = requireAddressError(); + const jsbn_1 = requireJsbn(); + const sprintf_js_1 = requireSprintf(); + function assert2(condition) { + if (!condition) { + throw new Error("Assertion failed."); + } + } + function addCommas(number) { + const r = /(\d+)(\d{3})/; + while (r.test(number)) { + number = number.replace(r, "$1,$2"); + } + return number; + } + function spanLeadingZeroes4(n) { + n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); + n = n.replace(/^(0{1,})(0)$/, '$1$2'); + return n; + } + function compact(address, slice) { + const s1 = []; + const s2 = []; + let i; + for (i = 0; i < address.length; i++) { + if (i < slice[0]) { + s1.push(address[i]); + } else if (i > slice[1]) { + s2.push(address[i]); + } + } + return s1.concat(["compact"]).concat(s2); + } + function paddedHex(octet) { + return (0, sprintf_js_1.sprintf)("%04x", parseInt(octet, 16)); + } + function unsignByte(b) { + return b & 255; + } + class Address6 { + constructor(address, optionalGroups) { + this.addressMinusSuffix = ""; + this.parsedSubnet = ""; + this.subnet = "/128"; + this.subnetMask = 128; + this.v4 = false; + this.zone = ""; + this.isInSubnet = common2.isInSubnet; + this.isCorrect = common2.isCorrect(constants6.BITS); + if (optionalGroups === void 0) { + this.groups = constants6.GROUPS; + } else { + this.groups = optionalGroups; + } + this.address = address; + const subnet = constants6.RE_SUBNET_STRING.exec(address); + if (subnet) { + this.parsedSubnet = subnet[0].replace("/", ""); + this.subnetMask = parseInt(this.parsedSubnet, 10); + this.subnet = `/${this.subnetMask}`; + if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + address = address.replace(constants6.RE_SUBNET_STRING, ""); + } else if (/\//.test(address)) { + throw new address_error_1.AddressError("Invalid subnet mask."); + } + const zone = constants6.RE_ZONE_STRING.exec(address); + if (zone) { + this.zone = zone[0]; + address = address.replace(constants6.RE_ZONE_STRING, ""); + } + this.addressMinusSuffix = address; + this.parsedAddress = this.parse(this.addressMinusSuffix); + } + static isValid(address) { + try { + new Address6(address); + return true; + } catch (e) { + return false; + } + } + /** + * Convert a BigInteger to a v6 address object + * @memberof Address6 + * @static + * @param {BigInteger} bigInteger - a BigInteger to convert + * @returns {Address6} + * @example + * var bigInteger = new BigInteger('1000000000000'); + * var address = Address6.fromBigInteger(bigInteger); + * address.correctForm(); // '::e8:d4a5:1000' + */ + static fromBigInteger(bigInteger) { + const hex = bigInteger.toString(16).padStart(32, "0"); + const groups = []; + let i; + for (i = 0; i < constants6.GROUPS; i++) { + groups.push(hex.slice(i * 4, (i + 1) * 4)); + } + return new Address6(groups.join(":")); + } + /** + * Convert a URL (with optional port number) to an address object + * @memberof Address6 + * @static + * @param {string} url - a URL with optional port number + * @example + * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); + * addressAndPort.address.correctForm(); // 'ffff::' + * addressAndPort.port; // 8080 + */ + static fromURL(url2) { + let host; + let port = null; + let result; + if (url2.indexOf("[") !== -1 && url2.indexOf("]:") !== -1) { + result = constants6.RE_URL_WITH_PORT.exec(url2); + if (result === null) { + return { + error: "failed to parse address with port", + address: null, + port: null + }; + } + host = result[1]; + port = result[2]; + } else if (url2.indexOf("/") !== -1) { + url2 = url2.replace(/^[a-z0-9]+:\/\//, ""); + result = constants6.RE_URL.exec(url2); + if (result === null) { + return { + error: "failed to parse address from URL", + address: null, + port: null + }; + } + host = result[1]; + } else { + host = url2; + } + if (port) { + port = parseInt(port, 10); + if (port < 0 || port > 65536) { + port = null; + } + } else { + port = null; + } + return { + address: new Address6(host), + port + }; + } + /** + * Create an IPv6-mapped address given an IPv4 address + * @memberof Address6 + * @static + * @param {string} address - An IPv4 address string + * @returns {Address6} + * @example + * var address = Address6.fromAddress4('192.168.0.1'); + * address.correctForm(); // '::ffff:c0a8:1' + * address.to4in6(); // '::ffff:192.168.0.1' + */ + static fromAddress4(address) { + const address4 = new ipv4_1.Address4(address); + const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); + return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); + } + /** + * Return an address from ip6.arpa form + * @memberof Address6 + * @static + * @param {string} arpaFormAddress - an 'ip6.arpa' form address + * @returns {Adress6} + * @example + * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) + * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' + */ + static fromArpa(arpaFormAddress) { + let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ""); + const semicolonAmount = 7; + if (address.length !== 63) { + throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); + } + const parts = address.split(".").reverse(); + for (let i = semicolonAmount; i > 0; i--) { + const insertIndex = i * 4; + parts.splice(insertIndex, 0, ":"); + } + address = parts.join(""); + return new Address6(address); + } + /** + * Return the Microsoft UNC transcription of the address + * @memberof Address6 + * @instance + * @returns {String} the Microsoft UNC transcription of the address + */ + microsoftTranscription() { + return (0, sprintf_js_1.sprintf)("%s.ipv6-literal.net", this.correctForm().replace(/:/g, "-")); + } + /** + * Return the first n bits of the address, defaulting to the subnet mask + * @memberof Address6 + * @instance + * @param {number} [mask=subnet] - the number of bits to mask + * @returns {String} the first n bits of the address as a string + */ + mask(mask = this.subnetMask) { + return this.getBitsBase2(0, mask); + } + /** + * Return the number of possible subnets of a given size in the address + * @memberof Address6 + * @instance + * @param {number} [size=128] - the subnet size + * @returns {String} + */ + // TODO: probably useful to have a numeric version of this too + possibleSubnets(subnetSize = 128) { + const availableBits = constants6.BITS - this.subnetMask; + const subnetBits = Math.abs(subnetSize - constants6.BITS); + const subnetPowers = availableBits - subnetBits; + if (subnetPowers < 0) { + return "0"; + } + return addCommas(new jsbn_1.BigInteger("2", 10).pow(subnetPowers).toString(10)); + } + /** + * Helper function getting start address. + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + _startAddress() { + return new jsbn_1.BigInteger(this.mask() + "0".repeat(constants6.BITS - this.subnetMask), 2); + } + /** + * The first address in the range given by this address' subnet + * Often referred to as the Network Address. + * @memberof Address6 + * @instance + * @returns {Address6} + */ + startAddress() { + return Address6.fromBigInteger(this._startAddress()); + } + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + * @memberof Address6 + * @instance + * @returns {Address6} + */ + startAddressExclusive() { + const adjust = new jsbn_1.BigInteger("1"); + return Address6.fromBigInteger(this._startAddress().add(adjust)); + } + /** + * Helper function getting end address. + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + _endAddress() { + return new jsbn_1.BigInteger(this.mask() + "1".repeat(constants6.BITS - this.subnetMask), 2); + } + /** + * The last address in the range given by this address' subnet + * Often referred to as the Broadcast + * @memberof Address6 + * @instance + * @returns {Address6} + */ + endAddress() { + return Address6.fromBigInteger(this._endAddress()); + } + /** + * The last host address in the range given by this address's subnet ie + * the last address prior to the Broadcast Address + * @memberof Address6 + * @instance + * @returns {Address6} + */ + endAddressExclusive() { + const adjust = new jsbn_1.BigInteger("1"); + return Address6.fromBigInteger(this._endAddress().subtract(adjust)); + } + /** + * Return the scope of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + getScope() { + let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; + if (this.getType() === "Global unicast" && scope !== "Link local") { + scope = "Global"; + } + return scope || "Unknown"; + } + /** + * Return the type of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + getType() { + for (const subnet of Object.keys(constants6.TYPES)) { + if (this.isInSubnet(new Address6(subnet))) { + return constants6.TYPES[subnet]; + } + } + return "Global unicast"; + } + /** + * Return the bits in the given range as a BigInteger + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + getBits(start, end) { + return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); + } + /** + * Return the bits in the given range as a base-2 string + * @memberof Address6 + * @instance + * @returns {String} + */ + getBitsBase2(start, end) { + return this.binaryZeroPad().slice(start, end); + } + /** + * Return the bits in the given range as a base-16 string + * @memberof Address6 + * @instance + * @returns {String} + */ + getBitsBase16(start, end) { + const length = end - start; + if (length % 4 !== 0) { + throw new Error("Length of bits to retrieve must be divisible by four"); + } + return this.getBits(start, end).toString(16).padStart(length / 4, "0"); + } + /** + * Return the bits that are set past the subnet mask length + * @memberof Address6 + * @instance + * @returns {String} + */ + getBitsPastSubnet() { + return this.getBitsBase2(this.subnetMask, constants6.BITS); + } + /** + * Return the reversed ip6.arpa form of the address + * @memberof Address6 + * @param {Object} options + * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix + * @instance + * @returns {String} + */ + reverseForm(options2) { + if (!options2) { + options2 = {}; + } + const characters = Math.floor(this.subnetMask / 4); + const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join("."); + if (characters > 0) { + if (options2.omitSuffix) { + return reversed; + } + return (0, sprintf_js_1.sprintf)("%s.ip6.arpa.", reversed); + } + if (options2.omitSuffix) { + return ""; + } + return "ip6.arpa."; + } + /** + * Return the correct form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + correctForm() { + let i; + let groups = []; + let zeroCounter = 0; + const zeroes = []; + for (i = 0; i < this.parsedAddress.length; i++) { + const value = parseInt(this.parsedAddress[i], 16); + if (value === 0) { + zeroCounter++; + } + if (value !== 0 && zeroCounter > 0) { + if (zeroCounter > 1) { + zeroes.push([i - zeroCounter, i - 1]); + } + zeroCounter = 0; + } + } + if (zeroCounter > 1) { + zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); + } + const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); + if (zeroes.length > 0) { + const index2 = zeroLengths.indexOf(Math.max(...zeroLengths)); + groups = compact(this.parsedAddress, zeroes[index2]); + } else { + groups = this.parsedAddress; + } + for (i = 0; i < groups.length; i++) { + if (groups[i] !== "compact") { + groups[i] = parseInt(groups[i], 16).toString(16); + } + } + let correct = groups.join(":"); + correct = correct.replace(/^compact$/, "::"); + correct = correct.replace(/^compact|compact$/, ":"); + correct = correct.replace(/compact/, ""); + return correct; + } + /** + * Return a zero-padded base-2 string representation of the address + * @memberof Address6 + * @instance + * @returns {String} + * @example + * var address = new Address6('2001:4860:4001:803::1011'); + * address.binaryZeroPad(); + * // '0010000000000001010010000110000001000000000000010000100000000011 + * // 0000000000000000000000000000000000000000000000000001000000010001' + */ + binaryZeroPad() { + return this.bigInteger().toString(2).padStart(constants6.BITS, "0"); + } + // TODO: Improve the semantics of this helper function + parse4in6(address) { + const groups = address.split(":"); + const lastGroup = groups.slice(-1)[0]; + const address4 = lastGroup.match(constants4.RE_ADDRESS); + if (address4) { + this.parsedAddress4 = address4[0]; + this.address4 = new ipv4_1.Address4(this.parsedAddress4); + for (let i = 0; i < this.address4.groups; i++) { + if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { + throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join("."))); + } + } + this.v4 = true; + groups[groups.length - 1] = this.address4.toGroup6(); + address = groups.join(":"); + } + return address; + } + // TODO: Make private? + parse(address) { + address = this.parse4in6(address); + const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); + if (badCharacters) { + throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)("Bad character%s detected in address: %s", badCharacters.length > 1 ? "s" : "", badCharacters.join("")), address.replace(constants6.RE_BAD_CHARACTERS, '$1')); + } + const badAddress = address.match(constants6.RE_BAD_ADDRESS); + if (badAddress) { + throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)("Address failed regex: %s", badAddress.join("")), address.replace(constants6.RE_BAD_ADDRESS, '$1')); + } + let groups = []; + const halves = address.split("::"); + if (halves.length === 2) { + let first = halves[0].split(":"); + let last = halves[1].split(":"); + if (first.length === 1 && first[0] === "") { + first = []; + } + if (last.length === 1 && last[0] === "") { + last = []; + } + const remaining = this.groups - (first.length + last.length); + if (!remaining) { + throw new address_error_1.AddressError("Error parsing groups"); + } + this.elidedGroups = remaining; + this.elisionBegin = first.length; + this.elisionEnd = first.length + this.elidedGroups; + groups = groups.concat(first); + for (let i = 0; i < remaining; i++) { + groups.push("0"); + } + groups = groups.concat(last); + } else if (halves.length === 1) { + groups = address.split(":"); + this.elidedGroups = 0; + } else { + throw new address_error_1.AddressError("Too many :: groups found"); + } + groups = groups.map((group) => (0, sprintf_js_1.sprintf)("%x", parseInt(group, 16))); + if (groups.length !== this.groups) { + throw new address_error_1.AddressError("Incorrect number of groups found"); + } + return groups; + } + /** + * Return the canonical form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + canonicalForm() { + return this.parsedAddress.map(paddedHex).join(":"); + } + /** + * Return the decimal form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + decimal() { + return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)("%05d", parseInt(n, 16))).join(":"); + } + /** + * Return the address as a BigInteger + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + bigInteger() { + return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(""), 16); + } + /** + * Return the last two groups of this address as an IPv4 address string + * @memberof Address6 + * @instance + * @returns {Address4} + * @example + * var address = new Address6('2001:4860:4001::1825:bf11'); + * address.to4().correctForm(); // '24.37.191.17' + */ + to4() { + const binary2 = this.binaryZeroPad().split(""); + return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary2.slice(96, 128).join(""), 2).toString(16)); + } + /** + * Return the v4-in-v6 form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + to4in6() { + const address4 = this.to4(); + const address6 = new Address6(this.parsedAddress.slice(0, 6).join(":"), 6); + const correct = address6.correctForm(); + let infix = ""; + if (!/:$/.test(correct)) { + infix = ":"; + } + return correct + infix + address4.address; + } + /** + * Return an object containing the Teredo properties of the address + * @memberof Address6 + * @instance + * @returns {Object} + */ + inspectTeredo() { + const prefix = this.getBitsBase16(0, 32); + const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger("ffff", 16)).toString(); + const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); + const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger("ffffffff", 16)).toString(16)); + const flags = this.getBits(64, 80); + const flagsBase2 = this.getBitsBase2(64, 80); + const coneNat = flags.testBit(15); + const reserved = flags.testBit(14); + const groupIndividual = flags.testBit(8); + const universalLocal = flags.testBit(9); + const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10); + return { + prefix: (0, sprintf_js_1.sprintf)("%s:%s", prefix.slice(0, 4), prefix.slice(4, 8)), + server4: server4.address, + client4: client4.address, + flags: flagsBase2, + coneNat, + microsoft: { + reserved, + universalLocal, + groupIndividual, + nonce + }, + udpPort + }; + } + /** + * Return an object containing the 6to4 properties of the address + * @memberof Address6 + * @instance + * @returns {Object} + */ + inspect6to4() { + const prefix = this.getBitsBase16(0, 16); + const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); + return { + prefix: (0, sprintf_js_1.sprintf)("%s", prefix.slice(0, 4)), + gateway: gateway.address + }; + } + /** + * Return a v6 6to4 address from a v6 v4inv6 address + * @memberof Address6 + * @instance + * @returns {Address6} + */ + to6to4() { + if (!this.is4()) { + return null; + } + const addr6to4 = [ + "2002", + this.getBitsBase16(96, 112), + this.getBitsBase16(112, 128), + "", + "/16" + ].join(":"); + return new Address6(addr6to4); + } + /** + * Return a byte array + * @memberof Address6 + * @instance + * @returns {Array} + */ + toByteArray() { + const byteArray = this.bigInteger().toByteArray(); + if (byteArray.length === 17 && byteArray[0] === 0) { + return byteArray.slice(1); + } + return byteArray; + } + /** + * Return an unsigned byte array + * @memberof Address6 + * @instance + * @returns {Array} + */ + toUnsignedByteArray() { + return this.toByteArray().map(unsignByte); + } + /** + * Convert a byte array to an Address6 object + * @memberof Address6 + * @static + * @returns {Address6} + */ + static fromByteArray(bytes) { + return this.fromUnsignedByteArray(bytes.map(unsignByte)); + } + /** + * Convert an unsigned byte array to an Address6 object + * @memberof Address6 + * @static + * @returns {Address6} + */ + static fromUnsignedByteArray(bytes) { + const BYTE_MAX = new jsbn_1.BigInteger("256", 10); + let result = new jsbn_1.BigInteger("0", 10); + let multiplier = new jsbn_1.BigInteger("1", 10); + for (let i = bytes.length - 1; i >= 0; i--) { + result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10))); + multiplier = multiplier.multiply(BYTE_MAX); + } + return Address6.fromBigInteger(result); + } + /** + * Returns true if the address is in the canonical form, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isCanonical() { + return this.addressMinusSuffix === this.canonicalForm(); + } + /** + * Returns true if the address is a link local address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isLinkLocal() { + if (this.getBitsBase2(0, 64) === "1111111010000000000000000000000000000000000000000000000000000000") { + return true; + } + return false; + } + /** + * Returns true if the address is a multicast address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isMulticast() { + return this.getType() === "Multicast"; + } + /** + * Returns true if the address is a v4-in-v6 address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + is4() { + return this.v4; + } + /** + * Returns true if the address is a Teredo address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isTeredo() { + return this.isInSubnet(new Address6("2001::/32")); + } + /** + * Returns true if the address is a 6to4 address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + is6to4() { + return this.isInSubnet(new Address6("2002::/16")); + } + /** + * Returns true if the address is a loopback address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isLoopback() { + return this.getType() === "Loopback"; + } + // #endregion + // #region HTML + /** + * @returns {String} the address in link form with a default port of 80 + */ + href(optionalPort) { + if (optionalPort === void 0) { + optionalPort = ""; + } else { + optionalPort = (0, sprintf_js_1.sprintf)(":%s", optionalPort); + } + return (0, sprintf_js_1.sprintf)("http://[%s]%s/", this.correctForm(), optionalPort); + } + /** + * @returns {String} a link suitable for conveying the address via a URL hash + */ + link(options2) { + if (!options2) { + options2 = {}; + } + if (options2.className === void 0) { + options2.className = ""; + } + if (options2.prefix === void 0) { + options2.prefix = "/#address="; + } + if (options2.v4 === void 0) { + options2.v4 = false; + } + let formFunction = this.correctForm; + if (options2.v4) { + formFunction = this.to4in6; + } + if (options2.className) { + return (0, sprintf_js_1.sprintf)('%2$s', options2.prefix, formFunction.call(this), options2.className); + } + return (0, sprintf_js_1.sprintf)('%2$s', options2.prefix, formFunction.call(this)); + } + /** + * Groups an address + * @returns {String} + */ + group() { + if (this.elidedGroups === 0) { + return helpers2.simpleGroup(this.address).join(":"); + } + assert2(typeof this.elidedGroups === "number"); + assert2(typeof this.elisionBegin === "number"); + const output = []; + const [left, right] = this.address.split("::"); + if (left.length) { + output.push(...helpers2.simpleGroup(left)); + } else { + output.push(""); + } + const classes = ["hover-group"]; + for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { + classes.push((0, sprintf_js_1.sprintf)("group-%d", i)); + } + output.push((0, sprintf_js_1.sprintf)('', classes.join(" "))); + if (right.length) { + output.push(...helpers2.simpleGroup(right, this.elisionEnd)); + } else { + output.push(""); + } + if (this.is4()) { + assert2(this.address4 instanceof ipv4_1.Address4); + output.pop(); + output.push(this.address4.groupForV6()); + } + return output.join(":"); + } + // #endregion + // #region Regular expressions + /** + * Generate a regular expression string that can be used to find or validate + * all variations of this address + * @memberof Address6 + * @instance + * @param {boolean} substringSearch + * @returns {string} + */ + regularExpressionString(substringSearch = false) { + let output = []; + const address6 = new Address6(this.correctForm()); + if (address6.elidedGroups === 0) { + output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + } else if (address6.elidedGroups === constants6.GROUPS) { + output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + } else { + const halves = address6.address.split("::"); + if (halves[0].length) { + output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); + } + assert2(typeof address6.elidedGroups === "number"); + output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + if (halves[1].length) { + output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); + } + output = [output.join(":")]; + } + if (!substringSearch) { + output = [ + "(?=^|", + regular_expressions_1.ADDRESS_BOUNDARY, + "|[^\\w\\:])(", + ...output, + ")(?=[^\\w\\:]|", + regular_expressions_1.ADDRESS_BOUNDARY, + "|$)" + ]; + } + return output.join(""); + } + /** + * Generate a regular expression that can be used to find or validate all + * variations of this address. + * @memberof Address6 + * @instance + * @param {boolean} substringSearch + * @returns {RegExp} + */ + regularExpression(substringSearch = false) { + return new RegExp(this.regularExpressionString(substringSearch), "i"); + } + } + ipv6.Address6 = Address6; + return ipv6; +} +var hasRequiredIpAddress; +function requireIpAddress() { + if (hasRequiredIpAddress) return ipAddress; + hasRequiredIpAddress = 1; + (function(exports) { + var __createBinding = ipAddress && ipAddress.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = ipAddress && ipAddress.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = ipAddress && ipAddress.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; + const ipv4_1 = requireIpv4(); + Object.defineProperty(exports, "Address4", { enumerable: true, get: function() { + return ipv4_1.Address4; + } }); + const ipv6_1 = requireIpv6(); + Object.defineProperty(exports, "Address6", { enumerable: true, get: function() { + return ipv6_1.Address6; + } }); + const address_error_1 = requireAddressError(); + Object.defineProperty(exports, "AddressError", { enumerable: true, get: function() { + return address_error_1.AddressError; + } }); + const helpers2 = __importStar(requireHelpers$1()); + exports.v6 = { helpers: helpers2 }; + })(ipAddress); + return ipAddress; +} +var hasRequiredHelpers; +function requireHelpers() { + if (hasRequiredHelpers) return helpers$1; + hasRequiredHelpers = 1; + Object.defineProperty(helpers$1, "__esModule", { value: true }); + helpers$1.ipToBuffer = helpers$1.int32ToIpv4 = helpers$1.ipv4ToInt32 = helpers$1.validateSocksClientChainOptions = helpers$1.validateSocksClientOptions = void 0; + const util_1 = requireUtil(); + const constants_1 = requireConstants$2(); + const stream2 = requireBrowser$h(); + const ip_address_1 = requireIpAddress(); + const net2 = require$$1$2; + function validateSocksClientOptions(options2, acceptedCommands = ["connect", "bind", "associate"]) { + if (!constants_1.SocksCommand[options2.command]) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options2); + } + if (acceptedCommands.indexOf(options2.command) === -1) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options2); + } + if (!isValidSocksRemoteHost(options2.destination)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options2); + } + if (!isValidSocksProxy(options2.proxy)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options2); + } + validateCustomProxyAuth(options2.proxy, options2); + if (options2.timeout && !isValidTimeoutValue(options2.timeout)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options2); + } + if (options2.existing_socket && !(options2.existing_socket instanceof stream2.Duplex)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options2); + } + } + helpers$1.validateSocksClientOptions = validateSocksClientOptions; + function validateSocksClientChainOptions(options2) { + if (options2.command !== "connect") { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options2); + } + if (!isValidSocksRemoteHost(options2.destination)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options2); + } + if (!(options2.proxies && Array.isArray(options2.proxies) && options2.proxies.length >= 2)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options2); + } + options2.proxies.forEach((proxy) => { + if (!isValidSocksProxy(proxy)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options2); + } + validateCustomProxyAuth(proxy, options2); + }); + if (options2.timeout && !isValidTimeoutValue(options2.timeout)) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options2); + } + } + helpers$1.validateSocksClientChainOptions = validateSocksClientChainOptions; + function validateCustomProxyAuth(proxy, options2) { + if (proxy.custom_auth_method !== void 0) { + if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options2); + } + if (proxy.custom_auth_request_handler === void 0 || typeof proxy.custom_auth_request_handler !== "function") { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options2); + } + if (proxy.custom_auth_response_size === void 0) { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options2); + } + if (proxy.custom_auth_response_handler === void 0 || typeof proxy.custom_auth_response_handler !== "function") { + throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options2); + } + } + } + function isValidSocksRemoteHost(remoteHost) { + return remoteHost && typeof remoteHost.host === "string" && typeof remoteHost.port === "number" && remoteHost.port >= 0 && remoteHost.port <= 65535; + } + function isValidSocksProxy(proxy) { + return proxy && (typeof proxy.host === "string" || typeof proxy.ipaddress === "string") && typeof proxy.port === "number" && proxy.port >= 0 && proxy.port <= 65535 && (proxy.type === 4 || proxy.type === 5); + } + function isValidTimeoutValue(value) { + return typeof value === "number" && value > 0; + } + function ipv4ToInt32(ip) { + const address = new ip_address_1.Address4(ip); + return address.toArray().reduce((acc, part) => (acc << 8) + part, 0); + } + helpers$1.ipv4ToInt32 = ipv4ToInt32; + function int32ToIpv4(int32) { + const octet1 = int32 >>> 24 & 255; + const octet2 = int32 >>> 16 & 255; + const octet3 = int32 >>> 8 & 255; + const octet4 = int32 & 255; + return [octet1, octet2, octet3, octet4].join("."); + } + helpers$1.int32ToIpv4 = int32ToIpv4; + function ipToBuffer(ip) { + if (net2.isIPv4(ip)) { + const address = new ip_address_1.Address4(ip); + return Buffer.from(address.toArray()); + } else if (net2.isIPv6(ip)) { + const address = new ip_address_1.Address6(ip); + return Buffer.from(address.canonicalForm().split(":").map((segment) => segment.padStart(4, "0")).join(""), "hex"); + } else { + throw new Error("Invalid IP address format"); + } + } + helpers$1.ipToBuffer = ipToBuffer; + return helpers$1; +} +var receivebuffer = {}; +var hasRequiredReceivebuffer; +function requireReceivebuffer() { + if (hasRequiredReceivebuffer) return receivebuffer; + hasRequiredReceivebuffer = 1; + Object.defineProperty(receivebuffer, "__esModule", { value: true }); + receivebuffer.ReceiveBuffer = void 0; + class ReceiveBuffer { + constructor(size = 4096) { + this.buffer = Buffer.allocUnsafe(size); + this.offset = 0; + this.originalSize = size; + } + get length() { + return this.offset; + } + append(data2) { + if (!Buffer.isBuffer(data2)) { + throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer."); + } + if (this.offset + data2.length >= this.buffer.length) { + const tmp = this.buffer; + this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data2.length)); + tmp.copy(this.buffer); + } + data2.copy(this.buffer, this.offset); + return this.offset += data2.length; + } + peek(length) { + if (length > this.offset) { + throw new Error("Attempted to read beyond the bounds of the managed internal data."); + } + return this.buffer.slice(0, length); + } + get(length) { + if (length > this.offset) { + throw new Error("Attempted to read beyond the bounds of the managed internal data."); + } + const value = Buffer.allocUnsafe(length); + this.buffer.slice(0, length).copy(value); + this.buffer.copyWithin(0, length, length + this.offset - length); + this.offset -= length; + return value; + } + } + receivebuffer.ReceiveBuffer = ReceiveBuffer; + return receivebuffer; +} +var hasRequiredSocksclient; +function requireSocksclient() { + if (hasRequiredSocksclient) return socksclient; + hasRequiredSocksclient = 1; + (function(exports) { + var __awaiter = socksclient && socksclient.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SocksClientError = exports.SocksClient = void 0; + const events_1 = requireEvents(); + const net2 = require$$1$2; + const smart_buffer_1 = requireSmartbuffer(); + const constants_1 = requireConstants$2(); + const helpers_1 = requireHelpers(); + const receivebuffer_1 = requireReceivebuffer(); + const util_1 = requireUtil(); + Object.defineProperty(exports, "SocksClientError", { enumerable: true, get: function() { + return util_1.SocksClientError; + } }); + const ip_address_1 = requireIpAddress(); + class SocksClient extends events_1.EventEmitter { + constructor(options2) { + super(); + this.options = Object.assign({}, options2); + (0, helpers_1.validateSocksClientOptions)(options2); + this.setState(constants_1.SocksClientState.Created); + } + /** + * Creates a new SOCKS connection. + * + * Note: Supports callbacks and promises. Only supports the connect command. + * @param options { SocksClientOptions } Options. + * @param callback { Function } An optional callback function. + * @returns { Promise } + */ + static createConnection(options2, callback) { + return new Promise((resolve, reject) => { + try { + (0, helpers_1.validateSocksClientOptions)(options2, ["connect"]); + } catch (err) { + if (typeof callback === "function") { + callback(err); + return resolve(err); + } else { + return reject(err); + } + } + const client = new SocksClient(options2); + client.connect(options2.existing_socket); + client.once("established", (info) => { + client.removeAllListeners(); + if (typeof callback === "function") { + callback(null, info); + resolve(info); + } else { + resolve(info); + } + }); + client.once("error", (err) => { + client.removeAllListeners(); + if (typeof callback === "function") { + callback(err); + resolve(err); + } else { + reject(err); + } + }); + }); + } + /** + * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. + * + * Note: Supports callbacks and promises. Only supports the connect method. + * Note: Implemented via createConnection() factory function. + * @param options { SocksClientChainOptions } Options + * @param callback { Function } An optional callback function. + * @returns { Promise } + */ + static createConnectionChain(options2, callback) { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + try { + (0, helpers_1.validateSocksClientChainOptions)(options2); + } catch (err) { + if (typeof callback === "function") { + callback(err); + return resolve(err); + } else { + return reject(err); + } + } + if (options2.randomizeChain) { + (0, util_1.shuffleArray)(options2.proxies); + } + try { + let sock; + for (let i = 0; i < options2.proxies.length; i++) { + const nextProxy = options2.proxies[i]; + const nextDestination = i === options2.proxies.length - 1 ? options2.destination : { + host: options2.proxies[i + 1].host || options2.proxies[i + 1].ipaddress, + port: options2.proxies[i + 1].port + }; + const result = yield SocksClient.createConnection({ + command: "connect", + proxy: nextProxy, + destination: nextDestination, + existing_socket: sock + }); + sock = sock || result.socket; + } + if (typeof callback === "function") { + callback(null, { socket: sock }); + resolve({ socket: sock }); + } else { + resolve({ socket: sock }); + } + } catch (err) { + if (typeof callback === "function") { + callback(err); + resolve(err); + } else { + reject(err); + } + } + })); + } + /** + * Creates a SOCKS UDP Frame. + * @param options + */ + static createUDPFrame(options2) { + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt16BE(0); + buff.writeUInt8(options2.frameNumber || 0); + if (net2.isIPv4(options2.remoteHost.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv4); + buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options2.remoteHost.host)); + } else if (net2.isIPv6(options2.remoteHost.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv6); + buff.writeBuffer((0, helpers_1.ipToBuffer)(options2.remoteHost.host)); + } else { + buff.writeUInt8(constants_1.Socks5HostType.Hostname); + buff.writeUInt8(Buffer.byteLength(options2.remoteHost.host)); + buff.writeString(options2.remoteHost.host); + } + buff.writeUInt16BE(options2.remoteHost.port); + buff.writeBuffer(options2.data); + return buff.toBuffer(); + } + /** + * Parses a SOCKS UDP frame. + * @param data + */ + static parseUDPFrame(data2) { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data2); + buff.readOffset = 2; + const frameNumber = buff.readUInt8(); + const hostType = buff.readUInt8(); + let remoteHost; + if (hostType === constants_1.Socks5HostType.IPv4) { + remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()); + } else if (hostType === constants_1.Socks5HostType.IPv6) { + remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(); + } else { + remoteHost = buff.readString(buff.readUInt8()); + } + const remotePort = buff.readUInt16BE(); + return { + frameNumber, + remoteHost: { + host: remoteHost, + port: remotePort + }, + data: buff.readBuffer() + }; + } + /** + * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. + */ + setState(newState) { + if (this.state !== constants_1.SocksClientState.Error) { + this.state = newState; + } + } + /** + * Starts the connection establishment to the proxy and destination. + * @param existingSocket Connected socket to use instead of creating a new one (internal use). + */ + connect(existingSocket) { + this.onDataReceived = (data2) => this.onDataReceivedHandler(data2); + this.onClose = () => this.onCloseHandler(); + this.onError = (err) => this.onErrorHandler(err); + this.onConnect = () => this.onConnectHandler(); + const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT); + if (timer.unref && typeof timer.unref === "function") { + timer.unref(); + } + if (existingSocket) { + this.socket = existingSocket; + } else { + this.socket = new net2.Socket(); + } + this.socket.once("close", this.onClose); + this.socket.once("error", this.onError); + this.socket.once("connect", this.onConnect); + this.socket.on("data", this.onDataReceived); + this.setState(constants_1.SocksClientState.Connecting); + this.receiveBuffer = new receivebuffer_1.ReceiveBuffer(); + if (existingSocket) { + this.socket.emit("connect"); + } else { + this.socket.connect(this.getSocketOptions()); + if (this.options.set_tcp_nodelay !== void 0 && this.options.set_tcp_nodelay !== null) { + this.socket.setNoDelay(!!this.options.set_tcp_nodelay); + } + } + this.prependOnceListener("established", (info) => { + setImmediate(() => { + if (this.receiveBuffer.length > 0) { + const excessData = this.receiveBuffer.get(this.receiveBuffer.length); + info.socket.emit("data", excessData); + } + info.socket.resume(); + }); + }); + } + // Socket options (defaults host/port to options.proxy.host/options.proxy.port) + getSocketOptions() { + return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port }); + } + /** + * Handles internal Socks timeout callback. + * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. + */ + onEstablishedTimeout() { + if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { + this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); + } + } + /** + * Handles Socket connect event. + */ + onConnectHandler() { + this.setState(constants_1.SocksClientState.Connected); + if (this.options.proxy.type === 4) { + this.sendSocks4InitialHandshake(); + } else { + this.sendSocks5InitialHandshake(); + } + this.setState(constants_1.SocksClientState.SentInitialHandshake); + } + /** + * Handles Socket data event. + * @param data + */ + onDataReceivedHandler(data2) { + this.receiveBuffer.append(data2); + this.processData(); + } + /** + * Handles processing of the data we have received. + */ + processData() { + while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) { + if (this.state === constants_1.SocksClientState.SentInitialHandshake) { + if (this.options.proxy.type === 4) { + this.handleSocks4FinalHandshakeResponse(); + } else { + this.handleInitialSocks5HandshakeResponse(); + } + } else if (this.state === constants_1.SocksClientState.SentAuthentication) { + this.handleInitialSocks5AuthenticationHandshakeResponse(); + } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { + this.handleSocks5FinalHandshakeResponse(); + } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { + if (this.options.proxy.type === 4) { + this.handleSocks4IncomingConnectionResponse(); + } else { + this.handleSocks5IncomingConnectionResponse(); + } + } else { + this.closeSocket(constants_1.ERRORS.InternalError); + break; + } + } + } + /** + * Handles Socket close event. + * @param had_error + */ + onCloseHandler() { + this.closeSocket(constants_1.ERRORS.SocketClosed); + } + /** + * Handles Socket error event. + * @param err + */ + onErrorHandler(err) { + this.closeSocket(err.message); + } + /** + * Removes internal event listeners on the underlying Socket. + */ + removeInternalSocketHandlers() { + this.socket.pause(); + this.socket.removeListener("data", this.onDataReceived); + this.socket.removeListener("close", this.onClose); + this.socket.removeListener("error", this.onError); + this.socket.removeListener("connect", this.onConnect); + } + /** + * Closes and destroys the underlying Socket. Emits an error event. + * @param err { String } An error string to include in error event. + */ + closeSocket(err) { + if (this.state !== constants_1.SocksClientState.Error) { + this.setState(constants_1.SocksClientState.Error); + this.socket.destroy(); + this.removeInternalSocketHandlers(); + this.emit("error", new util_1.SocksClientError(err, this.options)); + } + } + /** + * Sends initial Socks v4 handshake request. + */ + sendSocks4InitialHandshake() { + const userId = this.options.proxy.userId || ""; + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(4); + buff.writeUInt8(constants_1.SocksCommand[this.options.command]); + buff.writeUInt16BE(this.options.destination.port); + if (net2.isIPv4(this.options.destination.host)) { + buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); + buff.writeStringNT(userId); + } else { + buff.writeUInt8(0); + buff.writeUInt8(0); + buff.writeUInt8(0); + buff.writeUInt8(1); + buff.writeStringNT(userId); + buff.writeStringNT(this.options.destination.host); + } + this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response; + this.socket.write(buff.toBuffer()); + } + /** + * Handles Socks v4 handshake response. + * @param data + */ + handleSocks4FinalHandshakeResponse() { + const data2 = this.receiveBuffer.get(8); + if (data2[1] !== constants_1.Socks4Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data2[1]]})`); + } else { + if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data2); + buff.readOffset = 2; + const remoteHost = { + port: buff.readUInt16BE(), + host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()) + }; + if (remoteHost.host === "0.0.0.0") { + remoteHost.host = this.options.proxy.ipaddress; + } + this.setState(constants_1.SocksClientState.BoundWaitingForConnection); + this.emit("bound", { remoteHost, socket: this.socket }); + } else { + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit("established", { socket: this.socket }); + } + } + } + /** + * Handles Socks v4 incoming connection request (BIND) + * @param data + */ + handleSocks4IncomingConnectionResponse() { + const data2 = this.receiveBuffer.get(8); + if (data2[1] !== constants_1.Socks4Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data2[1]]})`); + } else { + const buff = smart_buffer_1.SmartBuffer.fromBuffer(data2); + buff.readOffset = 2; + const remoteHost = { + port: buff.readUInt16BE(), + host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()) + }; + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit("established", { remoteHost, socket: this.socket }); + } + } + /** + * Sends initial Socks v5 handshake request. + */ + sendSocks5InitialHandshake() { + const buff = new smart_buffer_1.SmartBuffer(); + const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth]; + if (this.options.proxy.userId || this.options.proxy.password) { + supportedAuthMethods.push(constants_1.Socks5Auth.UserPass); + } + if (this.options.proxy.custom_auth_method !== void 0) { + supportedAuthMethods.push(this.options.proxy.custom_auth_method); + } + buff.writeUInt8(5); + buff.writeUInt8(supportedAuthMethods.length); + for (const authMethod of supportedAuthMethods) { + buff.writeUInt8(authMethod); + } + this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse; + this.socket.write(buff.toBuffer()); + this.setState(constants_1.SocksClientState.SentInitialHandshake); + } + /** + * Handles initial Socks v5 handshake response. + * @param data + */ + handleInitialSocks5HandshakeResponse() { + const data2 = this.receiveBuffer.get(2); + if (data2[0] !== 5) { + this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion); + } else if (data2[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) { + this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType); + } else { + if (data2[1] === constants_1.Socks5Auth.NoAuth) { + this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth; + this.sendSocks5CommandRequest(); + } else if (data2[1] === constants_1.Socks5Auth.UserPass) { + this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass; + this.sendSocks5UserPassAuthentication(); + } else if (data2[1] === this.options.proxy.custom_auth_method) { + this.socks5ChosenAuthType = this.options.proxy.custom_auth_method; + this.sendSocks5CustomAuthentication(); + } else { + this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType); + } + } + } + /** + * Sends Socks v5 user & password auth handshake. + * + * Note: No auth and user/pass are currently supported. + */ + sendSocks5UserPassAuthentication() { + const userId = this.options.proxy.userId || ""; + const password = this.options.proxy.password || ""; + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(1); + buff.writeUInt8(Buffer.byteLength(userId)); + buff.writeString(userId); + buff.writeUInt8(Buffer.byteLength(password)); + buff.writeString(password); + this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; + this.socket.write(buff.toBuffer()); + this.setState(constants_1.SocksClientState.SentAuthentication); + } + sendSocks5CustomAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size; + this.socket.write(yield this.options.proxy.custom_auth_request_handler()); + this.setState(constants_1.SocksClientState.SentAuthentication); + }); + } + handleSocks5CustomAuthHandshakeResponse(data2) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.options.proxy.custom_auth_response_handler(data2); + }); + } + handleSocks5AuthenticationNoAuthHandshakeResponse(data2) { + return __awaiter(this, void 0, void 0, function* () { + return data2[1] === 0; + }); + } + handleSocks5AuthenticationUserPassHandshakeResponse(data2) { + return __awaiter(this, void 0, void 0, function* () { + return data2[1] === 0; + }); + } + /** + * Handles Socks v5 auth handshake response. + * @param data + */ + handleInitialSocks5AuthenticationHandshakeResponse() { + return __awaiter(this, void 0, void 0, function* () { + this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse); + let authResult = false; + if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) { + authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)); + } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) { + authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)); + } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) { + authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size)); + } + if (!authResult) { + this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); + } else { + this.sendSocks5CommandRequest(); + } + }); + } + /** + * Sends Socks v5 final handshake request. + */ + sendSocks5CommandRequest() { + const buff = new smart_buffer_1.SmartBuffer(); + buff.writeUInt8(5); + buff.writeUInt8(constants_1.SocksCommand[this.options.command]); + buff.writeUInt8(0); + if (net2.isIPv4(this.options.destination.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv4); + buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); + } else if (net2.isIPv6(this.options.destination.host)) { + buff.writeUInt8(constants_1.Socks5HostType.IPv6); + buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); + } else { + buff.writeUInt8(constants_1.Socks5HostType.Hostname); + buff.writeUInt8(this.options.destination.host.length); + buff.writeString(this.options.destination.host); + } + buff.writeUInt16BE(this.options.destination.port); + this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; + this.socket.write(buff.toBuffer()); + this.setState(constants_1.SocksClientState.SentFinalHandshake); + } + /** + * Handles Socks v5 final handshake response. + * @param data + */ + handleSocks5FinalHandshakeResponse() { + const header = this.receiveBuffer.peek(5); + if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); + } else { + const addressType = header[3]; + let remoteHost; + let buff; + if (addressType === constants_1.Socks5HostType.IPv4) { + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), + port: buff.readUInt16BE() + }; + if (remoteHost.host === "0.0.0.0") { + remoteHost.host = this.options.proxy.ipaddress; + } + } else if (addressType === constants_1.Socks5HostType.Hostname) { + const hostLength = header[4]; + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); + remoteHost = { + host: buff.readString(hostLength), + port: buff.readUInt16BE() + }; + } else if (addressType === constants_1.Socks5HostType.IPv6) { + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), + port: buff.readUInt16BE() + }; + } + this.setState(constants_1.SocksClientState.ReceivedFinalResponse); + if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) { + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit("established", { remoteHost, socket: this.socket }); + } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { + this.setState(constants_1.SocksClientState.BoundWaitingForConnection); + this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; + this.emit("bound", { remoteHost, socket: this.socket }); + } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) { + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit("established", { + remoteHost, + socket: this.socket + }); + } + } + } + /** + * Handles Socks v5 incoming connection request (BIND). + */ + handleSocks5IncomingConnectionResponse() { + const header = this.receiveBuffer.peek(5); + if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) { + this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); + } else { + const addressType = header[3]; + let remoteHost; + let buff; + if (addressType === constants_1.Socks5HostType.IPv4) { + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), + port: buff.readUInt16BE() + }; + if (remoteHost.host === "0.0.0.0") { + remoteHost.host = this.options.proxy.ipaddress; + } + } else if (addressType === constants_1.Socks5HostType.Hostname) { + const hostLength = header[4]; + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); + remoteHost = { + host: buff.readString(hostLength), + port: buff.readUInt16BE() + }; + } else if (addressType === constants_1.Socks5HostType.IPv6) { + const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; + if (this.receiveBuffer.length < dataNeeded) { + this.nextRequiredPacketBufferSize = dataNeeded; + return; + } + buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); + remoteHost = { + host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), + port: buff.readUInt16BE() + }; + } + this.setState(constants_1.SocksClientState.Established); + this.removeInternalSocketHandlers(); + this.emit("established", { remoteHost, socket: this.socket }); + } + } + get socksClientOptions() { + return Object.assign({}, this.options); + } + } + exports.SocksClient = SocksClient; + })(socksclient); + return socksclient; +} +var hasRequiredBuild; +function requireBuild() { + if (hasRequiredBuild) return build; + hasRequiredBuild = 1; + (function(exports) { + var __createBinding = build && build.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __exportStar = build && build.__exportStar || function(m, exports2) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(requireSocksclient(), exports); + })(build); + return build; +} +var hasRequiredAgent; +function requireAgent() { + if (hasRequiredAgent) return agent; + hasRequiredAgent = 1; + var __awaiter = agent && agent.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault = agent && agent.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(agent, "__esModule", { value: true }); + const dns_1 = __importDefault(require$$0$3); + const tls_1 = __importDefault(require$$1$1); + const url_1 = __importDefault(require$$1$5); + const debug_1 = __importDefault(requireBrowser$f()); + const agent_base_1 = requireSrc(); + const socks_1 = requireBuild(); + const debug2 = debug_1.default("socks-proxy-agent"); + function dnsLookup(host) { + return new Promise((resolve, reject) => { + dns_1.default.lookup(host, (err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + } + function parseSocksProxy(opts) { + let port = 0; + let lookup = false; + let type2 = 5; + const host = opts.hostname || opts.host; + if (!host) { + throw new TypeError('No "host"'); + } + if (typeof opts.port === "number") { + port = opts.port; + } else if (typeof opts.port === "string") { + port = parseInt(opts.port, 10); + } + if (!port) { + port = 1080; + } + if (opts.protocol) { + switch (opts.protocol.replace(":", "")) { + case "socks4": + lookup = true; + // pass through + case "socks4a": + type2 = 4; + break; + case "socks5": + lookup = true; + // pass through + case "socks": + // no version specified, default to 5h + case "socks5h": + type2 = 5; + break; + default: + throw new TypeError(`A "socks" protocol must be specified! Got: ${opts.protocol}`); + } + } + if (typeof opts.type !== "undefined") { + if (opts.type === 4 || opts.type === 5) { + type2 = opts.type; + } else { + throw new TypeError(`"type" must be 4 or 5, got: ${opts.type}`); + } + } + const proxy = { + host, + port, + type: type2 + }; + let userId = opts.userId || opts.username; + let password = opts.password; + if (opts.auth) { + const auth = opts.auth.split(":"); + userId = auth[0]; + password = auth[1]; + } + if (userId) { + Object.defineProperty(proxy, "userId", { + value: userId, + enumerable: false + }); + } + if (password) { + Object.defineProperty(proxy, "password", { + value: password, + enumerable: false + }); + } + return { lookup, proxy }; + } + class SocksProxyAgent2 extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === "string") { + opts = url_1.default.parse(_opts); + } else { + opts = _opts; + } + if (!opts) { + throw new TypeError("a SOCKS proxy server `host` and `port` must be specified!"); + } + super(opts); + const parsedProxy = parseSocksProxy(opts); + this.lookup = parsedProxy.lookup; + this.proxy = parsedProxy.proxy; + this.tlsConnectionOptions = opts.tls || {}; + } + /** + * Initiates a SOCKS connection to the specified SOCKS proxy server, + * which in turn connects to the specified remote host and port. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { lookup, proxy } = this; + let { host, port, timeout } = opts; + if (!host) { + throw new Error("No `host` defined!"); + } + if (lookup) { + host = yield dnsLookup(host); + } + const socksOpts = { + proxy, + destination: { host, port }, + command: "connect", + timeout + }; + debug2("Creating socks proxy connection: %o", socksOpts); + const { socket } = yield socks_1.SocksClient.createConnection(socksOpts); + debug2("Successfully created socks proxy connection"); + if (opts.secureEndpoint) { + debug2("Upgrading socket connection to TLS"); + const servername = opts.servername || opts.host; + return tls_1.default.connect(Object.assign(Object.assign(Object.assign({}, omit(opts, "host", "hostname", "path", "port")), { + socket, + servername + }), this.tlsConnectionOptions)); + } + return socket; + }); + } + } + agent.default = SocksProxyAgent2; + function omit(obj, ...keys) { + const ret = {}; + let key2; + for (key2 in obj) { + if (!keys.includes(key2)) { + ret[key2] = obj[key2]; + } + } + return ret; + } + return agent; +} +var dist; +var hasRequiredDist; +function requireDist() { + if (hasRequiredDist) return dist; + hasRequiredDist = 1; + var __importDefault = dist && dist.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + const agent_1 = __importDefault(requireAgent()); + function createSocksProxyAgent(opts) { + return new agent_1.default(opts); + } + (function(createSocksProxyAgent2) { + createSocksProxyAgent2.SocksProxyAgent = agent_1.default; + createSocksProxyAgent2.prototype = agent_1.default.prototype; + })(createSocksProxyAgent || (createSocksProxyAgent = {})); + dist = createSocksProxyAgent; + return dist; +} +var distExports = requireDist(); +const ALIAS = Symbol.for("yaml.alias"); +const DOC = Symbol.for("yaml.document"); +const MAP = Symbol.for("yaml.map"); +const PAIR = Symbol.for("yaml.pair"); +const SCALAR$1 = Symbol.for("yaml.scalar"); +const SEQ = Symbol.for("yaml.seq"); +const NODE_TYPE = Symbol.for("yaml.node.type"); +const isAlias = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === ALIAS; +const isDocument = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === DOC; +const isMap = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === MAP; +const isPair = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === PAIR; +const isScalar$1 = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SCALAR$1; +const isSeq = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SEQ; +function isCollection$1(node2) { + if (node2 && typeof node2 === "object") + switch (node2[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node2) { + if (node2 && typeof node2 === "object") + switch (node2[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR$1: + case SEQ: + return true; + } + return false; +} +const hasAnchor = (node2) => (isScalar$1(node2) || isCollection$1(node2)) && !!node2.anchor; +const BREAK$1 = Symbol("break visit"); +const SKIP$1 = Symbol("skip children"); +const REMOVE$1 = Symbol("remove node"); +function visit$1(node2, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node2)) { + const cd = visit_(null, node2.contents, visitor_, Object.freeze([node2])); + if (cd === REMOVE$1) + node2.contents = null; + } else + visit_(null, node2, visitor_, Object.freeze([])); +} +visit$1.BREAK = BREAK$1; +visit$1.SKIP = SKIP$1; +visit$1.REMOVE = REMOVE$1; +function visit_(key2, node2, visitor, path2) { + const ctrl = callVisitor(key2, node2, visitor, path2); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key2, path2, ctrl); + return visit_(key2, ctrl, visitor, path2); + } + if (typeof ctrl !== "symbol") { + if (isCollection$1(node2)) { + path2 = Object.freeze(path2.concat(node2)); + for (let i = 0; i < node2.items.length; ++i) { + const ci = visit_(i, node2.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node2.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node2)) { + path2 = Object.freeze(path2.concat(node2)); + const ck = visit_("key", node2.key, visitor, path2); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node2.key = null; + const cv = visit_("value", node2.value, visitor, path2); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node2.value = null; + } + } + return ctrl; +} +async function visitAsync(node2, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node2)) { + const cd = await visitAsync_(null, node2.contents, visitor_, Object.freeze([node2])); + if (cd === REMOVE$1) + node2.contents = null; + } else + await visitAsync_(null, node2, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK$1; +visitAsync.SKIP = SKIP$1; +visitAsync.REMOVE = REMOVE$1; +async function visitAsync_(key2, node2, visitor, path2) { + const ctrl = await callVisitor(key2, node2, visitor, path2); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key2, path2, ctrl); + return visitAsync_(key2, ctrl, visitor, path2); + } + if (typeof ctrl !== "symbol") { + if (isCollection$1(node2)) { + path2 = Object.freeze(path2.concat(node2)); + for (let i = 0; i < node2.items.length; ++i) { + const ci = await visitAsync_(i, node2.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node2.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node2)) { + path2 = Object.freeze(path2.concat(node2)); + const ck = await visitAsync_("key", node2.key, visitor, path2); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node2.key = null; + const cv = await visitAsync_("value", node2.value, visitor, path2); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node2.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key2, node2, visitor, path2) { + var _a2, _b2, _c2, _d2, _e2; + if (typeof visitor === "function") + return visitor(key2, node2, path2); + if (isMap(node2)) + return (_a2 = visitor.Map) == null ? void 0 : _a2.call(visitor, key2, node2, path2); + if (isSeq(node2)) + return (_b2 = visitor.Seq) == null ? void 0 : _b2.call(visitor, key2, node2, path2); + if (isPair(node2)) + return (_c2 = visitor.Pair) == null ? void 0 : _c2.call(visitor, key2, node2, path2); + if (isScalar$1(node2)) + return (_d2 = visitor.Scalar) == null ? void 0 : _d2.call(visitor, key2, node2, path2); + if (isAlias(node2)) + return (_e2 = visitor.Alias) == null ? void 0 : _e2.call(visitor, key2, node2, path2); + return void 0; +} +function replaceNode(key2, path2, node2) { + const parent = path2[path2.length - 1]; + if (isCollection$1(parent)) { + parent.items[key2] = node2; + } else if (isPair(parent)) { + if (key2 === "key") + parent.key = node2; + else + parent.value = node2; + } else if (isDocument(parent)) { + parent.contents = node2; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} +const escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +class Directives { + constructor(yaml2, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml2); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version2] = parts; + if (version2 === "1.1" || version2 === "1.2") { + this.yaml.version = version2; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version2); + onError(6, `Unsupported YAML version ${version2}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source2, onError) { + if (source2 === "!") + return "!"; + if (source2[0] !== "!") { + onError(`Not a valid tag: ${source2}`); + return null; + } + if (source2[1] === "<") { + const verbatim = source2.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source2} is invalid.`); + return null; + } + if (source2[source2.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source2.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source2} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error2) { + onError(String(error2)); + return null; + } + } + if (handle === "!") + return source2; + onError(`Could not resolve tag: ${source2}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit$1(doc.contents, (_key, node2) => { + if (isNode(node2) && node2.tag) + tags[node2.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } +} +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit$1(root, { + Value(_key, node2) { + if (node2.anchor) + anchors.add(node2.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source2) => { + aliasObjects.push(source2); + if (!prevAnchors) + prevAnchors = anchorNames(doc); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source2 of aliasObjects) { + const ref2 = sourceObjects.get(source2); + if (typeof ref2 === "object" && ref2.anchor && (isScalar$1(ref2.node) || isCollection$1(ref2.node))) { + ref2.node.anchor = ref2.anchor; + } else { + const error2 = new Error("Failed to resolve repeated object (this should not happen)"); + error2.source = source2; + throw error2; + } + } + }, + sourceObjects + }; +} +function applyReviver(reviver, obj, key2, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key2, val); +} +function toJS(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !hasAnchor(value)) + return value.toJSON(arg, ctx); + const data2 = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value, data2); + ctx.onCreate = (res2) => { + data2.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !(ctx == null ? void 0 : ctx.keep)) + return Number(value); + return value; +} +class NodeBase { + constructor(type2) { + Object.defineProperty(this, NODE_TYPE, { value: type2 }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +} +class Alias extends NodeBase { + constructor(source2) { + super(ALIAS); + this.source = source2; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc) { + let found = void 0; + visit$1(doc, { + Node: (_key, node2) => { + if (node2 === this) + return visit$1.BREAK; + if (node2.anchor === this.source) + found = node2; + } + }); + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source2 = this.resolve(doc); + if (!source2) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data2 = anchors.get(source2); + if (!data2) { + toJS(source2, null, ctx); + data2 = anchors.get(source2); + } + if (!data2 || data2.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data2.count += 1; + if (data2.aliasCount === 0) + data2.aliasCount = getAliasCount(doc, source2, anchors); + if (data2.count * data2.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + return data2.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src2 = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src2} `; + } + return src2; + } +} +function getAliasCount(doc, node2, anchors) { + if (isAlias(node2)) { + const source2 = node2.resolve(doc); + const anchor = anchors && source2 && anchors.get(source2); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection$1(node2)) { + let count = 0; + for (const item of node2.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node2)) { + const kc = getAliasCount(doc, node2.key, anchors); + const vc = getAliasCount(doc, node2.value, anchors); + return Math.max(kc, vc); + } + return 1; +} +const isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; +class Scalar extends NodeBase { + constructor(value) { + super(SCALAR$1); + this.value = value; + } + toJSON(arg, ctx) { + return (ctx == null ? void 0 : ctx.keep) ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +} +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; +const defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => { + var _a2; + return ((_a2 = t.identify) == null ? void 0 : _a2.call(t, value)) && !t.format; + }); +} +function createNode(value, tagName, ctx) { + var _a2, _b2, _c2; + if (isDocument(value)) + value = value.contents; + if (isNode(value)) + return value; + if (isPair(value)) { + const map2 = (_b2 = (_a2 = ctx.schema[MAP]).createNode) == null ? void 0 : _b2.call(_a2, ctx.schema, null, ctx); + map2.items.push(value); + return map2; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema2, sourceObjects } = ctx; + let ref2 = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref2 = sourceObjects.get(value); + if (ref2) { + if (!ref2.anchor) + ref2.anchor = onAnchor(value); + return new Alias(ref2.anchor); + } else { + ref2 = { anchor: null, node: null }; + sourceObjects.set(value, ref2); + } + } + if (tagName == null ? void 0 : tagName.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema2.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); + } + if (!value || typeof value !== "object") { + const node3 = new Scalar(value); + if (ref2) + ref2.node = node3; + return node3; + } + tagObj = value instanceof Map ? schema2[MAP] : Symbol.iterator in Object(value) ? schema2[SEQ] : schema2[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node2 = (tagObj == null ? void 0 : tagObj.createNode) ? tagObj.createNode(ctx.schema, value, ctx) : typeof ((_c2 = tagObj == null ? void 0 : tagObj.nodeClass) == null ? void 0 : _c2.from) === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value); + if (tagName) + node2.tag = tagName; + else if (!tagObj.default) + node2.tag = tagObj.tag; + if (ref2) + ref2.node = node2; + return node2; +} +function collectionFromPath(schema2, path2, value) { + let v = value; + for (let i = path2.length - 1; i >= 0; --i) { + const k = path2[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema2, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +const isEmptyPath = (path2) => path2 == null || typeof path2 === "object" && !!path2[Symbol.iterator]().next().done; +class Collection extends NodeBase { + constructor(type2, schema2) { + super(type2); + Object.defineProperty(this, "schema", { + value: schema2, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema2) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema2) + copy.schema = schema2; + copy.items = copy.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema2) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path2, value) { + if (isEmptyPath(path2)) + this.add(value); + else { + const [key2, ...rest] = path2; + const node2 = this.get(key2, true); + if (isCollection$1(node2)) + node2.addIn(rest, value); + else if (node2 === void 0 && this.schema) + this.set(key2, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path2) { + const [key2, ...rest] = path2; + if (rest.length === 0) + return this.delete(key2); + const node2 = this.get(key2, true); + if (isCollection$1(node2)) + return node2.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path2, keepScalar) { + const [key2, ...rest] = path2; + const node2 = this.get(key2, true); + if (rest.length === 0) + return !keepScalar && isScalar$1(node2) ? node2.value : node2; + else + return isCollection$1(node2) ? node2.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node2) => { + if (!isPair(node2)) + return false; + const n = node2.value; + return n == null || allowScalar && isScalar$1(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path2) { + const [key2, ...rest] = path2; + if (rest.length === 0) + return this.has(key2); + const node2 = this.get(key2, true); + return isCollection$1(node2) ? node2.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path2, value) { + const [key2, ...rest] = path2; + if (rest.length === 0) { + this.set(key2, value); + } else { + const node2 = this.get(key2, true); + if (isCollection$1(node2)) + node2.setIn(rest, value); + else if (node2 === void 0 && this.schema) + this.set(key2, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest}`); + } + } +} +const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment2, indent) { + if (/^\n+$/.test(comment2)) + return comment2.substring(1); + return indent ? comment2.replace(/^(?! *$)/gm, indent) : comment2; +} +const lineComment = (str, indent, comment2) => str.endsWith("\n") ? indentComment(comment2, indent) : comment2.includes("\n") ? "\n" + indentComment(comment2, indent) : (str.endsWith(" ") ? "" : " ") + comment2; +const FOLD_FLOW = "flow"; +const FOLD_BLOCK = "block"; +const FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} +const getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str += "\n"; + i += 2; + } + str += indent; + if (json[i + 2] === " ") + str += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +let blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (literal2 ? "|" : ">") + (startWithSpace ? indentSize : "") + chomp; + if (comment2) { + header += " " + commentString(comment2.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (literal2) { + value = value.replace(/\n+/g, `$&${indent}`); + return `${header} +${indent}${start}${value}${end}`; + } + value = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true)); + return `${header} +${indent}${body}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type: type2, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); + } + if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type2 !== Scalar.PLAIN && value.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => { + var _a2; + return tag.default && tag.tag !== "tag:yaml.org,2002:str" && ((_a2 = tag.test) == null ? void 0 : _a2.test(str)); + }; + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || (compat == null ? void 0 : compat.some(test))) + return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type: type2 } = item; + if (type2 !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type2 = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type2); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} +function createStringifyContext(doc, options2) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options2); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; +} +function getTagObject(tags, item) { + var _a2; + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj; + if (isScalar$1(item)) { + obj = item.value; + let match = tags.filter((t) => { + var _a3; + return (_a3 = t.identify) == null ? void 0 : _a3.call(t, obj); + }); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj = item; + tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = ((_a2 = obj == null ? void 0 : obj.constructor) == null ? void 0 : _a2.name) ?? typeof obj; + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node2, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar$1(node2) || isCollection$1(node2)) && node2.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node2.tag ? node2.tag : tagObj.default ? null : tagObj.tag; + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify$2(item, ctx, onComment, onChompKeep) { + var _a2; + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if ((_a2 = ctx.resolvedAliases) == null ? void 0 : _a2.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node2 = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + if (!tagObj) + tagObj = getTagObject(ctx.doc.schema.tags, node2); + const props = stringifyProps(node2, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node2, ctx, onComment, onChompKeep) : isScalar$1(node2) ? stringifyString(node2, ctx, onComment, onChompKeep) : node2.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return isScalar$1(node2) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} +${ctx.indent}${str}`; +} +function stringifyPair({ key: key2, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key2) && key2.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection$1(key2) || !isNode(key2) && typeof key2 === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key2 || keyComment && value == null && !ctx.inFlow || isCollection$1(key2) || (isScalar$1(key2) ? key2.type === Scalar.BLOCK_FOLDED || key2.type === Scalar.BLOCK_LITERAL : typeof key2 === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify$2(key2, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += lineComment(str, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str} +${indent}:`; + } else { + str = `${str}:`; + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar$1(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify$2(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws2 = " "; + if (keyComment || vsb || vcb) { + ws2 = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws2 += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws2 === "\n") + ws2 = "\n\n"; + } else { + ws2 += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection$1(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws2 = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws2 = ""; + } + str += ws2 + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str += lineComment(str, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; +} +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + if (typeof process !== "undefined" && process.emitWarning) + process.emitWarning(warning); + else + console.warn(warning); + } +} +const MERGE_KEY = "<<"; +const merge = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +const isMergeKey = (ctx, key2) => (merge.identify(key2) || isScalar$1(key2) && (!key2.type || key2.type === Scalar.PLAIN) && merge.identify(key2.value)) && (ctx == null ? void 0 : ctx.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default)); +function addMergeToJSMap(ctx, map2, value) { + value = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (isSeq(value)) + for (const it of value.items) + mergeValue(ctx, map2, it); + else if (Array.isArray(value)) + for (const it of value) + mergeValue(ctx, map2, it); + else + mergeValue(ctx, map2, value); +} +function mergeValue(ctx, map2, value) { + const source2 = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (!isMap(source2)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source2.toJSON(null, ctx, Map); + for (const [key2, value2] of srcMap) { + if (map2 instanceof Map) { + if (!map2.has(key2)) + map2.set(key2, value2); + } else if (map2 instanceof Set) { + map2.add(key2); + } else if (!Object.prototype.hasOwnProperty.call(map2, key2)) { + Object.defineProperty(map2, key2, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map2; +} +function addPairToJSMap(ctx, map2, { key: key2, value }) { + if (isNode(key2) && key2.addToJSMap) + key2.addToJSMap(ctx, map2, value); + else if (isMergeKey(ctx, key2)) + addMergeToJSMap(ctx, map2, value); + else { + const jsKey = toJS(key2, "", ctx); + if (map2 instanceof Map) { + map2.set(jsKey, toJS(value, jsKey, ctx)); + } else if (map2 instanceof Set) { + map2.add(jsKey); + } else { + const stringKey = stringifyKey(key2, jsKey, ctx); + const jsValue = toJS(value, stringKey, ctx); + if (stringKey in map2) + Object.defineProperty(map2, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map2[stringKey] = jsValue; + } + } + return map2; +} +function stringifyKey(key2, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key2) && (ctx == null ? void 0 : ctx.doc)) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node2 of ctx.anchors.keys()) + strCtx.anchors.add(node2.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key2.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} +function createPair(key2, value, ctx) { + const k = createNode(key2, void 0, ctx); + const v = createNode(value, void 0, ctx); + return new Pair(k, v); +} +class Pair { + constructor(key2, value = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key2; + this.value = value; + } + clone(schema2) { + let { key: key2, value } = this; + if (isNode(key2)) + key2 = key2.clone(schema2); + if (isNode(value)) + value = value.clone(schema2); + return new Pair(key2, value); + } + toJSON(_, ctx) { + const pair = (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return (ctx == null ? void 0 : ctx.doc) ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +} +function stringifyCollection(collection, ctx, options2) { + const flow = ctx.inFlow ?? collection.flow; + const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify2(collection, ctx, options2); +} +function stringifyBlockCollection({ comment: comment2, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment3 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment3 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str2 = stringify$2(item, itemCtx, () => comment3 = null, () => chompKeep = true); + if (comment3) + str2 += lineComment(str2, itemIndent, commentString(comment3)); + if (chompKeep && comment3) + chompKeep = false; + lines.push(blockItemPrefix + str2); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment2) { + str += "\n" + indentComment(commentString(comment2), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment2 = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && (ik == null ? void 0 : ik.comment)) { + comment2 = ik.comment; + } + } + if (comment2) + reqNewline = true; + let str = stringify$2(item, itemCtx, () => comment2 = null); + if (i < items.length - 1) + str += ","; + if (comment2) + str += lineComment(str, itemIndent, commentString(comment2)); + if (!reqNewline && (lines.length > linesAtValue || str.includes("\n"))) + reqNewline = true; + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment2, chompKeep) { + if (comment2 && chompKeep) + comment2 = comment2.replace(/^\n+/, ""); + if (comment2) { + const ic = indentComment(commentString(comment2), indent); + lines.push(ic.trimStart()); + } +} +function findPair(items, key2) { + const k = isScalar$1(key2) ? key2.value : key2; + for (const it of items) { + if (isPair(it)) { + if (it.key === key2 || it.key === k) + return it; + if (isScalar$1(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +class YAMLMap extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema2) { + super(MAP, schema2); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema2, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map2 = new this(schema2); + const add = (key2, value) => { + if (typeof replacer === "function") + value = replacer.call(obj, key2, value); + else if (Array.isArray(replacer) && !replacer.includes(key2)) + return; + if (value !== void 0 || keepUndefined) + map2.items.push(createPair(key2, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key2, value] of obj) + add(key2, value); + } else if (obj && typeof obj === "object") { + for (const key2 of Object.keys(obj)) + add(key2, obj[key2]); + } + if (typeof schema2.sortMapEntries === "function") { + map2.items.sort(schema2.sortMapEntries); + } + return map2; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + var _a2; + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair == null ? void 0 : pair.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = (_a2 = this.schema) == null ? void 0 : _a2.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar$1(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key2) { + const it = findPair(this.items, key2); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key2, keepScalar) { + const it = findPair(this.items, key2); + const node2 = it == null ? void 0 : it.value; + return (!keepScalar && isScalar$1(node2) ? node2.value : node2) ?? void 0; + } + has(key2) { + return !!findPair(this.items, key2); + } + set(key2, value) { + this.add(new Pair(key2, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map2 = Type ? new Type() : (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {}; + if (ctx == null ? void 0 : ctx.onCreate) + ctx.onCreate(map2); + for (const item of this.items) + addPairToJSMap(ctx, map2, item); + return map2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +} +const map = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map2, onError) { + if (!isMap(map2)) + onError("Expected a mapping for this tag"); + return map2; + }, + createNode: (schema2, obj, ctx) => YAMLMap.from(schema2, obj, ctx) +}; +class YAMLSeq extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema2) { + super(SEQ, schema2); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key2) { + const idx = asItemIndex(key2); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key2, keepScalar) { + const idx = asItemIndex(key2); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar$1(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key2) { + const idx = asItemIndex(key2); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key2, value) { + const idx = asItemIndex(key2); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key2}.`); + const prev = this.items[idx]; + if (isScalar$1(prev) && isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx == null ? void 0 : ctx.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema2, obj, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema2); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key2 = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key2, it); + } + seq2.items.push(createNode(it, void 0, ctx)); + } + } + return seq2; + } +} +function asItemIndex(key2) { + let idx = isScalar$1(key2) ? key2.value : key2; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} +const seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema2, obj, ctx) => YAMLSeq.from(schema2, obj, ctx) +}; +const string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; +const nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source: source2 }, ctx) => typeof source2 === "string" && nullTag.test.test(source2) ? source2 : ctx.options.nullStr +}; +const boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source: source2, value }, ctx) { + if (source2 && boolTag.test.test(source2)) { + const sv = source2[0] === "t" || source2[0] === "T"; + if (value === sv) + return source2; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } +}; +function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === "bigint") + return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n = JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} +const floatNaN$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node2) { + const num = Number(node2.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node2); + } +}; +const float$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node2 = new Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") + node2.minFractionDigits = str.length - dot - 1; + return node2; + }, + stringify: stringifyNumber +}; +const intIdentify$2 = (value) => typeof value === "bigint" || Number.isInteger(value); +const intResolve$1 = (str, offset2, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset2), radix); +function intStringify$1(node2, radix, prefix) { + const { value } = node2; + if (intIdentify$2(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber(node2); +} +const intOct$1 = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt), + stringify: (node2) => intStringify$1(node2, 8, "0o") +}; +const int$1 = { + identify: intIdentify$2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex$1 = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt), + stringify: (node2) => intStringify$1(node2, 16, "0x") +}; +const schema$2 = [ + map, + seq, + string, + nullTag, + boolTag, + intOct$1, + int$1, + intHex$1, + floatNaN$1, + floatExp$1, + float$1 +]; +function intIdentify$1(value) { + return typeof value === "bigint" || Number.isInteger(value); +} +const stringifyJSON = ({ value }) => JSON.stringify(value); +const jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true|false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify$1, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } +]; +const jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } +}; +const schema$1 = [map, seq].concat(jsonScalars, jsonError); +const binary = { + identify: (value) => value instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src2, onError) { + if (typeof Buffer === "function") { + return Buffer.from(src2, "base64"); + } else if (typeof atob === "function") { + const str = atob(src2.replace(/[\n\r]/g, "")); + const buffer2 = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer2[i] = str.charCodeAt(i); + return buffer2; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src2; + } + }, + stringify({ comment: comment2, type: type2, value }, ctx, onComment, onChompKeep) { + const buf = value; + let str; + if (typeof Buffer === "function") { + str = buf instanceof Buffer ? buf.toString("base64") : Buffer.from(buf.buffer).toString("base64"); + } else if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + if (!type2) + type2 = Scalar.BLOCK_LITERAL; + if (type2 !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type2 === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment: comment2, type: type2, value: str }, ctx, onComment, onChompKeep); + } +}; +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema2, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema2); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key2, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key2 = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key2 = keys[0]; + value = it[key2]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key2 = it; + } + pairs2.items.push(createPair(key2, value, ctx)); + } + return pairs2; +} +const pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; +class YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map2 = /* @__PURE__ */ new Map(); + if (ctx == null ? void 0 : ctx.onCreate) + ctx.onCreate(map2); + for (const pair of this.items) { + let key2, value; + if (isPair(pair)) { + key2 = toJS(pair.key, "", ctx); + value = toJS(pair.value, key2, ctx); + } else { + key2 = toJS(pair, "", ctx); + } + if (map2.has(key2)) + throw new Error("Ordered maps must not include duplicate keys"); + map2.set(key2, value); + } + return map2; + } + static from(schema2, iterable, ctx) { + const pairs2 = createPairs(schema2, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +} +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +const omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key: key2 } of pairs2.items) { + if (isScalar$1(key2)) { + if (seenKeys.includes(key2.value)) { + onError(`Ordered maps must not include duplicate keys: ${key2.value}`); + } else { + seenKeys.push(key2.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema2, iterable, ctx) => YAMLOMap.from(schema2, iterable, ctx) +}; +function boolStringify({ value, source: source2 }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source2 && boolObj.test.test(source2)) + return source2; + return value ? ctx.options.trueStr : ctx.options.falseStr; +} +const trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +const falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; +const floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node2) { + const num = Number(node2.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node2); + } +}; +const float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node2 = new Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node2.minFractionDigits = f.length; + } + return node2; + }, + stringify: stringifyNumber +}; +const intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); +function intResolve(str, offset2, radix, { intAsBigInt }) { + const sign2 = str[0]; + if (sign2 === "-" || sign2 === "+") + offset2 += 1; + str = str.substring(offset2).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n2 = BigInt(str); + return sign2 === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str, radix); + return sign2 === "-" ? -1 * n : n; +} +function intStringify(node2, radix, prefix) { + const { value } = node2; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber(node2); +} +const intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node2) => intStringify(node2, 2, "0b") +}; +const intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node2) => intStringify(node2, 8, "0") +}; +const int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node2) => intStringify(node2, 16, "0x") +}; +class YAMLSet extends YAMLMap { + constructor(schema2) { + super(schema2); + this.tag = YAMLSet.tag; + } + add(key2) { + let pair; + if (isPair(key2)) + pair = key2; + else if (key2 && typeof key2 === "object" && "key" in key2 && "value" in key2 && key2.value === null) + pair = new Pair(key2.key, null); + else + pair = new Pair(key2, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key2, keepPair) { + const pair = findPair(this.items, key2); + return !keepPair && isPair(pair) ? isScalar$1(pair.key) ? pair.key.value : pair.key : pair; + } + set(key2, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = findPair(this.items, key2); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair(key2)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema2, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema2); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set2.items.push(createPair(value, null, ctx)); + } + return set2; + } +} +YAMLSet.tag = "tag:yaml.org,2002:set"; +const set = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema2, iterable, ctx) => YAMLSet.from(schema2, iterable, ctx), + resolve(map2, onError) { + if (isMap(map2)) { + if (map2.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map2); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map2; + } +}; +function parseSexagesimal(str, asBigInt) { + const sign2 = str[0]; + const parts = sign2 === "-" || sign2 === "+" ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); + return sign2 === "-" ? num(-1) * res : res; +} +function stringifySexagesimal(node2) { + let { value } = node2; + let num = (n) => n; + if (typeof value === "bigint") + num = (n) => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber(node2); + let sign2 = ""; + if (value < 0) { + sign2 = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) { + parts.unshift(0); + } else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign2 + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +const intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "") +}; +const schema = [ + map, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct, + int, + intHex, + floatNaN, + floatExp, + float, + binary, + merge, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; +const schemas = /* @__PURE__ */ new Map([ + ["core", schema$2], + ["failsafe", [map, seq, string]], + ["json", schema$1], + ["yaml11", schema], + ["yaml-1.1", schema] +]); +const tagsByName = { + binary, + bool: boolTag, + float: float$1, + floatExp: floatExp$1, + floatNaN: floatNaN$1, + floatTime, + int: int$1, + intHex: intHex$1, + intOct: intOct$1, + intTime, + map, + merge, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +const coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge) ? schemaTags.concat(merge) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key2) => key2 !== "yaml11").map((key2) => JSON.stringify(key2)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key2) => JSON.stringify(key2)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +class Schema { + constructor({ compat, customTags, merge: merge2, resolveKnownTags, schema: schema2, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema2 === "string" && schema2 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge2); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map }); + Object.defineProperty(this, SCALAR$1, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } +} +function stringifyDocument(doc, options2) { + var _a2; + const lines = []; + let hasDirectives = options2.directives === true; + if (options2.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push("---"); + const ctx = createStringifyContext(doc, options2); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify$2(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { + lines[lines.length - 1] = `--- ${body}`; + } else + lines.push(body); + } else { + lines.push(stringify$2(doc.contents, ctx)); + } + if ((_a2 = doc.directives) == null ? void 0 : _a2.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines.push("..."); + lines.push(indentComment(cs, "")); + } else { + lines.push(`... ${cs}`); + } + } else { + lines.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") + lines.push(""); + lines.push(indentComment(commentString(dc), "")); + } + } + return lines.join("\n") + "\n"; +} +class Document { + constructor(value, replacer, options2) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options2 === void 0 && replacer) { + options2 = replacer; + replacer = void 0; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options2); + this.options = opt; + let { version: version2 } = opt; + if (options2 == null ? void 0 : options2._directives) { + this.directives = options2._directives.atDocument(); + if (this.directives.yaml.explicit) + version2 = this.directives.yaml.version; + } else + this.directives = new Directives({ version: version2 }); + this.setSchema(version2, options2); + this.contents = value === void 0 ? null : this.createNode(value, _replacer, options2); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path2, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path2, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node2, name) { + if (!node2.anchor) { + const prev = anchorNames(this); + node2.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node2.anchor); + } + createNode(value, replacer, options2) { + let _replacer = void 0; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options2 === void 0 && replacer) { + options2 = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options2 ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node2 = createNode(value, tag, ctx); + if (flow && isCollection$1(node2)) + node2.flow = true; + setAnchors(); + return node2; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key2, value, options2 = {}) { + const k = this.createNode(key2, null, options2); + const v = this.createNode(value, null, options2); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key2) { + return assertCollection(this.contents) ? this.contents.delete(key2) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path2) { + if (isEmptyPath(path2)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path2) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key2, keepScalar) { + return isCollection$1(this.contents) ? this.contents.get(key2, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path2, keepScalar) { + if (isEmptyPath(path2)) + return !keepScalar && isScalar$1(this.contents) ? this.contents.value : this.contents; + return isCollection$1(this.contents) ? this.contents.getIn(path2, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key2) { + return isCollection$1(this.contents) ? this.contents.has(key2) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path2) { + if (isEmptyPath(path2)) + return this.contents !== void 0; + return isCollection$1(this.contents) ? this.contents.hasIn(path2) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key2, value) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key2], value); + } else if (assertCollection(this.contents)) { + this.contents.set(key2, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path2, value) { + if (isEmptyPath(path2)) { + this.contents = value; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path2), value); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path2, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version2, options2 = {}) { + if (typeof version2 === "number") + version2 = String(version2); + let opt; + switch (version2) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version2; + else + this.directives = new Directives({ version: version2 }); + opt = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version2); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options2.schema instanceof Object) + this.schema = options2.schema; + else if (opt) + this.schema = new Schema(Object.assign(opt, options2)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options2 = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options2 && (!Number.isInteger(options2.indent) || Number(options2.indent) <= 0)) { + const s = JSON.stringify(options2.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options2); + } +} +function assertCollection(contents) { + if (isCollection$1(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +} +class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +} +class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +} +const prettifyError = (src2, lc) => (error2) => { + if (error2.pos[0] === -1) + return; + error2.linePos = error2.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error2.linePos[0]; + error2.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src2.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src2.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "…\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error2.linePos[1]; + if (end && end.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = " ".repeat(ci) + "^".repeat(count); + error2.message += `: + +${lineStr} +${pointer} +`; + } +}; +function resolveProps(tokens, { flow, indicator, next, offset: offset2, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment2 = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || (next == null ? void 0 : next.type) !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment2) + comment2 = cb; + else + comment2 += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment2) + comment2 += token.source; + else + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + if (start === null) + start = token.offset; + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + if (start === null) + start = token.offset; + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset2; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || (next == null ? void 0 : next.type) === "block-map" || (next == null ? void 0 : next.type) === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment: comment2, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} +function containsNewline(key2) { + if (!key2) + return null; + switch (key2.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key2.source.includes("\n")) + return true; + if (key2.end) { + for (const st of key2.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key2.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} +function flowIndentCheck(indent, fc, onError) { + if ((fc == null ? void 0 : fc.type) === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar$1(a) && isScalar$1(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} +const startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + var _a2; + const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLMap; + const map2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset2 = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key: key2, sep, value } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key2 ?? (sep == null ? void 0 : sep[0]), + offset: offset2, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key2) { + if (key2.type === "block-seq") + onError(offset2, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key2 && key2.indent !== bm.indent) + onError(offset2, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map2.comment) + map2.comment += "\n" + keyProps.comment; + else + map2.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key2)) { + onError(key2 ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (((_a2 = keyProps.found) == null ? void 0 : _a2.indent) !== bm.indent) { + onError(offset2, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key2 ? composeNode2(ctx, key2, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key2, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map2.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key2 || key2.type === "block-scalar" + }); + offset2 = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if ((value == null ? void 0 : value.type) === "block-map" && !valueProps.hasNewline) + onError(offset2, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : composeEmptyNode2(ctx, offset2, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value, onError); + offset2 = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } + } + if (commentEnd && commentEnd < offset2) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map2.range = [bm.offset, offset2, commentEnd ?? offset2]; + return map2; +} +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset2 = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset: offset2, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value && value.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset2, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node2 = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value, onError); + offset2 = node2.range[2]; + seq2.items.push(node2); + } + seq2.range = [bs.offset, offset2, commentEnd ?? offset2]; + return seq2; +} +function resolveEnd(end, offset2, reqSpace, onError) { + let comment2 = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source: source2, type: type2 } = token; + switch (type2) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source2.substring(1) || " "; + if (!comment2) + comment2 = cb; + else + comment2 += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment2) + sep += source2; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type2} at node end`); + } + offset2 += source2.length; + } + } + return { comment: comment2, offset: offset2 }; +} +const blockMsg = "Block collections are not allowed within flow collections"; +const isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset2 = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key: key2, sep, value } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key2 ?? (sep == null ? void 0 : sep[0]), + offset: offset2, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset2 = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key2)) + onError( + key2, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset2 = valueNode.range[2]; + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key2 ? composeNode2(ctx, key2, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key2)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) { + if ("source" in value && value.source && value.source[0] === ":") + onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map2 = coll; + if (mapIncludes(ctx, map2.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map2.items.push(pair); + } else { + const map2 = new YAMLMap(ctx.schema); + map2.flow = true; + map2.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map2.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map2); + } + offset2 = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset2; + if (ce && ce.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset2, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + var _a2; + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt && kt.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt == null ? void 0 : kt.collection) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = ((_a2 = tag.resolve) == null ? void 0 : _a2.call(tag, coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options)) ?? coll; + const node2 = isNode(res) ? res : new Scalar(res); + node2.range = coll.range; + node2.tag = tagName; + if (tag == null ? void 0 : tag.format) + node2.format = tag.format; + return node2; +} +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type2 = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value2, type: type2, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset2 = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset2 + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset2, "BAD_INDENT", message); + } + break; + } + offset2 += indent.length + content.length + 1; + } + for (let i = lines.length - 1; i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset2 += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src2 = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src2}`; + onError(offset2 - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type2 === Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value += "\n"; + else + sep = "\n"; + } else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines.length; ++i) + value += "\n" + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== "\n") + value += "\n"; + break; + default: + value += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value, type: type2, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset: offset2, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source: source2 } = props[0]; + const mode = source2[0]; + let indent = 0; + let chomp = ""; + let error2 = -1; + for (let i = 1; i < source2.length; ++i) { + const ch = source2[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error2 === -1) + error2 = offset2 + i; + } + } + if (error2 !== -1) + onError(error2, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source2}`); + let hasSpace = false; + let comment2 = ""; + let length = source2.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment2 = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment: comment2, length }; +} +function splitLines(source2) { + const split = source2.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = (m == null ? void 0 : m[1]) ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines = [line0]; + for (let i = 1; i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; +} +function resolveFlowScalar(scalar, strict, onError) { + const { offset: offset2, type: type2, source: source2, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset2 + rel, code, msg); + switch (type2) { + case "scalar": + _type = Scalar.PLAIN; + value = plainValue(source2, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source2, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source2, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type2}`); + return { + value: "", + type: null, + comment: "", + range: [offset2, offset2 + source2.length, offset2 + source2.length] + }; + } + const valueEnd = offset2 + source2.length; + const re2 = resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re2.comment, + range: [offset2, valueEnd, re2.offset] + }; +} +function plainValue(source2, onError) { + let badChar = ""; + switch (source2[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source2[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source2[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source2); +} +function singleQuotedValue(source2, onError) { + if (source2[source2.length - 1] !== "'" || source2.length === 1) + onError(source2.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source2.slice(1, -1)).replace(/''/g, "'"); +} +function foldLines(source2) { + let first, line; + try { + first = new RegExp("(.*?)(? wsStart ? source2.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source2[source2.length - 1] !== '"' || source2.length === 1) + onError(source2.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source2, offset2) { + let fold = ""; + let ch = source2[offset2 + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source2[offset2 + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset2 += 1; + ch = source2[offset2 + 1]; + } + if (!fold) + fold = " "; + return { fold, offset: offset2 }; +} +const escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "…", + // Unicode next line + _: " ", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source2, offset2, length, onError) { + const cc = source2.substr(offset2, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + if (isNaN(code)) { + const raw = source2.substr(offset2 - 2, length + 2); + onError(offset2 - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } + return String.fromCodePoint(code); +} +function composeScalar(ctx, token, tagToken, onError) { + const { value, type: type2, comment: comment2, range: range2 } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR$1]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value, token, onError); + else + tag = ctx.schema[SCALAR$1]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar$1(res) ? res : new Scalar(res); + } catch (error2) { + const msg = error2 instanceof Error ? error2.message : String(error2); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value); + } + scalar.range = range2; + scalar.source = value; + if (type2) + scalar.type = type2; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment2) + scalar.comment = comment2; + return scalar; +} +function findScalarTagByName(schema2, value, tagName, tagToken, onError) { + var _a2; + if (tagName === "!") + return schema2[SCALAR$1]; + const matchWithTest = []; + for (const tag of schema2.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if ((_a2 = tag.test) == null ? void 0 : _a2.test(value)) + return tag; + const kt = schema2.knownTags[tagName]; + if (kt && !kt.collection) { + schema2.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema2[SCALAR$1]; +} +function findScalarTagByTest({ atKey, directives, schema: schema2 }, value, token, onError) { + const tag = schema2.tags.find((tag2) => { + var _a2; + return (tag2.default === true || atKey && tag2.default === "key") && ((_a2 = tag2.test) == null ? void 0 : _a2.test(value)); + }) || schema2[SCALAR$1]; + if (schema2.compat) { + const compat = schema2.compat.find((tag2) => { + var _a2; + return tag2.default && ((_a2 = tag2.test) == null ? void 0 : _a2.test(value)); + }) ?? schema2[SCALAR$1]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} +function emptyScalarPosition(offset2, before, pos) { + if (before) { + if (pos === null) + pos = before.length; + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset2 -= st.source.length; + continue; + } + st = before[++i]; + while ((st == null ? void 0 : st.type) === "space") { + offset2 += st.source.length; + st = before[++i]; + } + break; + } + } + return offset2; +} +const CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment: comment2, anchor, tag } = props; + let node2; + let isSrcToken = true; + switch (token.type) { + case "alias": + node2 = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node2 = composeScalar(ctx, token, tag, onError); + if (anchor) + node2.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + node2 = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node2.anchor = anchor.source.substring(1); + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + node2 = composeEmptyNode(ctx, token.offset, void 0, null, props, onError); + isSrcToken = false; + } + } + if (anchor && node2.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar$1(node2) || typeof node2.value !== "string" || node2.tag && node2.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node2.spaceBefore = true; + if (comment2) { + if (token.type === "scalar" && token.source === "") + node2.comment = comment2; + else + node2.commentBefore = comment2; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node2.srcToken = token; + return node2; +} +function composeEmptyNode(ctx, offset2, before, pos, { spaceBefore, comment: comment2, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset2, before, pos), + indent: -1, + source: "" + }; + const node2 = composeScalar(ctx, token, tag, onError); + if (anchor) { + node2.anchor = anchor.source.substring(1); + if (node2.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node2.spaceBefore = true; + if (comment2) { + node2.comment = comment2; + node2.range[2] = end; + } + return node2; +} +function composeAlias({ options: options2 }, { offset: offset2, source: source2, end }, onError) { + const alias = new Alias(source2.substring(1)); + if (alias.source === "") + onError(offset2, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset2 + source2.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset2 + source2.length; + const re2 = resolveEnd(end, valueEnd, options2.strict, onError); + alias.range = [offset2, valueEnd, re2.offset]; + if (re2.comment) + alias.comment = re2.comment; + return alias; +} +function composeDoc(options2, directives, { offset: offset2, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options2); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value ?? (end == null ? void 0 : end[0]), + offset: offset2, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re2 = resolveEnd(end, contentEnd, false, onError); + if (re2.comment) + doc.comment = re2.comment; + doc.range = [offset2, contentEnd, re2.offset]; + return doc; +} +function getErrorPos(src2) { + if (typeof src2 === "number") + return [src2, src2 + 1]; + if (Array.isArray(src2)) + return src2.length === 2 ? src2 : [src2[0], src2[1]]; + const { offset: offset2, source: source2 } = src2; + return [offset2, offset2 + (typeof source2 === "string" ? source2.length : 1)]; +} +function parsePrelude(prelude) { + var _a2; + let comment2 = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source2 = prelude[i]; + switch (source2[0]) { + case "#": + comment2 += (comment2 === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source2.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (((_a2 = prelude[i + 1]) == null ? void 0 : _a2[0]) !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment: comment2, afterEmptyLine }; +} +class Composer { + constructor(options2 = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source2, code, message, warning) => { + const pos = getErrorPos(source2); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options2.version || "1.2" }); + this.options = options2; + } + decorate(doc, afterDoc) { + const { comment: comment2, afterEmptyLine } = parsePrelude(this.prelude); + if (comment2) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment2}` : comment2; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment2; + } else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment2} +${cb}` : comment2; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment2} +${cb}` : comment2; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset2, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset2; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error2 = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error2); + else + this.doc.errors.push(error2); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +} +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset2 = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset2, code, message); + else + throw new YAMLParseError([offset2, offset2 + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset: offset2 = -1, type: type2 = "PLAIN" } = context; + const source2 = stringifyString({ type: type2, value }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source2[0]) { + case "|": + case ">": { + const he = source2.indexOf("\n"); + const head = source2.substring(0, he); + const body = source2.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset: offset2, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset: offset2, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset: offset2, indent, source: source2, end }; + case "'": + return { type: "single-quoted-scalar", offset: offset2, indent, source: source2, end }; + default: + return { type: "scalar", offset: offset2, indent, source: source2, end }; + } +} +function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type: type2 } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type2) + switch (token.type) { + case "single-quoted-scalar": + type2 = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type2 = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type2 = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type2 = "PLAIN"; + } + const source2 = stringifyString({ type: type2, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source2[0]) { + case "|": + case ">": + setBlockScalarValue(token, source2); + break; + case '"': + setFlowScalarValue(token, source2, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source2, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source2, "scalar"); + } +} +function setBlockScalarValue(token, source2) { + const he = source2.indexOf("\n"); + const head = source2.substring(0, he); + const body = source2.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset: offset2 } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset: offset2, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key2 of Object.keys(token)) + if (key2 !== "type" && key2 !== "offset") + delete token[key2]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source2, type2) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type2; + token.source = source2; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source2.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type: type2, source: source2, end }); + break; + } + case "block-map": + case "block-seq": { + const offset2 = token.offset + source2.length; + const nl = { type: "newline", offset: offset2, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type: type2, source: source2, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key2 of Object.keys(token)) + if (key2 !== "type" && key2 !== "offset") + delete token[key2]; + Object.assign(token, { type: type2, indent, source: source2, end }); + } + } +} +const stringify$1 = (cst2) => "type" in cst2 ? stringifyToken(cst2) : stringifyItem(cst2); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key: key2, sep, value }) { + let res = ""; + for (const st of start) + res += st.source; + if (key2) + res += stringifyToken(key2); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; +} +const BREAK = Symbol("break visit"); +const SKIP = Symbol("skip children"); +const REMOVE = Symbol("remove item"); +function visit(cst2, visitor) { + if ("type" in cst2 && cst2.type === "document") + cst2 = { start: cst2.start, value: cst2.value }; + _visit(Object.freeze([]), cst2, visitor); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +visit.itemAtPath = (cst2, path2) => { + let item = cst2; + for (const [field, index2] of path2) { + const tok = item == null ? void 0 : item[field]; + if (tok && "items" in tok) { + item = tok.items[index2]; + } else + return void 0; + } + return item; +}; +visit.parentCollection = (cst2, path2) => { + const parent = visit.itemAtPath(cst2, path2.slice(0, -1)); + const field = path2[path2.length - 1][0]; + const coll = parent == null ? void 0 : parent[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path2, item, visitor) { + let ctrl = visitor(item, path2); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path2.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path2); + } + } + return typeof ctrl === "function" ? ctrl(item, path2) : ctrl; +} +const BOM = "\uFEFF"; +const DOCUMENT = ""; +const FLOW_END = ""; +const SCALAR = ""; +const isCollection = (token) => !!token && "items" in token; +const isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source2) { + switch (source2) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source2[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} +const cst = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + BOM, + DOCUMENT, + FLOW_END, + SCALAR, + createScalarToken, + isCollection, + isScalar, + prettyToken, + resolveAsScalar, + setScalarValue, + stringify: stringify$1, + tokenType, + visit +}, Symbol.toStringTag, { value: "Module" })); +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +const hexDigits = new Set("0123456789ABCDEFabcdef"); +const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +const flowIndicatorChars = new Set(",[]{}"); +const invalidAnchorChars = new Set(" ,[]{}\n\r "); +const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +class Lexer { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source2, incomplete = false) { + if (source2) { + if (typeof source2 !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source2 : source2; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset2) { + let ch = this.buffer[offset2]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset2]; + if (ch === "\r") { + const next = this.buffer[indent + offset2 + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset2 + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset2 + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset2, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset2 + 3])) + return -1; + } + return offset2; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state2) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state2; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return yield* this.parseBlockStart(); + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote2 = this.charAt(0); + let end = this.buffer.indexOf(quote2, this.pos + 1); + if (quote2 === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case "!": + return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "&": + return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +} +class LineCounter { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset2) => this.lineStarts.push(offset2); + this.linePos = (offset2) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset2) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset2) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset2 }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset2 - start + 1 }; + }; + } +} +function includesToken(list, type2) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type2) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token == null ? void 0 : token.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + var _a2; + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (((_a2 = prev[++i]) == null ? void 0 : _a2.type) === "space") { + } + return prev.splice(i, prev.length); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } +} +let Parser$1 = class Parser { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source2, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source2, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source2) { + this.source = source2; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source2.length; + return; + } + const type2 = tokenType(source2); + if (!type2) { + const message = `Not a YAML token: ${source2}`; + yield* this.pop({ type: "error", offset: this.offset, message, source: source2 }); + this.offset += source2.length; + } else if (type2 === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type2; + yield* this.step(); + switch (type2) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source2.length); + break; + case "space": + if (this.atNewLine && source2[0] === " ") + this.indent += source2.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source2.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source2.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && (!top || top.type !== "doc-end")) { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error2) { + const token = error2 ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map2 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map2) { + var _a2; + const it = map2.items[map2.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if ((last == null ? void 0 : last.type) === "comment") + end == null ? void 0 : end.push(this.sourceToken); + else + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map2.indent)) { + const prev = map2.items[map2.items.length - 2]; + const end = (_a2 = prev == null ? void 0 : prev.value) == null ? void 0 : _a2.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map2.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map2.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map2.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map2.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key2 = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: key2, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map2.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map2.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map2); + if (bv) { + if (atMapIndent && bv.type !== "block-seq") { + map2.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + var _a2; + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if ((last == null ? void 0 : last.type) === "comment") + end == null ? void 0 : end.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = (_a2 = prev == null ? void 0 : prev.value) == null ? void 0 : _a2.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top && top.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map2 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type2) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type: type2, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; +function parseOptions(options2) { + const prettyErrors = options2.prettyErrors !== false; + const lineCounter = options2.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source2, options2 = {}) { + const { lineCounter, prettyErrors } = parseOptions(options2); + const parser2 = new Parser$1(lineCounter == null ? void 0 : lineCounter.addNewLine); + const composer = new Composer(options2); + const docs = Array.from(composer.compose(parser2.parse(source2))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source2, lineCounter)); + doc.warnings.forEach(prettifyError(source2, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source2, options2 = {}) { + const { lineCounter, prettyErrors } = parseOptions(options2); + const parser2 = new Parser$1(lineCounter == null ? void 0 : lineCounter.addNewLine); + const composer = new Composer(options2); + let doc = null; + for (const _doc of composer.compose(parser2.parse(source2), true, source2.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source2, lineCounter)); + doc.warnings.forEach(prettifyError(source2, lineCounter)); + } + return doc; +} +function parse$2(src2, reviver, options2) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options2 === void 0 && reviver && typeof reviver === "object") { + options2 = reviver; + } + const doc = parseDocument(src2, options2); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options2)); +} +function stringify(value, replacer, options2) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options2 === void 0 && replacer) { + options2 = replacer; + } + if (typeof options2 === "string") + options2 = options2.length; + if (typeof options2 === "number") { + const indent = Math.round(options2); + options2 = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === void 0) { + const { keepUndefined } = options2 ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value) && !_replacer) + return value.toString(options2); + return new Document(value, _replacer, options2).toString(options2); +} +const YAML = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Alias, + CST: cst, + Composer, + Document, + Lexer, + LineCounter, + Pair, + Parser: Parser$1, + Scalar, + Schema, + YAMLError, + YAMLMap, + YAMLParseError, + YAMLSeq, + YAMLWarning, + isAlias, + isCollection: isCollection$1, + isDocument, + isMap, + isNode, + isPair, + isScalar: isScalar$1, + isSeq, + parse: parse$2, + parseAllDocuments, + parseDocument, + stringify, + visit: visit$1, + visitAsync +}, Symbol.toStringTag, { value: "Module" })); +var browser$2; +var hasRequiredBrowser$2; +function requireBrowser$2() { + if (hasRequiredBrowser$2) return browser$2; + hasRequiredBrowser$2 = 1; + browser$2 = function() { + throw new Error( + "ws does not work in the browser. Browser clients must use the native WebSocket object" + ); + }; + return browser$2; +} +var browserExports$1 = requireBrowser$2(); +const wsLibrary = /* @__PURE__ */ getDefaultExportFromCjs(browserExports$1); +const colors$1 = colorsLibrary; +const debug$1 = debugLibrary; +const diff2 = diffLibrary; +const dotenv = dotenvLibrary; +const jpegjs$1 = jpegLibrary; +const lockfileLibrary = requireLockfile(); +const lockfile$1 = lockfileLibrary; +const mime$1 = mimeLibrary; +const minimatch = minimatchLibrary; +const open$1 = openLibrary; +const progress$1 = progressLibrary; +const yaml$1 = YAML; +const ws$1 = wsLibrary; +const wsServer = browserExports$1.WebSocketServer; +const wsReceiver$1 = browserExports$1.Receiver; +const wsSender$1 = browserExports$1.Sender; +const utilsBundleImpl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + HttpsProxyAgent: distExports$1.HttpsProxyAgent, + PNG: pngExports.PNG, + SocksProxyAgent: distExports.SocksProxyAgent, + colors: colors$1, + debug: debug$1, + diff: diff2, + dotenv, + getProxyForUrl: proxyFromEnvExports.getProxyForUrl, + jpegjs: jpegjs$1, + lockfile: lockfile$1, + mime: mime$1, + minimatch, + open: open$1, + program: commanderExports.program, + progress: progress$1, + ws: ws$1, + wsReceiver: wsReceiver$1, + wsSender: wsSender$1, + wsServer, + yaml: yaml$1 +}, Symbol.toStringTag, { value: "Module" })); +const require$$0$2 = /* @__PURE__ */ getAugmentedNamespace(utilsBundleImpl); +const colors = require$$0$2.colors; +const debug$2 = require$$0$2.debug; +require$$0$2.diff; +require$$0$2.dotenv; +const getProxyForUrl = require$$0$2.getProxyForUrl; +const HttpsProxyAgent = require$$0$2.HttpsProxyAgent; +const jpegjs = require$$0$2.jpegjs; +const lockfile = require$$0$2.lockfile; +const mime = require$$0$2.mime; +require$$0$2.minimatch; +require$$0$2.open; +const PNG = require$$0$2.PNG; +require$$0$2.program; +const progress = require$$0$2.progress; +const SocksProxyAgent = require$$0$2.SocksProxyAgent; +const yaml = require$$0$2.yaml; +const ws = require$$0$2.ws; +require$$0$2.wsServer; +const wsReceiver = require$$0$2.wsReceiver; +const wsSender = require$$0$2.wsSender; +const debugLoggerColorMap = { + "api": 45, + // cyan + "protocol": 34, + // green + "install": 34, + // green + "download": 34, + // green + "browser": 0, + // reset + "socks": 92, + // purple + "client-certificates": 92, + // purple + "error": 160, + // red, + "channel": 33, + // blue + "server": 45, + // cyan + "server:channel": 34, + // green + "server:metadata": 33, + // blue, + "recorder": 45 + // cyan +}; +class DebugLogger { + constructor() { + this._debuggers = /* @__PURE__ */ new Map(); + if (define_process_env_default.DEBUG_FILE) { + const ansiRegex = new RegExp([ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" + ].join("|"), "g"); + const stream2 = fs.createWriteStream(define_process_env_default.DEBUG_FILE); + debug$2.log = (data2) => { + stream2.write(data2.replace(ansiRegex, "")); + stream2.write("\n"); + }; + } + } + log(name, message) { + let cachedDebugger = this._debuggers.get(name); + if (!cachedDebugger) { + cachedDebugger = debug$2(`pw:${name}`); + this._debuggers.set(name, cachedDebugger); + cachedDebugger.color = debugLoggerColorMap[name] || 0; + } + cachedDebugger(message); + } + isEnabled(name) { + return debug$2.enabled(`pw:${name}`); + } +} +const debugLogger = new DebugLogger(); +const kLogCount = 150; +class RecentLogsCollector { + constructor() { + this._logs = []; + } + log(message) { + this._logs.push(message); + if (this._logs.length === kLogCount * 2) + this._logs.splice(0, kLogCount); + } + recentLogs() { + if (this._logs.length > kLogCount) + return this._logs.slice(-150); + return this._logs; + } +} +function captureRawStack() { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 50; + const error2 = new Error(); + const stack = error2.stack || ""; + Error.stackTraceLimit = stackTraceLimit; + return stack.split("\n"); +} +function parseStackFrame(text, pathSeparator, showInternalStackFrames) { + const match = text && text.match(re); + if (!match) + return null; + let fname = match[2]; + let file = match[7]; + if (!file) + return null; + if (!showInternalStackFrames && (file.startsWith("internal") || file.startsWith("node:"))) + return null; + const line = match[8]; + const column = match[9]; + const closeParen = match[11] === ")"; + const frame = { + file: "", + line: 0, + column: 0 + }; + if (line) + frame.line = Number(line); + if (column) + frame.column = Number(column); + if (closeParen && file) { + let closes = 0; + for (let i = file.length - 1; i > 0; i--) { + if (file.charAt(i) === ")") { + closes++; + } else if (file.charAt(i) === "(" && file.charAt(i - 1) === " ") { + closes--; + if (closes === -1 && file.charAt(i - 1) === " ") { + const before = file.slice(0, i - 1); + const after = file.slice(i + 1); + file = after; + fname += ` (${before}`; + break; + } + } + } + } + if (fname) { + const methodMatch = fname.match(methodRe); + if (methodMatch) + fname = methodMatch[1]; + } + if (file) { + if (file.startsWith("file://")) + file = fileURLToPath(file, pathSeparator); + frame.file = file; + } + if (fname) + frame.function = fname; + return frame; +} +function rewriteErrorMessage(e, newMessage) { + var _a2; + const lines = (((_a2 = e.stack) == null ? void 0 : _a2.split("\n")) || []).filter((l) => l.startsWith(" at ")); + e.message = newMessage; + const errorTitle = `${e.name}: ${e.message}`; + if (lines.length) + e.stack = `${errorTitle} +${lines.join("\n")}`; + return e; +} +function stringifyStackFrames(frames) { + const stackLines = []; + for (const frame of frames) { + if (frame.function) + stackLines.push(` at ${frame.function} (${frame.file}:${frame.line}:${frame.column})`); + else + stackLines.push(` at ${frame.file}:${frame.line}:${frame.column}`); + } + return stackLines; +} +function splitErrorMessage(message) { + const separationIdx = message.indexOf(":"); + return { + name: separationIdx !== -1 ? message.slice(0, separationIdx) : "", + message: separationIdx !== -1 && separationIdx + 2 <= message.length ? message.substring(separationIdx + 2) : message + }; +} +const re = new RegExp( + "^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$" +); +const methodRe = /^(.*?) \[as (.*?)\]$/; +function fileURLToPath(fileUrl, pathSeparator) { + if (!fileUrl.startsWith("file://")) + return fileUrl; + let path2 = decodeURIComponent(fileUrl.slice(7)); + if (path2.startsWith("/") && /^[a-zA-Z]:/.test(path2.slice(1))) + path2 = path2.slice(1); + return path2.replace(/\//g, pathSeparator); +} +class ManualPromise extends Promise { + constructor() { + let resolve; + let reject; + super((f, r) => { + resolve = f; + reject = r; + }); + this._isDone = false; + this._resolve = resolve; + this._reject = reject; + } + isDone() { + return this._isDone; + } + resolve(t) { + this._isDone = true; + this._resolve(t); + } + reject(e) { + this._isDone = true; + this._reject(e); + } + static get [Symbol.species]() { + return Promise; + } + get [Symbol.toStringTag]() { + return "ManualPromise"; + } +} +class LongStandingScope { + constructor() { + this._terminatePromises = /* @__PURE__ */ new Map(); + this._isClosed = false; + } + reject(error2) { + this._isClosed = true; + this._terminateError = error2; + for (const p of this._terminatePromises.keys()) + p.resolve(error2); + } + close(error2) { + this._isClosed = true; + this._closeError = error2; + for (const [p, frames] of this._terminatePromises) + p.resolve(cloneError(error2, frames)); + } + isClosed() { + return this._isClosed; + } + static async raceMultiple(scopes, promise) { + return Promise.race(scopes.map((s) => s.race(promise))); + } + async race(promise) { + return this._race(Array.isArray(promise) ? promise : [promise], false); + } + async safeRace(promise, defaultValue) { + return this._race([promise], true, defaultValue); + } + async _race(promises2, safe2, defaultValue) { + const terminatePromise = new ManualPromise(); + const frames = captureRawStack(); + if (this._terminateError) + terminatePromise.resolve(this._terminateError); + if (this._closeError) + terminatePromise.resolve(cloneError(this._closeError, frames)); + this._terminatePromises.set(terminatePromise, frames); + try { + return await Promise.race([ + terminatePromise.then((e) => safe2 ? defaultValue : Promise.reject(e)), + ...promises2 + ]); + } finally { + this._terminatePromises.delete(terminatePromise); + } + } +} +function cloneError(error2, frames) { + const clone = new Error(); + clone.name = error2.name; + clone.message = error2.message; + clone.stack = [error2.name + ":" + error2.message, ...frames].join("\n"); + return clone; +} +const version$2 = "1.53.0"; +const require$$0$1 = { + version: version$2 +}; +let didFailToReadOSRelease = false; +let osRelease; +function getLinuxDistributionInfoSync() { + if (process.platform !== "linux") + return void 0; + if (!osRelease && !didFailToReadOSRelease) { + try { + const osReleaseText = fs.readFileSync("/etc/os-release", "utf8"); + const fields = parseOSReleaseText(osReleaseText); + osRelease = { + id: fields.get("id") ?? "", + version: fields.get("version_id") ?? "" + }; + } catch (e) { + didFailToReadOSRelease = true; + } + } + return osRelease; +} +function parseOSReleaseText(osReleaseText) { + const fields = /* @__PURE__ */ new Map(); + for (const line of osReleaseText.split("\n")) { + const tokens = line.split("="); + const name = tokens.shift(); + let value = tokens.join("=").trim(); + if (value.startsWith('"') && value.endsWith('"')) + value = value.substring(1, value.length - 1); + if (!name) + continue; + fields.set(name.toLowerCase(), value); + } + return fields; +} +let cachedUserAgent; +function getUserAgent() { + if (cachedUserAgent) + return cachedUserAgent; + try { + cachedUserAgent = determineUserAgent(); + } catch (e) { + cachedUserAgent = "Playwright/unknown"; + } + return cachedUserAgent; +} +function determineUserAgent() { + let osIdentifier = "unknown"; + let osVersion = "unknown"; + if (process.platform === "win32") { + const version2 = os.release().split("."); + osIdentifier = "windows"; + osVersion = `${version2[0]}.${version2[1]}`; + } else if (process.platform === "darwin") { + const version2 = execSync().toString().trim().split("."); + osIdentifier = "macOS"; + osVersion = `${version2[0]}.${version2[1]}`; + } else if (process.platform === "linux") { + const distroInfo = getLinuxDistributionInfoSync(); + if (distroInfo) { + osIdentifier = distroInfo.id || "linux"; + osVersion = distroInfo.version || "unknown"; + } else { + osIdentifier = "linux"; + } + } + const additionalTokens = []; + if (define_process_env_default.CI) + additionalTokens.push("CI/1"); + const serializedTokens = additionalTokens.length ? " " + additionalTokens.join(" ") : ""; + const { embedderName, embedderVersion } = getEmbedderName(); + return `Playwright/${getPlaywrightVersion()} (${os.arch()}; ${osIdentifier} ${osVersion}) ${embedderName}/${embedderVersion}${serializedTokens}`; +} +function getEmbedderName() { + let embedderName = "unknown"; + let embedderVersion = "unknown"; + if (!define_process_env_default.PW_LANG_NAME) { + embedderName = "node"; + embedderVersion = process.version.substring(1).split(".").slice(0, 2).join("."); + } else if (["node", "python", "java", "csharp"].includes(define_process_env_default.PW_LANG_NAME)) { + embedderName = define_process_env_default.PW_LANG_NAME; + embedderVersion = define_process_env_default.PW_LANG_NAME_VERSION ?? "unknown"; + } + return { embedderName, embedderVersion }; +} +function getPlaywrightVersion(majorMinorOnly = false) { + const version2 = define_process_env_default.PW_VERSION_OVERRIDE || require$$0$1.version; + return majorMinorOnly ? version2.split(".").slice(0, 2).join(".") : version2; +} +var getStream = { exports: {} }; +var once = { exports: {} }; +var wrappy_1; +var hasRequiredWrappy; +function requireWrappy() { + if (hasRequiredWrappy) return wrappy_1; + hasRequiredWrappy = 1; + wrappy_1 = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k) { + wrapper[k] = fn[k]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k) { + ret[k] = cb2[k]; + }); + } + return ret; + } + } + return wrappy_1; +} +var hasRequiredOnce; +function requireOnce() { + if (hasRequiredOnce) return once.exports; + hasRequiredOnce = 1; + var wrappy = requireWrappy(); + once.exports = wrappy(once$1); + once.exports.strict = wrappy(onceStrict); + once$1.proto = once$1(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once$1(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once$1(fn) { + var f = function() { + if (f.called) return f.value; + f.called = true; + return f.value = fn.apply(this, arguments); + }; + f.called = false; + return f; + } + function onceStrict(fn) { + var f = function() { + if (f.called) + throw new Error(f.onceError); + f.called = true; + return f.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f; + } + return once.exports; +} +var endOfStream$1; +var hasRequiredEndOfStream$1; +function requireEndOfStream$1() { + if (hasRequiredEndOfStream$1) return endOfStream$1; + hasRequiredEndOfStream$1 = 1; + var once2 = requireOnce(); + var noop2 = function() { + }; + var isRequest = function(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + }; + var isChildProcess = function(stream2) { + return stream2.stdio && Array.isArray(stream2.stdio) && stream2.stdio.length === 3; + }; + var eos = function(stream2, opts, callback) { + if (typeof opts === "function") return eos(stream2, null, opts); + if (!opts) opts = {}; + callback = once2(callback || noop2); + var ws2 = stream2._writableState; + var rs = stream2._readableState; + var readable2 = opts.readable || opts.readable !== false && stream2.readable; + var writable2 = opts.writable || opts.writable !== false && stream2.writable; + var cancelled = false; + var onlegacyfinish = function() { + if (!stream2.writable) onfinish(); + }; + var onfinish = function() { + writable2 = false; + if (!readable2) callback.call(stream2); + }; + var onend = function() { + readable2 = false; + if (!writable2) callback.call(stream2); + }; + var onexit = function(exitCode) { + callback.call(stream2, exitCode ? new Error("exited with error code: " + exitCode) : null); + }; + var onerror = function(err) { + callback.call(stream2, err); + }; + var onclose = function() { + process.nextTick(onclosenexttick); + }; + var onclosenexttick = function() { + if (cancelled) return; + if (readable2 && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream2, new Error("premature close")); + if (writable2 && !(ws2 && (ws2.ended && !ws2.destroyed))) return callback.call(stream2, new Error("premature close")); + }; + var onrequest = function() { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + stream2.on("abort", onclose); + if (stream2.req) onrequest(); + else stream2.on("request", onrequest); + } else if (writable2 && !ws2) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + if (isChildProcess(stream2)) stream2.on("exit", onexit); + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (opts.error !== false) stream2.on("error", onerror); + stream2.on("close", onclose); + return function() { + cancelled = true; + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("exit", onexit); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.removeListener("close", onclose); + }; + }; + endOfStream$1 = eos; + return endOfStream$1; +} +var pump_1; +var hasRequiredPump; +function requirePump() { + if (hasRequiredPump) return pump_1; + hasRequiredPump = 1; + var once2 = requireOnce(); + var eos = requireEndOfStream$1(); + var fs2; + try { + fs2 = require$$2$1; + } catch (e) { + } + var noop2 = function() { + }; + var ancient = /^v?\.0/.test(process.version); + var isFn = function(fn) { + return typeof fn === "function"; + }; + var isFS = function(stream2) { + if (!ancient) return false; + if (!fs2) return false; + return (stream2 instanceof (fs2.ReadStream || noop2) || stream2 instanceof (fs2.WriteStream || noop2)) && isFn(stream2.close); + }; + var isRequest = function(stream2) { + return stream2.setHeader && isFn(stream2.abort); + }; + var destroyer = function(stream2, reading, writing, callback) { + callback = once2(callback); + var closed = false; + stream2.on("close", function() { + closed = true; + }); + eos(stream2, { readable: reading, writable: writing }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isFS(stream2)) return stream2.close(noop2); + if (isRequest(stream2)) return stream2.abort(); + if (isFn(stream2.destroy)) return stream2.destroy(); + callback(err || new Error("stream was destroyed")); + }; + }; + var call = function(fn) { + fn(); + }; + var pipe = function(from2, to) { + return from2.pipe(to); + }; + var pump = function() { + var streams = Array.prototype.slice.call(arguments); + var callback = isFn(streams[streams.length - 1] || noop2) && streams.pop() || noop2; + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) throw new Error("pump requires two streams per minimum"); + var error2; + var destroys = streams.map(function(stream2, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream2, reading, writing, function(err) { + if (!error2) error2 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error2); + }); + }); + return streams.reduce(pipe); + }; + pump_1 = pump; + return pump_1; +} +var bufferStream; +var hasRequiredBufferStream; +function requireBufferStream() { + if (hasRequiredBufferStream) return bufferStream; + hasRequiredBufferStream = 1; + const { PassThrough: PassThroughStream } = requireBrowser$h(); + bufferStream = (options2) => { + options2 = { ...options2 }; + const { array } = options2; + let { encoding: encoding2 } = options2; + const isBuffer = encoding2 === "buffer"; + let objectMode = false; + if (array) { + objectMode = !(encoding2 || isBuffer); + } else { + encoding2 = encoding2 || "utf8"; + } + if (isBuffer) { + encoding2 = null; + } + const stream2 = new PassThroughStream({ objectMode }); + if (encoding2) { + stream2.setEncoding(encoding2); + } + let length = 0; + const chunks = []; + stream2.on("data", (chunk) => { + chunks.push(chunk); + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + stream2.getBufferedValue = () => { + if (array) { + return chunks; + } + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(""); + }; + stream2.getBufferedLength = () => length; + return stream2; + }; + return bufferStream; +} +var hasRequiredGetStream; +function requireGetStream() { + if (hasRequiredGetStream) return getStream.exports; + hasRequiredGetStream = 1; + const { constants: BufferConstants } = requireBuffer$2(); + const pump = requirePump(); + const bufferStream2 = requireBufferStream(); + class MaxBufferError extends Error { + constructor() { + super("maxBuffer exceeded"); + this.name = "MaxBufferError"; + } + } + async function getStream$1(inputStream, options2) { + if (!inputStream) { + return Promise.reject(new Error("Expected a stream")); + } + options2 = { + maxBuffer: Infinity, + ...options2 + }; + const { maxBuffer } = options2; + let stream2; + await new Promise((resolve, reject) => { + const rejectPromise = (error2) => { + if (error2 && stream2.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error2.bufferedData = stream2.getBufferedValue(); + } + reject(error2); + }; + stream2 = pump(inputStream, bufferStream2(options2), (error2) => { + if (error2) { + rejectPromise(error2); + return; + } + resolve(); + }); + stream2.on("data", () => { + if (stream2.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + return stream2.getBufferedValue(); + } + getStream.exports = getStream$1; + getStream.exports.default = getStream$1; + getStream.exports.buffer = (stream2, options2) => getStream$1(stream2, { ...options2, encoding: "buffer" }); + getStream.exports.array = (stream2, options2) => getStream$1(stream2, { ...options2, array: true }); + getStream.exports.MaxBufferError = MaxBufferError; + return getStream.exports; +} +var yauzl$1 = {}; +var fdSlicer = {}; +var pend; +var hasRequiredPend; +function requirePend() { + if (hasRequiredPend) return pend; + hasRequiredPend = 1; + pend = Pend; + function Pend() { + this.pending = 0; + this.max = Infinity; + this.listeners = []; + this.waiting = []; + this.error = null; + } + Pend.prototype.go = function(fn) { + if (this.pending < this.max) { + pendGo(this, fn); + } else { + this.waiting.push(fn); + } + }; + Pend.prototype.wait = function(cb) { + if (this.pending === 0) { + cb(this.error); + } else { + this.listeners.push(cb); + } + }; + Pend.prototype.hold = function() { + return pendHold(this); + }; + function pendHold(self2) { + self2.pending += 1; + var called = false; + return onCb; + function onCb(err) { + if (called) throw new Error("callback called twice"); + called = true; + self2.error = self2.error || err; + self2.pending -= 1; + if (self2.waiting.length > 0 && self2.pending < self2.max) { + pendGo(self2, self2.waiting.shift()); + } else if (self2.pending === 0) { + var listeners = self2.listeners; + self2.listeners = []; + listeners.forEach(cbListener); + } + } + function cbListener(listener) { + listener(self2.error); + } + } + function pendGo(self2, fn) { + fn(pendHold(self2)); + } + return pend; +} +var hasRequiredFdSlicer; +function requireFdSlicer() { + if (hasRequiredFdSlicer) return fdSlicer; + hasRequiredFdSlicer = 1; + var fs2 = require$$2$1; + var util2 = requireUtil$5(); + var stream2 = requireBrowser$h(); + var Readable = stream2.Readable; + var Writable = stream2.Writable; + var PassThrough = stream2.PassThrough; + var Pend = requirePend(); + var EventEmitter2 = requireEvents().EventEmitter; + fdSlicer.createFromBuffer = createFromBuffer; + fdSlicer.createFromFd = createFromFd; + fdSlicer.BufferSlicer = BufferSlicer; + fdSlicer.FdSlicer = FdSlicer; + util2.inherits(FdSlicer, EventEmitter2); + function FdSlicer(fd, options2) { + options2 = options2 || {}; + EventEmitter2.call(this); + this.fd = fd; + this.pend = new Pend(); + this.pend.max = 1; + this.refCount = 0; + this.autoClose = !!options2.autoClose; + } + FdSlicer.prototype.read = function(buffer2, offset2, length, position, callback) { + var self2 = this; + self2.pend.go(function(cb) { + fs2.read(self2.fd, buffer2, offset2, length, position, function(err, bytesRead, buffer3) { + cb(); + callback(err, bytesRead, buffer3); + }); + }); + }; + FdSlicer.prototype.write = function(buffer2, offset2, length, position, callback) { + var self2 = this; + self2.pend.go(function(cb) { + fs2.write(self2.fd, buffer2, offset2, length, position, function(err, written, buffer3) { + cb(); + callback(err, written, buffer3); + }); + }); + }; + FdSlicer.prototype.createReadStream = function(options2) { + return new ReadStream2(this, options2); + }; + FdSlicer.prototype.createWriteStream = function(options2) { + return new WriteStream2(this, options2); + }; + FdSlicer.prototype.ref = function() { + this.refCount += 1; + }; + FdSlicer.prototype.unref = function() { + var self2 = this; + self2.refCount -= 1; + if (self2.refCount > 0) return; + if (self2.refCount < 0) throw new Error("invalid unref"); + if (self2.autoClose) { + fs2.close(self2.fd, onCloseDone); + } + function onCloseDone(err) { + if (err) { + self2.emit("error", err); + } else { + self2.emit("close"); + } + } + }; + util2.inherits(ReadStream2, Readable); + function ReadStream2(context, options2) { + options2 = options2 || {}; + Readable.call(this, options2); + this.context = context; + this.context.ref(); + this.start = options2.start || 0; + this.endOffset = options2.end; + this.pos = this.start; + this.destroyed = false; + } + ReadStream2.prototype._read = function(n) { + var self2 = this; + if (self2.destroyed) return; + var toRead = Math.min(self2._readableState.highWaterMark, n); + if (self2.endOffset != null) { + toRead = Math.min(toRead, self2.endOffset - self2.pos); + } + if (toRead <= 0) { + self2.destroyed = true; + self2.push(null); + self2.context.unref(); + return; + } + self2.context.pend.go(function(cb) { + if (self2.destroyed) return cb(); + var buffer2 = Buffer.allocUnsafe(toRead); + fs2.read(self2.context.fd, buffer2, 0, toRead, self2.pos, function(err, bytesRead) { + if (err) { + self2.destroy(err); + } else if (bytesRead === 0) { + self2.destroyed = true; + self2.push(null); + self2.context.unref(); + } else { + self2.pos += bytesRead; + self2.push(buffer2.slice(0, bytesRead)); + } + cb(); + }); + }); + }; + ReadStream2.prototype.destroy = function(err) { + if (this.destroyed) return; + err = err || new Error("stream destroyed"); + this.destroyed = true; + this.emit("error", err); + this.context.unref(); + }; + util2.inherits(WriteStream2, Writable); + function WriteStream2(context, options2) { + options2 = options2 || {}; + Writable.call(this, options2); + this.context = context; + this.context.ref(); + this.start = options2.start || 0; + this.endOffset = options2.end == null ? Infinity : +options2.end; + this.bytesWritten = 0; + this.pos = this.start; + this.destroyed = false; + this.on("finish", this.destroy.bind(this)); + } + WriteStream2.prototype._write = function(buffer2, encoding2, callback) { + var self2 = this; + if (self2.destroyed) return; + if (self2.pos + buffer2.length > self2.endOffset) { + var err = new Error("maximum file length exceeded"); + err.code = "ETOOBIG"; + self2.destroy(); + callback(err); + return; + } + self2.context.pend.go(function(cb) { + if (self2.destroyed) return cb(); + fs2.write(self2.context.fd, buffer2, 0, buffer2.length, self2.pos, function(err2, bytes) { + if (err2) { + self2.destroy(); + cb(); + callback(err2); + } else { + self2.bytesWritten += bytes; + self2.pos += bytes; + self2.emit("progress"); + cb(); + callback(); + } + }); + }); + }; + WriteStream2.prototype.destroy = function() { + if (this.destroyed) return; + this.destroyed = true; + this.context.unref(); + }; + util2.inherits(BufferSlicer, EventEmitter2); + function BufferSlicer(buffer2, options2) { + EventEmitter2.call(this); + options2 = options2 || {}; + this.refCount = 0; + this.buffer = buffer2; + this.maxChunkSize = options2.maxChunkSize || Number.MAX_SAFE_INTEGER; + } + BufferSlicer.prototype.read = function(buffer2, offset2, length, position, callback) { + if (!(0 <= offset2 && offset2 <= buffer2.length)) throw new RangeError("offset outside buffer: 0 <= " + offset2 + " <= " + buffer2.length); + if (position < 0) throw new RangeError("position is negative: " + position); + if (offset2 + length > buffer2.length) { + length = buffer2.length - offset2; + } + if (position + length > this.buffer.length) { + length = this.buffer.length - position; + } + if (length <= 0) { + setImmediate(function() { + callback(null, 0); + }); + return; + } + this.buffer.copy(buffer2, offset2, position, position + length); + setImmediate(function() { + callback(null, length); + }); + }; + BufferSlicer.prototype.write = function(buffer2, offset2, length, position, callback) { + buffer2.copy(this.buffer, position, offset2, offset2 + length); + setImmediate(function() { + callback(null, length, buffer2); + }); + }; + BufferSlicer.prototype.createReadStream = function(options2) { + options2 = options2 || {}; + var readStream = new PassThrough(options2); + readStream.destroyed = false; + readStream.start = options2.start || 0; + readStream.endOffset = options2.end; + readStream.pos = readStream.endOffset || this.buffer.length; + var entireSlice = this.buffer.slice(readStream.start, readStream.pos); + var offset2 = 0; + while (true) { + var nextOffset = offset2 + this.maxChunkSize; + if (nextOffset >= entireSlice.length) { + if (offset2 < entireSlice.length) { + readStream.write(entireSlice.slice(offset2, entireSlice.length)); + } + break; + } + readStream.write(entireSlice.slice(offset2, nextOffset)); + offset2 = nextOffset; + } + readStream.end(); + readStream.destroy = function() { + readStream.destroyed = true; + }; + return readStream; + }; + BufferSlicer.prototype.createWriteStream = function(options2) { + var bufferSlicer = this; + options2 = options2 || {}; + var writeStream = new Writable(options2); + writeStream.start = options2.start || 0; + writeStream.endOffset = options2.end == null ? this.buffer.length : +options2.end; + writeStream.bytesWritten = 0; + writeStream.pos = writeStream.start; + writeStream.destroyed = false; + writeStream._write = function(buffer2, encoding2, callback) { + if (writeStream.destroyed) return; + var end = writeStream.pos + buffer2.length; + if (end > writeStream.endOffset) { + var err = new Error("maximum file length exceeded"); + err.code = "ETOOBIG"; + writeStream.destroyed = true; + callback(err); + return; + } + buffer2.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer2.length); + writeStream.bytesWritten += buffer2.length; + writeStream.pos = end; + writeStream.emit("progress"); + callback(); + }; + writeStream.destroy = function() { + writeStream.destroyed = true; + }; + return writeStream; + }; + BufferSlicer.prototype.ref = function() { + this.refCount += 1; + }; + BufferSlicer.prototype.unref = function() { + this.refCount -= 1; + if (this.refCount < 0) { + throw new Error("invalid unref"); + } + }; + function createFromBuffer(buffer2, options2) { + return new BufferSlicer(buffer2, options2); + } + function createFromFd(fd, options2) { + return new FdSlicer(fd, options2); + } + return fdSlicer; +} +var bufferCrc32; +var hasRequiredBufferCrc32; +function requireBufferCrc32() { + if (hasRequiredBufferCrc32) return bufferCrc32; + hasRequiredBufferCrc32 = 1; + var Buffer2 = requireBuffer$2().Buffer; + var CRC_TABLE = [ + 0, + 1996959894, + 3993919788, + 2567524794, + 124634137, + 1886057615, + 3915621685, + 2657392035, + 249268274, + 2044508324, + 3772115230, + 2547177864, + 162941995, + 2125561021, + 3887607047, + 2428444049, + 498536548, + 1789927666, + 4089016648, + 2227061214, + 450548861, + 1843258603, + 4107580753, + 2211677639, + 325883990, + 1684777152, + 4251122042, + 2321926636, + 335633487, + 1661365465, + 4195302755, + 2366115317, + 997073096, + 1281953886, + 3579855332, + 2724688242, + 1006888145, + 1258607687, + 3524101629, + 2768942443, + 901097722, + 1119000684, + 3686517206, + 2898065728, + 853044451, + 1172266101, + 3705015759, + 2882616665, + 651767980, + 1373503546, + 3369554304, + 3218104598, + 565507253, + 1454621731, + 3485111705, + 3099436303, + 671266974, + 1594198024, + 3322730930, + 2970347812, + 795835527, + 1483230225, + 3244367275, + 3060149565, + 1994146192, + 31158534, + 2563907772, + 4023717930, + 1907459465, + 112637215, + 2680153253, + 3904427059, + 2013776290, + 251722036, + 2517215374, + 3775830040, + 2137656763, + 141376813, + 2439277719, + 3865271297, + 1802195444, + 476864866, + 2238001368, + 4066508878, + 1812370925, + 453092731, + 2181625025, + 4111451223, + 1706088902, + 314042704, + 2344532202, + 4240017532, + 1658658271, + 366619977, + 2362670323, + 4224994405, + 1303535960, + 984961486, + 2747007092, + 3569037538, + 1256170817, + 1037604311, + 2765210733, + 3554079995, + 1131014506, + 879679996, + 2909243462, + 3663771856, + 1141124467, + 855842277, + 2852801631, + 3708648649, + 1342533948, + 654459306, + 3188396048, + 3373015174, + 1466479909, + 544179635, + 3110523913, + 3462522015, + 1591671054, + 702138776, + 2966460450, + 3352799412, + 1504918807, + 783551873, + 3082640443, + 3233442989, + 3988292384, + 2596254646, + 62317068, + 1957810842, + 3939845945, + 2647816111, + 81470997, + 1943803523, + 3814918930, + 2489596804, + 225274430, + 2053790376, + 3826175755, + 2466906013, + 167816743, + 2097651377, + 4027552580, + 2265490386, + 503444072, + 1762050814, + 4150417245, + 2154129355, + 426522225, + 1852507879, + 4275313526, + 2312317920, + 282753626, + 1742555852, + 4189708143, + 2394877945, + 397917763, + 1622183637, + 3604390888, + 2714866558, + 953729732, + 1340076626, + 3518719985, + 2797360999, + 1068828381, + 1219638859, + 3624741850, + 2936675148, + 906185462, + 1090812512, + 3747672003, + 2825379669, + 829329135, + 1181335161, + 3412177804, + 3160834842, + 628085408, + 1382605366, + 3423369109, + 3138078467, + 570562233, + 1426400815, + 3317316542, + 2998733608, + 733239954, + 1555261956, + 3268935591, + 3050360625, + 752459403, + 1541320221, + 2607071920, + 3965973030, + 1969922972, + 40735498, + 2617837225, + 3943577151, + 1913087877, + 83908371, + 2512341634, + 3803740692, + 2075208622, + 213261112, + 2463272603, + 3855990285, + 2094854071, + 198958881, + 2262029012, + 4057260610, + 1759359992, + 534414190, + 2176718541, + 4139329115, + 1873836001, + 414664567, + 2282248934, + 4279200368, + 1711684554, + 285281116, + 2405801727, + 4167216745, + 1634467795, + 376229701, + 2685067896, + 3608007406, + 1308918612, + 956543938, + 2808555105, + 3495958263, + 1231636301, + 1047427035, + 2932959818, + 3654703836, + 1088359270, + 936918e3, + 2847714899, + 3736837829, + 1202900863, + 817233897, + 3183342108, + 3401237130, + 1404277552, + 615818150, + 3134207493, + 3453421203, + 1423857449, + 601450431, + 3009837614, + 3294710456, + 1567103746, + 711928724, + 3020668471, + 3272380065, + 1510334235, + 755167117 + ]; + if (typeof Int32Array !== "undefined") { + CRC_TABLE = new Int32Array(CRC_TABLE); + } + function ensureBuffer(input) { + if (Buffer2.isBuffer(input)) { + return input; + } + var hasNewBufferAPI = typeof Buffer2.alloc === "function" && typeof Buffer2.from === "function"; + if (typeof input === "number") { + return hasNewBufferAPI ? Buffer2.alloc(input) : new Buffer2(input); + } else if (typeof input === "string") { + return hasNewBufferAPI ? Buffer2.from(input) : new Buffer2(input); + } else { + throw new Error("input must be buffer, number, or string, received " + typeof input); + } + } + function bufferizeInt(num) { + var tmp = ensureBuffer(4); + tmp.writeInt32BE(num, 0); + return tmp; + } + function _crc32(buf, previous) { + buf = ensureBuffer(buf); + if (Buffer2.isBuffer(previous)) { + previous = previous.readUInt32BE(0); + } + var crc2 = ~~previous ^ -1; + for (var n = 0; n < buf.length; n++) { + crc2 = CRC_TABLE[(crc2 ^ buf[n]) & 255] ^ crc2 >>> 8; + } + return crc2 ^ -1; + } + function crc32() { + return bufferizeInt(_crc32.apply(null, arguments)); + } + crc32.signed = function() { + return _crc32.apply(null, arguments); + }; + crc32.unsigned = function() { + return _crc32.apply(null, arguments) >>> 0; + }; + bufferCrc32 = crc32; + return bufferCrc32; +} +var hasRequiredYauzl; +function requireYauzl() { + if (hasRequiredYauzl) return yauzl$1; + hasRequiredYauzl = 1; + var fs2 = require$$2$1; + var zlib = requireLib(); + var fd_slicer = requireFdSlicer(); + var crc32 = requireBufferCrc32(); + var util2 = requireUtil$5(); + var EventEmitter2 = requireEvents().EventEmitter; + var Transform = requireBrowser$h().Transform; + var PassThrough = requireBrowser$h().PassThrough; + var Writable = requireBrowser$h().Writable; + yauzl$1.open = open2; + yauzl$1.fromFd = fromFd; + yauzl$1.fromBuffer = fromBuffer; + yauzl$1.fromRandomAccessReader = fromRandomAccessReader; + yauzl$1.dosDateTimeToDate = dosDateTimeToDate; + yauzl$1.getFileNameLowLevel = getFileNameLowLevel; + yauzl$1.validateFileName = validateFileName; + yauzl$1.parseExtraFields = parseExtraFields; + yauzl$1.ZipFile = ZipFile2; + yauzl$1.Entry = Entry; + yauzl$1.LocalFileHeader = LocalFileHeader; + yauzl$1.RandomAccessReader = RandomAccessReader; + function open2(path2, options2, callback) { + if (typeof options2 === "function") { + callback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + if (options2.autoClose == null) options2.autoClose = true; + if (options2.lazyEntries == null) options2.lazyEntries = false; + if (options2.decodeStrings == null) options2.decodeStrings = true; + if (options2.validateEntrySizes == null) options2.validateEntrySizes = true; + if (options2.strictFileNames == null) options2.strictFileNames = false; + if (callback == null) callback = defaultCallback; + fs2.open(path2, "r", function(err, fd) { + if (err) return callback(err); + fromFd(fd, options2, function(err2, zipfile) { + if (err2) fs2.close(fd, defaultCallback); + callback(err2, zipfile); + }); + }); + } + function fromFd(fd, options2, callback) { + if (typeof options2 === "function") { + callback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + if (options2.autoClose == null) options2.autoClose = false; + if (options2.lazyEntries == null) options2.lazyEntries = false; + if (options2.decodeStrings == null) options2.decodeStrings = true; + if (options2.validateEntrySizes == null) options2.validateEntrySizes = true; + if (options2.strictFileNames == null) options2.strictFileNames = false; + if (callback == null) callback = defaultCallback; + fs2.fstat(fd, function(err, stats) { + if (err) return callback(err); + var reader = fd_slicer.createFromFd(fd, { autoClose: true }); + fromRandomAccessReader(reader, stats.size, options2, callback); + }); + } + function fromBuffer(buffer2, options2, callback) { + if (typeof options2 === "function") { + callback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + options2.autoClose = false; + if (options2.lazyEntries == null) options2.lazyEntries = false; + if (options2.decodeStrings == null) options2.decodeStrings = true; + if (options2.validateEntrySizes == null) options2.validateEntrySizes = true; + if (options2.strictFileNames == null) options2.strictFileNames = false; + var reader = fd_slicer.createFromBuffer(buffer2, { maxChunkSize: 65536 }); + fromRandomAccessReader(reader, buffer2.length, options2, callback); + } + function fromRandomAccessReader(reader, totalSize, options2, callback) { + if (typeof options2 === "function") { + callback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + if (options2.autoClose == null) options2.autoClose = true; + if (options2.lazyEntries == null) options2.lazyEntries = false; + if (options2.decodeStrings == null) options2.decodeStrings = true; + var decodeStrings = !!options2.decodeStrings; + if (options2.validateEntrySizes == null) options2.validateEntrySizes = true; + if (options2.strictFileNames == null) options2.strictFileNames = false; + if (callback == null) callback = defaultCallback; + if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number"); + if (totalSize > Number.MAX_SAFE_INTEGER) { + throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double."); + } + reader.ref(); + var eocdrWithoutCommentSize = 22; + var zip64EocdlSize = 20; + var maxCommentSize = 65535; + var bufferSize = Math.min(zip64EocdlSize + eocdrWithoutCommentSize + maxCommentSize, totalSize); + var buffer2 = newBuffer(bufferSize); + var bufferReadStart = totalSize - buffer2.length; + readAndAssertNoEof(reader, buffer2, 0, bufferSize, bufferReadStart, function(err) { + if (err) return callback(err); + for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) { + if (buffer2.readUInt32LE(i) !== 101010256) continue; + var eocdrBuffer = buffer2.subarray(i); + var diskNumber = eocdrBuffer.readUInt16LE(4); + var entryCount = eocdrBuffer.readUInt16LE(10); + var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16); + var commentLength = eocdrBuffer.readUInt16LE(20); + var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize; + if (commentLength !== expectedCommentLength) { + return callback(new Error("Invalid comment length. Expected: " + expectedCommentLength + ". Found: " + commentLength + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?")); + } + var comment2 = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22); + if (i - zip64EocdlSize >= 0 && buffer2.readUInt32LE(i - zip64EocdlSize) === 117853008) { + var zip64EocdlBuffer = buffer2.subarray(i - zip64EocdlSize, i - zip64EocdlSize + zip64EocdlSize); + var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8); + var zip64EocdrBuffer = newBuffer(56); + return readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err2) { + if (err2) return callback(err2); + if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) { + return callback(new Error("invalid zip64 end of central directory record signature")); + } + diskNumber = zip64EocdrBuffer.readUInt32LE(16); + if (diskNumber !== 0) { + return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber)); + } + entryCount = readUInt64LE(zip64EocdrBuffer, 32); + centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48); + return callback(null, new ZipFile2(reader, centralDirectoryOffset, totalSize, entryCount, comment2, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames)); + }); + } + if (diskNumber !== 0) { + return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber)); + } + return callback(null, new ZipFile2(reader, centralDirectoryOffset, totalSize, entryCount, comment2, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames)); + } + callback(new Error("End of central directory record signature not found. Either not a zip file, or file is truncated.")); + }); + } + util2.inherits(ZipFile2, EventEmitter2); + function ZipFile2(reader, centralDirectoryOffset, fileSize, entryCount, comment2, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) { + var self2 = this; + EventEmitter2.call(self2); + self2.reader = reader; + self2.reader.on("error", function(err) { + emitError(self2, err); + }); + self2.reader.once("close", function() { + self2.emit("close"); + }); + self2.readEntryCursor = centralDirectoryOffset; + self2.fileSize = fileSize; + self2.entryCount = entryCount; + self2.comment = comment2; + self2.entriesRead = 0; + self2.autoClose = !!autoClose; + self2.lazyEntries = !!lazyEntries; + self2.decodeStrings = !!decodeStrings; + self2.validateEntrySizes = !!validateEntrySizes; + self2.strictFileNames = !!strictFileNames; + self2.isOpen = true; + self2.emittedError = false; + if (!self2.lazyEntries) self2._readEntry(); + } + ZipFile2.prototype.close = function() { + if (!this.isOpen) return; + this.isOpen = false; + this.reader.unref(); + }; + function emitErrorAndAutoClose(self2, err) { + if (self2.autoClose) self2.close(); + emitError(self2, err); + } + function emitError(self2, err) { + if (self2.emittedError) return; + self2.emittedError = true; + self2.emit("error", err); + } + ZipFile2.prototype.readEntry = function() { + if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true"); + this._readEntry(); + }; + ZipFile2.prototype._readEntry = function() { + var self2 = this; + if (self2.entryCount === self2.entriesRead) { + setImmediate(function() { + if (self2.autoClose) self2.close(); + if (self2.emittedError) return; + self2.emit("end"); + }); + return; + } + if (self2.emittedError) return; + var buffer2 = newBuffer(46); + readAndAssertNoEof(self2.reader, buffer2, 0, buffer2.length, self2.readEntryCursor, function(err) { + if (err) return emitErrorAndAutoClose(self2, err); + if (self2.emittedError) return; + var entry = new Entry(); + var signature2 = buffer2.readUInt32LE(0); + if (signature2 !== 33639248) return emitErrorAndAutoClose(self2, new Error("invalid central directory file header signature: 0x" + signature2.toString(16))); + entry.versionMadeBy = buffer2.readUInt16LE(4); + entry.versionNeededToExtract = buffer2.readUInt16LE(6); + entry.generalPurposeBitFlag = buffer2.readUInt16LE(8); + entry.compressionMethod = buffer2.readUInt16LE(10); + entry.lastModFileTime = buffer2.readUInt16LE(12); + entry.lastModFileDate = buffer2.readUInt16LE(14); + entry.crc32 = buffer2.readUInt32LE(16); + entry.compressedSize = buffer2.readUInt32LE(20); + entry.uncompressedSize = buffer2.readUInt32LE(24); + entry.fileNameLength = buffer2.readUInt16LE(28); + entry.extraFieldLength = buffer2.readUInt16LE(30); + entry.fileCommentLength = buffer2.readUInt16LE(32); + entry.internalFileAttributes = buffer2.readUInt16LE(36); + entry.externalFileAttributes = buffer2.readUInt32LE(38); + entry.relativeOffsetOfLocalHeader = buffer2.readUInt32LE(42); + if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self2, new Error("strong encryption is not supported")); + self2.readEntryCursor += 46; + buffer2 = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength); + readAndAssertNoEof(self2.reader, buffer2, 0, buffer2.length, self2.readEntryCursor, function(err2) { + if (err2) return emitErrorAndAutoClose(self2, err2); + if (self2.emittedError) return; + entry.fileNameRaw = buffer2.subarray(0, entry.fileNameLength); + var fileCommentStart = entry.fileNameLength + entry.extraFieldLength; + entry.extraFieldRaw = buffer2.subarray(entry.fileNameLength, fileCommentStart); + entry.fileCommentRaw = buffer2.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength); + try { + entry.extraFields = parseExtraFields(entry.extraFieldRaw); + } catch (err3) { + return emitErrorAndAutoClose(self2, err3); + } + if (self2.decodeStrings) { + var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0; + entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8); + entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self2.strictFileNames); + var errorMessage = validateFileName(entry.fileName); + if (errorMessage != null) return emitErrorAndAutoClose(self2, new Error(errorMessage)); + } else { + entry.fileComment = entry.fileCommentRaw; + entry.fileName = entry.fileNameRaw; + } + entry.comment = entry.fileComment; + self2.readEntryCursor += buffer2.length; + self2.entriesRead += 1; + for (var i = 0; i < entry.extraFields.length; i++) { + var extraField = entry.extraFields[i]; + if (extraField.id !== 1) continue; + var zip64EiefBuffer = extraField.data; + var index2 = 0; + if (entry.uncompressedSize === 4294967295) { + if (index2 + 8 > zip64EiefBuffer.length) { + return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include uncompressed size")); + } + entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index2); + index2 += 8; + } + if (entry.compressedSize === 4294967295) { + if (index2 + 8 > zip64EiefBuffer.length) { + return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include compressed size")); + } + entry.compressedSize = readUInt64LE(zip64EiefBuffer, index2); + index2 += 8; + } + if (entry.relativeOffsetOfLocalHeader === 4294967295) { + if (index2 + 8 > zip64EiefBuffer.length) { + return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include relative header offset")); + } + entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index2); + index2 += 8; + } + break; + } + if (self2.validateEntrySizes && entry.compressionMethod === 0) { + var expectedCompressedSize = entry.uncompressedSize; + if (entry.isEncrypted()) { + expectedCompressedSize += 12; + } + if (entry.compressedSize !== expectedCompressedSize) { + var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize; + return emitErrorAndAutoClose(self2, new Error(msg)); + } + } + self2.emit("entry", entry); + if (!self2.lazyEntries) self2._readEntry(); + }); + }); + }; + ZipFile2.prototype.openReadStream = function(entry, options2, callback) { + var self2 = this; + var relativeStart = 0; + var relativeEnd = entry.compressedSize; + if (callback == null) { + callback = options2; + options2 = null; + } + if (options2 == null) { + options2 = {}; + } else { + if (options2.decrypt != null) { + if (!entry.isEncrypted()) { + throw new Error("options.decrypt can only be specified for encrypted entries"); + } + if (options2.decrypt !== false) throw new Error("invalid options.decrypt value: " + options2.decrypt); + if (entry.isCompressed()) { + if (options2.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false"); + } + } + if (options2.decompress != null) { + if (!entry.isCompressed()) { + throw new Error("options.decompress can only be specified for compressed entries"); + } + if (!(options2.decompress === false || options2.decompress === true)) { + throw new Error("invalid options.decompress value: " + options2.decompress); + } + } + if (options2.start != null || options2.end != null) { + if (entry.isCompressed() && options2.decompress !== false) { + throw new Error("start/end range not allowed for compressed entry without options.decompress === false"); + } + if (entry.isEncrypted() && options2.decrypt !== false) { + throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false"); + } + } + if (options2.start != null) { + relativeStart = options2.start; + if (relativeStart < 0) throw new Error("options.start < 0"); + if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize"); + } + if (options2.end != null) { + relativeEnd = options2.end; + if (relativeEnd < 0) throw new Error("options.end < 0"); + if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize"); + if (relativeEnd < relativeStart) throw new Error("options.end < options.start"); + } + } + if (!self2.isOpen) return callback(new Error("closed")); + if (entry.isEncrypted()) { + if (options2.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false")); + } + var decompress; + if (entry.compressionMethod === 0) { + decompress = false; + } else if (entry.compressionMethod === 8) { + decompress = options2.decompress != null ? options2.decompress : true; + } else { + return callback(new Error("unsupported compression method: " + entry.compressionMethod)); + } + self2.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) { + if (err) return callback(err); + self2.openReadStreamLowLevel( + localFileHeader.fileDataStart, + entry.compressedSize, + relativeStart, + relativeEnd, + decompress, + entry.uncompressedSize, + callback + ); + }); + }; + ZipFile2.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) { + var self2 = this; + var readStream = self2.reader.createReadStream({ + start: fileDataStart + relativeStart, + end: fileDataStart + relativeEnd + }); + var endpointStream = readStream; + if (decompress) { + var destroyed = false; + var inflateFilter = zlib.createInflateRaw(); + readStream.on("error", function(err) { + setImmediate(function() { + if (!destroyed) inflateFilter.emit("error", err); + }); + }); + readStream.pipe(inflateFilter); + if (self2.validateEntrySizes) { + endpointStream = new AssertByteCountStream(uncompressedSize); + inflateFilter.on("error", function(err) { + setImmediate(function() { + if (!destroyed) endpointStream.emit("error", err); + }); + }); + inflateFilter.pipe(endpointStream); + } else { + endpointStream = inflateFilter; + } + installDestroyFn(endpointStream, function() { + destroyed = true; + if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream); + readStream.unpipe(inflateFilter); + readStream.destroy(); + }); + } + callback(null, endpointStream); + }; + ZipFile2.prototype.readLocalFileHeader = function(entry, options2, callback) { + var self2 = this; + if (callback == null) { + callback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + self2.reader.ref(); + var buffer2 = newBuffer(30); + readAndAssertNoEof(self2.reader, buffer2, 0, buffer2.length, entry.relativeOffsetOfLocalHeader, function(err) { + try { + if (err) return callback(err); + var signature2 = buffer2.readUInt32LE(0); + if (signature2 !== 67324752) { + return callback(new Error("invalid local file header signature: 0x" + signature2.toString(16))); + } + var fileNameLength = buffer2.readUInt16LE(26); + var extraFieldLength = buffer2.readUInt16LE(28); + var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength; + if (fileDataStart + entry.compressedSize > self2.fileSize) { + return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self2.fileSize)); + } + if (options2.minimal) { + return callback(null, { fileDataStart }); + } + var localFileHeader = new LocalFileHeader(); + localFileHeader.fileDataStart = fileDataStart; + localFileHeader.versionNeededToExtract = buffer2.readUInt16LE(4); + localFileHeader.generalPurposeBitFlag = buffer2.readUInt16LE(6); + localFileHeader.compressionMethod = buffer2.readUInt16LE(8); + localFileHeader.lastModFileTime = buffer2.readUInt16LE(10); + localFileHeader.lastModFileDate = buffer2.readUInt16LE(12); + localFileHeader.crc32 = buffer2.readUInt32LE(14); + localFileHeader.compressedSize = buffer2.readUInt32LE(18); + localFileHeader.uncompressedSize = buffer2.readUInt32LE(22); + localFileHeader.fileNameLength = fileNameLength; + localFileHeader.extraFieldLength = extraFieldLength; + buffer2 = newBuffer(fileNameLength + extraFieldLength); + self2.reader.ref(); + readAndAssertNoEof(self2.reader, buffer2, 0, buffer2.length, entry.relativeOffsetOfLocalHeader + 30, function(err2) { + try { + if (err2) return callback(err2); + localFileHeader.fileName = buffer2.subarray(0, fileNameLength); + localFileHeader.extraField = buffer2.subarray(fileNameLength); + return callback(null, localFileHeader); + } finally { + self2.reader.unref(); + } + }); + } finally { + self2.reader.unref(); + } + }); + }; + function Entry() { + } + Entry.prototype.getLastModDate = function(options2) { + if (options2 == null) options2 = {}; + if (!options2.forceDosFormat) { + for (var i = 0; i < this.extraFields.length; i++) { + var extraField = this.extraFields[i]; + if (extraField.id === 21589) { + var data2 = extraField.data; + if (data2.length < 5) continue; + var flags = data2[0]; + var HAS_MTIME = 1; + if (!(flags & HAS_MTIME)) continue; + var posixTimestamp = data2.readInt32LE(1); + return new Date(posixTimestamp * 1e3); + } else if (extraField.id === 10) { + var data2 = extraField.data; + var cursor = 4; + while (cursor < data2.length + 4) { + var tag = data2.readUInt16LE(cursor); + cursor += 2; + var size = data2.readUInt16LE(cursor); + cursor += 2; + if (tag !== 1) { + cursor += size; + continue; + } + if (size < 8 || cursor + size > data2.length) break; + var hundredNanoSecondsSince1601 = 4294967296 * data2.readInt32LE(cursor + 4) + data2.readUInt32LE(cursor); + var millisecondsSince1970 = hundredNanoSecondsSince1601 / 1e4 - 116444736e5; + return new Date(millisecondsSince1970); + } + } + } + } + return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime, options2.timezone); + }; + Entry.prototype.isEncrypted = function() { + return (this.generalPurposeBitFlag & 1) !== 0; + }; + Entry.prototype.isCompressed = function() { + return this.compressionMethod === 8; + }; + function LocalFileHeader() { + } + function dosDateTimeToDate(date, time, timezone) { + var day = date & 31; + var month = (date >> 5 & 15) - 1; + var year = (date >> 9 & 127) + 1980; + var millisecond = 0; + var second = (time & 31) * 2; + var minute = time >> 5 & 63; + var hour = time >> 11 & 31; + if (timezone == null || timezone === "local") { + return new Date(year, month, day, hour, minute, second, millisecond); + } else if (timezone === "UTC") { + return new Date(Date.UTC(year, month, day, hour, minute, second, millisecond)); + } else { + throw new Error("unrecognized options.timezone: " + options.timezone); + } + } + function getFileNameLowLevel(generalPurposeBitFlag, fileNameBuffer, extraFields, strictFileNames) { + var fileName = null; + for (var i = 0; i < extraFields.length; i++) { + var extraField = extraFields[i]; + if (extraField.id === 28789) { + if (extraField.data.length < 6) { + continue; + } + if (extraField.data.readUInt8(0) !== 1) { + continue; + } + var oldNameCrc32 = extraField.data.readUInt32LE(1); + if (crc32.unsigned(fileNameBuffer) !== oldNameCrc32) { + continue; + } + fileName = decodeBuffer(extraField.data.subarray(5), true); + break; + } + } + if (fileName == null) { + var isUtf8 = (generalPurposeBitFlag & 2048) !== 0; + fileName = decodeBuffer(fileNameBuffer, isUtf8); + } + if (!strictFileNames) { + fileName = fileName.replace(/\\/g, "/"); + } + return fileName; + } + function validateFileName(fileName) { + if (fileName.indexOf("\\") !== -1) { + return "invalid characters in fileName: " + fileName; + } + if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) { + return "absolute path: " + fileName; + } + if (fileName.split("/").indexOf("..") !== -1) { + return "invalid relative path: " + fileName; + } + return null; + } + function parseExtraFields(extraFieldBuffer) { + var extraFields = []; + var i = 0; + while (i < extraFieldBuffer.length - 3) { + var headerId = extraFieldBuffer.readUInt16LE(i + 0); + var dataSize = extraFieldBuffer.readUInt16LE(i + 2); + var dataStart = i + 4; + var dataEnd = dataStart + dataSize; + if (dataEnd > extraFieldBuffer.length) throw new Error("extra field length exceeds extra field buffer size"); + var dataBuffer = extraFieldBuffer.subarray(dataStart, dataEnd); + extraFields.push({ + id: headerId, + data: dataBuffer + }); + i = dataEnd; + } + return extraFields; + } + function readAndAssertNoEof(reader, buffer2, offset2, length, position, callback) { + if (length === 0) { + return setImmediate(function() { + callback(null, newBuffer(0)); + }); + } + reader.read(buffer2, offset2, length, position, function(err, bytesRead) { + if (err) return callback(err); + if (bytesRead < length) { + return callback(new Error("unexpected EOF")); + } + callback(); + }); + } + util2.inherits(AssertByteCountStream, Transform); + function AssertByteCountStream(byteCount) { + Transform.call(this); + this.actualByteCount = 0; + this.expectedByteCount = byteCount; + } + AssertByteCountStream.prototype._transform = function(chunk, encoding2, cb) { + this.actualByteCount += chunk.length; + if (this.actualByteCount > this.expectedByteCount) { + var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount; + return cb(new Error(msg)); + } + cb(null, chunk); + }; + AssertByteCountStream.prototype._flush = function(cb) { + if (this.actualByteCount < this.expectedByteCount) { + var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount; + return cb(new Error(msg)); + } + cb(); + }; + util2.inherits(RandomAccessReader, EventEmitter2); + function RandomAccessReader() { + EventEmitter2.call(this); + this.refCount = 0; + } + RandomAccessReader.prototype.ref = function() { + this.refCount += 1; + }; + RandomAccessReader.prototype.unref = function() { + var self2 = this; + self2.refCount -= 1; + if (self2.refCount > 0) return; + if (self2.refCount < 0) throw new Error("invalid unref"); + self2.close(onCloseDone); + function onCloseDone(err) { + if (err) return self2.emit("error", err); + self2.emit("close"); + } + }; + RandomAccessReader.prototype.createReadStream = function(options2) { + if (options2 == null) options2 = {}; + var start = options2.start; + var end = options2.end; + if (start === end) { + var emptyStream = new PassThrough(); + setImmediate(function() { + emptyStream.end(); + }); + return emptyStream; + } + var stream2 = this._readStreamForRange(start, end); + var destroyed = false; + var refUnrefFilter = new RefUnrefFilter(this); + stream2.on("error", function(err) { + setImmediate(function() { + if (!destroyed) refUnrefFilter.emit("error", err); + }); + }); + installDestroyFn(refUnrefFilter, function() { + stream2.unpipe(refUnrefFilter); + refUnrefFilter.unref(); + stream2.destroy(); + }); + var byteCounter = new AssertByteCountStream(end - start); + refUnrefFilter.on("error", function(err) { + setImmediate(function() { + if (!destroyed) byteCounter.emit("error", err); + }); + }); + installDestroyFn(byteCounter, function() { + destroyed = true; + refUnrefFilter.unpipe(byteCounter); + refUnrefFilter.destroy(); + }); + return stream2.pipe(refUnrefFilter).pipe(byteCounter); + }; + RandomAccessReader.prototype._readStreamForRange = function(start, end) { + throw new Error("not implemented"); + }; + RandomAccessReader.prototype.read = function(buffer2, offset2, length, position, callback) { + var readStream = this.createReadStream({ start: position, end: position + length }); + var writeStream = new Writable(); + var written = 0; + writeStream._write = function(chunk, encoding2, cb) { + chunk.copy(buffer2, offset2 + written, 0, chunk.length); + written += chunk.length; + cb(); + }; + writeStream.on("finish", callback); + readStream.on("error", function(error2) { + callback(error2); + }); + readStream.pipe(writeStream); + }; + RandomAccessReader.prototype.close = function(callback) { + setImmediate(callback); + }; + util2.inherits(RefUnrefFilter, PassThrough); + function RefUnrefFilter(context) { + PassThrough.call(this); + this.context = context; + this.context.ref(); + this.unreffedYet = false; + } + RefUnrefFilter.prototype._flush = function(cb) { + this.unref(); + cb(); + }; + RefUnrefFilter.prototype.unref = function(cb) { + if (this.unreffedYet) return; + this.unreffedYet = true; + this.context.unref(); + }; + var cp437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "; + function decodeBuffer(buffer2, isUtf8) { + if (isUtf8) { + return buffer2.toString("utf8"); + } else { + var result = ""; + for (var i = 0; i < buffer2.length; i++) { + result += cp437[buffer2[i]]; + } + return result; + } + } + function readUInt64LE(buffer2, offset2) { + var lower32 = buffer2.readUInt32LE(offset2); + var upper32 = buffer2.readUInt32LE(offset2 + 4); + return upper32 * 4294967296 + lower32; + } + var newBuffer; + if (typeof Buffer.allocUnsafe === "function") { + newBuffer = function(len) { + return Buffer.allocUnsafe(len); + }; + } else { + newBuffer = function(len) { + return new Buffer(len); + }; + } + function installDestroyFn(stream2, fn) { + if (typeof stream2.destroy === "function") { + stream2._destroy = function(err, cb) { + fn(); + if (cb != null) cb(err); + }; + } else { + stream2.destroy = fn; + } + } + function defaultCallback(err) { + if (err) throw err; + } + return yauzl$1; +} +var extractZip$1; +var hasRequiredExtractZip; +function requireExtractZip() { + if (hasRequiredExtractZip) return extractZip$1; + hasRequiredExtractZip = 1; + const debug2 = requireBrowser$f()("extract-zip"); + const { createWriteStream: createWriteStream2, promises: fs2 } = require$$2$1; + const getStream2 = requireGetStream(); + const path2 = requirePath(); + const { promisify: promisify2 } = requireUtil$5(); + const stream2 = requireBrowser$h(); + const yauzl2 = requireYauzl(); + const openZip = promisify2(yauzl2.open); + const pipeline = promisify2(stream2.pipeline); + class Extractor { + constructor(zipPath, opts) { + this.zipPath = zipPath; + this.opts = opts; + } + async extract() { + debug2("opening", this.zipPath, "with opts", this.opts); + this.zipfile = await openZip(this.zipPath, { lazyEntries: true }); + this.canceled = false; + return new Promise((resolve, reject) => { + this.zipfile.on("error", (err) => { + this.canceled = true; + reject(err); + }); + this.zipfile.readEntry(); + this.zipfile.on("close", () => { + if (!this.canceled) { + debug2("zip extraction complete"); + resolve(); + } + }); + this.zipfile.on("entry", async (entry) => { + if (this.canceled) { + debug2("skipping entry", entry.fileName, { cancelled: this.canceled }); + return; + } + debug2("zipfile entry", entry.fileName); + if (entry.fileName.startsWith("__MACOSX/")) { + this.zipfile.readEntry(); + return; + } + const destDir = path2.dirname(path2.join(this.opts.dir, entry.fileName)); + try { + await fs2.mkdir(destDir, { recursive: true }); + const canonicalDestDir = await fs2.realpath(destDir); + const relativeDestDir = path2.relative(this.opts.dir, canonicalDestDir); + if (relativeDestDir.split(path2.sep).includes("..")) { + throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`); + } + await this.extractEntry(entry); + debug2("finished processing", entry.fileName); + this.zipfile.readEntry(); + } catch (err) { + this.canceled = true; + this.zipfile.close(); + reject(err); + } + }); + }); + } + async extractEntry(entry) { + if (this.canceled) { + debug2("skipping entry extraction", entry.fileName, { cancelled: this.canceled }); + return; + } + if (this.opts.onEntry) { + this.opts.onEntry(entry, this.zipfile); + } + const dest = path2.join(this.opts.dir, entry.fileName); + const mode = entry.externalFileAttributes >> 16 & 65535; + const IFMT = 61440; + const IFDIR = 16384; + const IFLNK = 40960; + const symlink2 = (mode & IFMT) === IFLNK; + let isDir = (mode & IFMT) === IFDIR; + if (!isDir && entry.fileName.endsWith("/")) { + isDir = true; + } + const madeBy = entry.versionMadeBy >> 8; + if (!isDir) isDir = madeBy === 0 && entry.externalFileAttributes === 16; + debug2("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink2 }); + const procMode = this.getExtractedMode(mode, isDir) & 511; + const destDir = isDir ? dest : path2.dirname(dest); + const mkdirOptions = { recursive: true }; + if (isDir) { + mkdirOptions.mode = procMode; + } + debug2("mkdir", { dir: destDir, ...mkdirOptions }); + await fs2.mkdir(destDir, mkdirOptions); + if (isDir) return; + debug2("opening read stream", dest); + const readStream = await promisify2(this.zipfile.openReadStream.bind(this.zipfile))(entry); + if (symlink2) { + const link2 = await getStream2(readStream); + debug2("creating symlink", link2, dest); + await fs2.symlink(link2, dest); + } else { + await pipeline(readStream, createWriteStream2(dest, { mode: procMode })); + } + } + getExtractedMode(entryMode, isDir) { + let mode = entryMode; + if (mode === 0) { + if (isDir) { + if (this.opts.defaultDirMode) { + mode = parseInt(this.opts.defaultDirMode, 10); + } + if (!mode) { + mode = 493; + } + } else { + if (this.opts.defaultFileMode) { + mode = parseInt(this.opts.defaultFileMode, 10); + } + if (!mode) { + mode = 420; + } + } + } + return mode; + } + } + extractZip$1 = async function(zipPath, opts) { + debug2("creating target directory", opts.dir); + if (!path2.isAbsolute(opts.dir)) { + throw new Error("Target directory is expected to be absolute"); + } + await fs2.mkdir(opts.dir, { recursive: true }); + opts.dir = await fs2.realpath(opts.dir); + return new Extractor(zipPath, opts).extract(); + }; + return extractZip$1; +} +var yazl$1 = {}; +var hasRequiredYazl; +function requireYazl() { + if (hasRequiredYazl) return yazl$1; + hasRequiredYazl = 1; + var fs2 = require$$2$1; + var Transform = requireBrowser$h().Transform; + var PassThrough = requireBrowser$h().PassThrough; + var zlib = requireLib(); + var util2 = requireUtil$5(); + var EventEmitter2 = requireEvents().EventEmitter; + var crc32 = requireBufferCrc32(); + yazl$1.ZipFile = ZipFile2; + yazl$1.dateToDosDateTime = dateToDosDateTime; + util2.inherits(ZipFile2, EventEmitter2); + function ZipFile2() { + this.outputStream = new PassThrough(); + this.entries = []; + this.outputStreamCursor = 0; + this.ended = false; + this.allDone = false; + this.forceZip64Eocd = false; + } + ZipFile2.prototype.addFile = function(realPath, metadataPath, options2) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, false); + if (options2 == null) options2 = {}; + var entry = new Entry(metadataPath, false, options2); + self2.entries.push(entry); + fs2.stat(realPath, function(err, stats) { + if (err) return self2.emit("error", err); + if (!stats.isFile()) return self2.emit("error", new Error("not a file: " + realPath)); + entry.uncompressedSize = stats.size; + if (options2.mtime == null) entry.setLastModDate(stats.mtime); + if (options2.mode == null) entry.setFileAttributesMode(stats.mode); + entry.setFileDataPumpFunction(function() { + var readStream = fs2.createReadStream(realPath); + entry.state = Entry.FILE_DATA_IN_PROGRESS; + readStream.on("error", function(err2) { + self2.emit("error", err2); + }); + pumpFileDataReadStream(self2, entry, readStream); + }); + pumpEntries(self2); + }); + }; + ZipFile2.prototype.addReadStream = function(readStream, metadataPath, options2) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, false); + if (options2 == null) options2 = {}; + var entry = new Entry(metadataPath, false, options2); + self2.entries.push(entry); + entry.setFileDataPumpFunction(function() { + entry.state = Entry.FILE_DATA_IN_PROGRESS; + pumpFileDataReadStream(self2, entry, readStream); + }); + pumpEntries(self2); + }; + ZipFile2.prototype.addBuffer = function(buffer2, metadataPath, options2) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, false); + if (buffer2.length > 1073741823) throw new Error("buffer too large: " + buffer2.length + " > 1073741823"); + if (options2 == null) options2 = {}; + if (options2.size != null) throw new Error("options.size not allowed"); + var entry = new Entry(metadataPath, false, options2); + entry.uncompressedSize = buffer2.length; + entry.crc32 = crc32.unsigned(buffer2); + entry.crcAndFileSizeKnown = true; + self2.entries.push(entry); + if (!entry.compress) { + setCompressedBuffer(buffer2); + } else { + zlib.deflateRaw(buffer2, function(err, compressedBuffer) { + setCompressedBuffer(compressedBuffer); + }); + } + function setCompressedBuffer(compressedBuffer) { + entry.compressedSize = compressedBuffer.length; + entry.setFileDataPumpFunction(function() { + writeToOutputStream(self2, compressedBuffer); + writeToOutputStream(self2, entry.getDataDescriptor()); + entry.state = Entry.FILE_DATA_DONE; + setImmediate(function() { + pumpEntries(self2); + }); + }); + pumpEntries(self2); + } + }; + ZipFile2.prototype.addEmptyDirectory = function(metadataPath, options2) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, true); + if (options2 == null) options2 = {}; + if (options2.size != null) throw new Error("options.size not allowed"); + if (options2.compress != null) throw new Error("options.compress not allowed"); + var entry = new Entry(metadataPath, true, options2); + self2.entries.push(entry); + entry.setFileDataPumpFunction(function() { + writeToOutputStream(self2, entry.getDataDescriptor()); + entry.state = Entry.FILE_DATA_DONE; + pumpEntries(self2); + }); + pumpEntries(self2); + }; + var eocdrSignatureBuffer = bufferFrom([80, 75, 5, 6]); + ZipFile2.prototype.end = function(options2, finalSizeCallback) { + if (typeof options2 === "function") { + finalSizeCallback = options2; + options2 = null; + } + if (options2 == null) options2 = {}; + if (this.ended) return; + this.ended = true; + this.finalSizeCallback = finalSizeCallback; + this.forceZip64Eocd = !!options2.forceZip64Format; + if (options2.comment) { + if (typeof options2.comment === "string") { + this.comment = encodeCp437(options2.comment); + } else { + this.comment = options2.comment; + } + if (this.comment.length > 65535) throw new Error("comment is too large"); + if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature"); + } else { + this.comment = EMPTY_BUFFER; + } + pumpEntries(this); + }; + function writeToOutputStream(self2, buffer2) { + self2.outputStream.write(buffer2); + self2.outputStreamCursor += buffer2.length; + } + function pumpFileDataReadStream(self2, entry, readStream) { + var crc32Watcher = new Crc32Watcher(); + var uncompressedSizeCounter = new ByteCounter(); + var compressor = entry.compress ? new zlib.DeflateRaw() : new PassThrough(); + var compressedSizeCounter = new ByteCounter(); + readStream.pipe(crc32Watcher).pipe(uncompressedSizeCounter).pipe(compressor).pipe(compressedSizeCounter).pipe(self2.outputStream, { end: false }); + compressedSizeCounter.on("end", function() { + entry.crc32 = crc32Watcher.crc32; + if (entry.uncompressedSize == null) { + entry.uncompressedSize = uncompressedSizeCounter.byteCount; + } else { + if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self2.emit("error", new Error("file data stream has unexpected number of bytes")); + } + entry.compressedSize = compressedSizeCounter.byteCount; + self2.outputStreamCursor += entry.compressedSize; + writeToOutputStream(self2, entry.getDataDescriptor()); + entry.state = Entry.FILE_DATA_DONE; + pumpEntries(self2); + }); + } + function pumpEntries(self2) { + if (self2.allDone) return; + if (self2.ended && self2.finalSizeCallback != null) { + var finalSize = calculateFinalSize(self2); + if (finalSize != null) { + self2.finalSizeCallback(finalSize); + self2.finalSizeCallback = null; + } + } + var entry = getFirstNotDoneEntry(); + function getFirstNotDoneEntry() { + for (var i = 0; i < self2.entries.length; i++) { + var entry2 = self2.entries[i]; + if (entry2.state < Entry.FILE_DATA_DONE) return entry2; + } + return null; + } + if (entry != null) { + if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return; + if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return; + entry.relativeOffsetOfLocalHeader = self2.outputStreamCursor; + var localFileHeader = entry.getLocalFileHeader(); + writeToOutputStream(self2, localFileHeader); + entry.doFileDataPump(); + } else { + if (self2.ended) { + self2.offsetOfStartOfCentralDirectory = self2.outputStreamCursor; + self2.entries.forEach(function(entry2) { + var centralDirectoryRecord = entry2.getCentralDirectoryRecord(); + writeToOutputStream(self2, centralDirectoryRecord); + }); + writeToOutputStream(self2, getEndOfCentralDirectoryRecord(self2)); + self2.outputStream.end(); + self2.allDone = true; + } + } + } + function calculateFinalSize(self2) { + var pretendOutputCursor = 0; + var centralDirectorySize = 0; + for (var i = 0; i < self2.entries.length; i++) { + var entry = self2.entries[i]; + if (entry.compress) return -1; + if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) { + if (entry.uncompressedSize == null) return -1; + } else { + if (entry.uncompressedSize == null) return null; + } + entry.relativeOffsetOfLocalHeader = pretendOutputCursor; + var useZip64Format = entry.useZip64Format(); + pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length; + pretendOutputCursor += entry.uncompressedSize; + if (!entry.crcAndFileSizeKnown) { + if (useZip64Format) { + pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE; + } else { + pretendOutputCursor += DATA_DESCRIPTOR_SIZE; + } + } + centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length; + if (useZip64Format) { + centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE; + } + } + var endOfCentralDirectorySize = 0; + if (self2.forceZip64Eocd || self2.entries.length >= 65535 || centralDirectorySize >= 65535 || pretendOutputCursor >= 4294967295) { + endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE; + } + endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self2.comment.length; + return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize; + } + var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56; + var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20; + var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22; + function getEndOfCentralDirectoryRecord(self2, actuallyJustTellMeHowLongItWouldBe) { + var needZip64Format = false; + var normalEntriesLength = self2.entries.length; + if (self2.forceZip64Eocd || self2.entries.length >= 65535) { + normalEntriesLength = 65535; + needZip64Format = true; + } + var sizeOfCentralDirectory = self2.outputStreamCursor - self2.offsetOfStartOfCentralDirectory; + var normalSizeOfCentralDirectory = sizeOfCentralDirectory; + if (self2.forceZip64Eocd || sizeOfCentralDirectory >= 4294967295) { + normalSizeOfCentralDirectory = 4294967295; + needZip64Format = true; + } + var normalOffsetOfStartOfCentralDirectory = self2.offsetOfStartOfCentralDirectory; + if (self2.forceZip64Eocd || self2.offsetOfStartOfCentralDirectory >= 4294967295) { + normalOffsetOfStartOfCentralDirectory = 4294967295; + needZip64Format = true; + } + var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self2.comment.length); + eocdrBuffer.writeUInt32LE(101010256, 0); + eocdrBuffer.writeUInt16LE(0, 4); + eocdrBuffer.writeUInt16LE(0, 6); + eocdrBuffer.writeUInt16LE(normalEntriesLength, 8); + eocdrBuffer.writeUInt16LE(normalEntriesLength, 10); + eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12); + eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16); + eocdrBuffer.writeUInt16LE(self2.comment.length, 20); + self2.comment.copy(eocdrBuffer, 22); + if (!needZip64Format) return eocdrBuffer; + var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE); + zip64EocdrBuffer.writeUInt32LE(101075792, 0); + writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4); + zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12); + zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14); + zip64EocdrBuffer.writeUInt32LE(0, 16); + zip64EocdrBuffer.writeUInt32LE(0, 20); + writeUInt64LE(zip64EocdrBuffer, self2.entries.length, 24); + writeUInt64LE(zip64EocdrBuffer, self2.entries.length, 32); + writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40); + writeUInt64LE(zip64EocdrBuffer, self2.offsetOfStartOfCentralDirectory, 48); + var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE); + zip64EocdlBuffer.writeUInt32LE(117853008, 0); + zip64EocdlBuffer.writeUInt32LE(0, 4); + writeUInt64LE(zip64EocdlBuffer, self2.outputStreamCursor, 8); + zip64EocdlBuffer.writeUInt32LE(1, 16); + return Buffer.concat([ + zip64EocdrBuffer, + zip64EocdlBuffer, + eocdrBuffer + ]); + } + function validateMetadataPath(metadataPath, isDirectory) { + if (metadataPath === "") throw new Error("empty metadataPath"); + metadataPath = metadataPath.replace(/\\/g, "/"); + if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath); + if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath); + var looksLikeDirectory = /\/$/.test(metadataPath); + if (isDirectory) { + if (!looksLikeDirectory) metadataPath += "/"; + } else { + if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath); + } + return metadataPath; + } + var EMPTY_BUFFER = bufferAlloc(0); + function Entry(metadataPath, isDirectory, options2) { + this.utf8FileName = bufferFrom(metadataPath); + if (this.utf8FileName.length > 65535) throw new Error("utf8 file name too long. " + utf8FileName.length + " > 65535"); + this.isDirectory = isDirectory; + this.state = Entry.WAITING_FOR_METADATA; + this.setLastModDate(options2.mtime != null ? options2.mtime : /* @__PURE__ */ new Date()); + if (options2.mode != null) { + this.setFileAttributesMode(options2.mode); + } else { + this.setFileAttributesMode(isDirectory ? 16893 : 33204); + } + if (isDirectory) { + this.crcAndFileSizeKnown = true; + this.crc32 = 0; + this.uncompressedSize = 0; + this.compressedSize = 0; + } else { + this.crcAndFileSizeKnown = false; + this.crc32 = null; + this.uncompressedSize = null; + this.compressedSize = null; + if (options2.size != null) this.uncompressedSize = options2.size; + } + if (isDirectory) { + this.compress = false; + } else { + this.compress = true; + if (options2.compress != null) this.compress = !!options2.compress; + } + this.forceZip64Format = !!options2.forceZip64Format; + if (options2.fileComment) { + if (typeof options2.fileComment === "string") { + this.fileComment = bufferFrom(options2.fileComment, "utf-8"); + } else { + this.fileComment = options2.fileComment; + } + if (this.fileComment.length > 65535) throw new Error("fileComment is too large"); + } else { + this.fileComment = EMPTY_BUFFER; + } + } + Entry.WAITING_FOR_METADATA = 0; + Entry.READY_TO_PUMP_FILE_DATA = 1; + Entry.FILE_DATA_IN_PROGRESS = 2; + Entry.FILE_DATA_DONE = 3; + Entry.prototype.setLastModDate = function(date) { + var dosDateTime = dateToDosDateTime(date); + this.lastModFileTime = dosDateTime.time; + this.lastModFileDate = dosDateTime.date; + }; + Entry.prototype.setFileAttributesMode = function(mode) { + if ((mode & 65535) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= 65535"); + this.externalFileAttributes = mode << 16 >>> 0; + }; + Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) { + this.doFileDataPump = doFileDataPump; + this.state = Entry.READY_TO_PUMP_FILE_DATA; + }; + Entry.prototype.useZip64Format = function() { + return this.forceZip64Format || this.uncompressedSize != null && this.uncompressedSize > 4294967294 || this.compressedSize != null && this.compressedSize > 4294967294 || this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 4294967294; + }; + var LOCAL_FILE_HEADER_FIXED_SIZE = 30; + var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20; + var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45; + var VERSION_MADE_BY = 3 << 8 | 63; + var FILE_NAME_IS_UTF8 = 1 << 11; + var UNKNOWN_CRC32_AND_FILE_SIZES = 1 << 3; + Entry.prototype.getLocalFileHeader = function() { + var crc322 = 0; + var compressedSize = 0; + var uncompressedSize = 0; + if (this.crcAndFileSizeKnown) { + crc322 = this.crc32; + compressedSize = this.compressedSize; + uncompressedSize = this.uncompressedSize; + } + var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE); + var generalPurposeBitFlag = FILE_NAME_IS_UTF8; + if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; + fixedSizeStuff.writeUInt32LE(67324752, 0); + fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4); + fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6); + fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8); + fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10); + fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12); + fixedSizeStuff.writeUInt32LE(crc322, 14); + fixedSizeStuff.writeUInt32LE(compressedSize, 18); + fixedSizeStuff.writeUInt32LE(uncompressedSize, 22); + fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26); + fixedSizeStuff.writeUInt16LE(0, 28); + return Buffer.concat([ + fixedSizeStuff, + // file name (variable size) + this.utf8FileName + // extra field (variable size) + // no extra fields + ]); + }; + var DATA_DESCRIPTOR_SIZE = 16; + var ZIP64_DATA_DESCRIPTOR_SIZE = 24; + Entry.prototype.getDataDescriptor = function() { + if (this.crcAndFileSizeKnown) { + return EMPTY_BUFFER; + } + if (!this.useZip64Format()) { + var buffer2 = bufferAlloc(DATA_DESCRIPTOR_SIZE); + buffer2.writeUInt32LE(134695760, 0); + buffer2.writeUInt32LE(this.crc32, 4); + buffer2.writeUInt32LE(this.compressedSize, 8); + buffer2.writeUInt32LE(this.uncompressedSize, 12); + return buffer2; + } else { + var buffer2 = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE); + buffer2.writeUInt32LE(134695760, 0); + buffer2.writeUInt32LE(this.crc32, 4); + writeUInt64LE(buffer2, this.compressedSize, 8); + writeUInt64LE(buffer2, this.uncompressedSize, 16); + return buffer2; + } + }; + var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46; + var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28; + Entry.prototype.getCentralDirectoryRecord = function() { + var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE); + var generalPurposeBitFlag = FILE_NAME_IS_UTF8; + if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; + var normalCompressedSize = this.compressedSize; + var normalUncompressedSize = this.uncompressedSize; + var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader; + var versionNeededToExtract; + var zeiefBuffer; + if (this.useZip64Format()) { + normalCompressedSize = 4294967295; + normalUncompressedSize = 4294967295; + normalRelativeOffsetOfLocalHeader = 4294967295; + versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64; + zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE); + zeiefBuffer.writeUInt16LE(1, 0); + zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2); + writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4); + writeUInt64LE(zeiefBuffer, this.compressedSize, 12); + writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20); + } else { + versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8; + zeiefBuffer = EMPTY_BUFFER; + } + fixedSizeStuff.writeUInt32LE(33639248, 0); + fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4); + fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6); + fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8); + fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10); + fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12); + fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14); + fixedSizeStuff.writeUInt32LE(this.crc32, 16); + fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20); + fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24); + fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28); + fixedSizeStuff.writeUInt16LE(zeiefBuffer.length, 30); + fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32); + fixedSizeStuff.writeUInt16LE(0, 34); + fixedSizeStuff.writeUInt16LE(0, 36); + fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38); + fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42); + return Buffer.concat([ + fixedSizeStuff, + // file name (variable size) + this.utf8FileName, + // extra field (variable size) + zeiefBuffer, + // file comment (variable size) + this.fileComment + ]); + }; + Entry.prototype.getCompressionMethod = function() { + var NO_COMPRESSION = 0; + var DEFLATE_COMPRESSION = 8; + return this.compress ? DEFLATE_COMPRESSION : NO_COMPRESSION; + }; + function dateToDosDateTime(jsDate) { + var date = 0; + date |= jsDate.getDate() & 31; + date |= (jsDate.getMonth() + 1 & 15) << 5; + date |= (jsDate.getFullYear() - 1980 & 127) << 9; + var time = 0; + time |= Math.floor(jsDate.getSeconds() / 2); + time |= (jsDate.getMinutes() & 63) << 5; + time |= (jsDate.getHours() & 31) << 11; + return { date, time }; + } + function writeUInt64LE(buffer2, n, offset2) { + var high = Math.floor(n / 4294967296); + var low = n % 4294967296; + buffer2.writeUInt32LE(low, offset2); + buffer2.writeUInt32LE(high, offset2 + 4); + } + util2.inherits(ByteCounter, Transform); + function ByteCounter(options2) { + Transform.call(this, options2); + this.byteCount = 0; + } + ByteCounter.prototype._transform = function(chunk, encoding2, cb) { + this.byteCount += chunk.length; + cb(null, chunk); + }; + util2.inherits(Crc32Watcher, Transform); + function Crc32Watcher(options2) { + Transform.call(this, options2); + this.crc32 = 0; + } + Crc32Watcher.prototype._transform = function(chunk, encoding2, cb) { + this.crc32 = crc32.unsigned(chunk, this.crc32); + cb(null, chunk); + }; + var cp437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "; + if (cp437.length !== 256) throw new Error("assertion failure"); + var reverseCp437 = null; + function encodeCp437(string2) { + if (/^[\x20-\x7e]*$/.test(string2)) { + return bufferFrom(string2, "utf-8"); + } + if (reverseCp437 == null) { + reverseCp437 = {}; + for (var i = 0; i < cp437.length; i++) { + reverseCp437[cp437[i]] = i; + } + } + var result = bufferAlloc(string2.length); + for (var i = 0; i < string2.length; i++) { + var b = reverseCp437[string2[i]]; + if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string2[i])); + result[i] = b; + } + return result; + } + function bufferAlloc(size) { + bufferAlloc = modern; + try { + return bufferAlloc(size); + } catch (e) { + bufferAlloc = legacy2; + return bufferAlloc(size); + } + function modern(size2) { + return Buffer.allocUnsafe(size2); + } + function legacy2(size2) { + return new Buffer(size2); + } + } + function bufferFrom(something, encoding2) { + bufferFrom = modern; + try { + return bufferFrom(something, encoding2); + } catch (e) { + bufferFrom = legacy2; + return bufferFrom(something, encoding2); + } + function modern(something2, encoding3) { + return Buffer.from(something2, encoding3); + } + function legacy2(something2, encoding3) { + return new Buffer(something2, encoding3); + } + } + function bufferIncludes(buffer2, content) { + bufferIncludes = modern; + try { + return bufferIncludes(buffer2, content); + } catch (e) { + bufferIncludes = legacy2; + return bufferIncludes(buffer2, content); + } + function modern(buffer3, content2) { + return buffer3.includes(content2); + } + function legacy2(buffer3, content2) { + for (var i = 0; i <= buffer3.length - content2.length; i++) { + for (var j = 0; ; j++) { + if (j === content2.length) return true; + if (buffer3[i + j] !== content2[j]) break; + } + } + return false; + } + } + return yazl$1; +} +var yazlExports = requireYazl(); +const index$2 = /* @__PURE__ */ getDefaultExportFromCjs(yazlExports); +const index$3 = /* @__PURE__ */ _mergeNamespaces({ + __proto__: null, + default: index$2 +}, [yazlExports]); +var yauzlExports = requireYauzl(); +const index = /* @__PURE__ */ getDefaultExportFromCjs(yauzlExports); +const index$1 = /* @__PURE__ */ _mergeNamespaces({ + __proto__: null, + default: index +}, [yauzlExports]); +const extractZip = requireExtractZip(); +const extract = extractZip; +const zipBundleImpl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + extract, + yauzl: index$1, + yazl: index$3 +}, Symbol.toStringTag, { value: "Module" })); +const require$$0 = /* @__PURE__ */ getAugmentedNamespace(zipBundleImpl); +const yazl = require$$0.yazl; +const yauzl = require$$0.yauzl; +require$$0.extract; +const existsAsync = (path2) => new Promise((resolve) => fs.stat(path2, (err) => resolve(!err))); +async function mkdirIfNeeded$1(filePath) { + await fs.promises.mkdir(path.dirname(filePath), { recursive: true }).catch(() => { + }); +} +async function removeFolders(dirs) { + return await Promise.all(dirs.map( + (dir) => fs.promises.rm(dir, { recursive: true, force: true, maxRetries: 10 }).catch((e) => e) + )); +} +function canAccessFile(file) { + if (!file) + return false; + try { + fs.accessSync(file); + return true; + } catch (e) { + return false; + } +} +class SerializedFS { + constructor() { + this._buffers = /* @__PURE__ */ new Map(); + this._operations = []; + this._operationsDone = new ManualPromise(); + this._operationsDone.resolve(); + } + mkdir(dir) { + this._appendOperation({ op: "mkdir", dir }); + } + writeFile(file, content, skipIfExists) { + this._buffers.delete(file); + this._appendOperation({ op: "writeFile", file, content, skipIfExists }); + } + appendFile(file, text, flush) { + if (!this._buffers.has(file)) + this._buffers.set(file, []); + this._buffers.get(file).push(text); + if (flush) + this._flushFile(file); + } + _flushFile(file) { + const buffer2 = this._buffers.get(file); + if (buffer2 === void 0) + return; + const content = buffer2.join(""); + this._buffers.delete(file); + this._appendOperation({ op: "appendFile", file, content }); + } + copyFile(from2, to) { + this._flushFile(from2); + this._buffers.delete(to); + this._appendOperation({ op: "copyFile", from: from2, to }); + } + async syncAndGetError() { + for (const file of this._buffers.keys()) + this._flushFile(file); + await this._operationsDone; + return this._error; + } + zip(entries, zipFileName) { + for (const file of this._buffers.keys()) + this._flushFile(file); + this._appendOperation({ op: "zip", entries, zipFileName }); + } + // This method serializes all writes to the trace. + _appendOperation(op) { + const last = this._operations[this._operations.length - 1]; + if ((last == null ? void 0 : last.op) === "appendFile" && op.op === "appendFile" && last.file === op.file) { + last.content += op.content; + return; + } + this._operations.push(op); + if (this._operationsDone.isDone()) + this._performOperations(); + } + async _performOperations() { + this._operationsDone = new ManualPromise(); + while (this._operations.length) { + const op = this._operations.shift(); + if (this._error) + continue; + try { + await this._performOperation(op); + } catch (e) { + this._error = e; + } + } + this._operationsDone.resolve(); + } + async _performOperation(op) { + switch (op.op) { + case "mkdir": { + await fs.promises.mkdir(op.dir, { recursive: true }); + return; + } + case "writeFile": { + if (op.skipIfExists) + await fs.promises.writeFile(op.file, op.content, { flag: "wx" }).catch(() => { + }); + else + await fs.promises.writeFile(op.file, op.content); + return; + } + case "copyFile": { + await fs.promises.copyFile(op.from, op.to); + return; + } + case "appendFile": { + await fs.promises.appendFile(op.file, op.content); + return; + } + case "zip": { + const zipFile = new yazl.ZipFile(); + const result = new ManualPromise(); + zipFile.on("error", (error2) => result.reject(error2)); + for (const entry of op.entries) + zipFile.addFile(entry.value, entry.name); + zipFile.end(); + zipFile.outputStream.pipe(fs.createWriteStream(op.zipFileName)).on("close", () => result.resolve()).on("error", (error2) => result.reject(error2)); + await result; + return; + } + } + } +} +async function downloadBrowserWithProgressBar(title, browserDirectory, executablePath, downloadURLs, downloadFileName, downloadSocketTimeout) { + if (await existsAsync(browserDirectoryToMarkerFilePath(browserDirectory))) { + debugLogger.log("install", `${title} is already downloaded.`); + return false; + } + const zipPath = path.join(os.tmpdir(), downloadFileName); + try { + const retryCount = 5; + for (let attempt = 1; attempt <= retryCount; ++attempt) { + debugLogger.log("install", `downloading ${title} - attempt #${attempt}`); + const url2 = downloadURLs[(attempt - 1) % downloadURLs.length]; + logPolitely(`Downloading ${title}` + colors.dim(` from ${url2}`)); + const { error: error2 } = await downloadBrowserWithProgressBarOutOfProcess(title, browserDirectory, url2, zipPath, executablePath, downloadSocketTimeout); + if (!error2) { + debugLogger.log("install", `SUCCESS installing ${title}`); + break; + } + if (await existsAsync(zipPath)) + await fs.promises.unlink(zipPath); + if (await existsAsync(browserDirectory)) + await fs.promises.rmdir(browserDirectory, { recursive: true }); + const errorMessage = (error2 == null ? void 0 : error2.message) || ""; + debugLogger.log("install", `attempt #${attempt} - ERROR: ${errorMessage}`); + if (attempt >= retryCount) + throw error2; + } + } catch (e) { + debugLogger.log("install", `FAILED installation ${title} with error: ${e}`); + process.exitCode = 1; + throw e; + } finally { + if (await existsAsync(zipPath)) + await fs.promises.unlink(zipPath); + } + logPolitely(`${title} downloaded to ${browserDirectory}`); + return true; +} +function downloadBrowserWithProgressBarOutOfProcess(title, browserDirectory, url2, zipPath, executablePath, socketTimeout) { + const cp2 = fork(path.join("playwright/packages/playwright-core/src/server/registry", "oopDownloadBrowserMain.js")); + const promise = new ManualPromise(); + const progress2 = getDownloadProgress(); + cp2.on("message", (message) => { + if ((message == null ? void 0 : message.method) === "log") + debugLogger.log("install", message.params.message); + if ((message == null ? void 0 : message.method) === "progress") + progress2(message.params.done, message.params.total); + }); + cp2.on("exit", (code) => { + if (code !== 0) { + promise.resolve({ error: new Error(`Download failure, code=${code}`) }); + return; + } + if (!fs.existsSync(browserDirectoryToMarkerFilePath(browserDirectory))) + promise.resolve({ error: new Error(`Download failure, ${browserDirectoryToMarkerFilePath(browserDirectory)} does not exist`) }); + else + promise.resolve({ error: null }); + }); + cp2.on("error", (error2) => { + promise.resolve({ error: error2 }); + }); + debugLogger.log("install", `running download:`); + debugLogger.log("install", `-- from url: ${url2}`); + debugLogger.log("install", `-- to location: ${zipPath}`); + const downloadParams = { + title, + browserDirectory, + url: url2, + zipPath, + executablePath, + socketTimeout, + userAgent: getUserAgent() + }; + cp2.send({ method: "download", params: downloadParams }); + return promise; +} +function logPolitely(toBeLogged) { + const logLevel = define_process_env_default.npm_config_loglevel; + const logLevelDisplay = ["silent", "error", "warn"].indexOf(logLevel || "") > -1; + if (!logLevelDisplay) + console.log(toBeLogged); +} +function getDownloadProgress() { + if (process.stdout.isTTY) + return getAnimatedDownloadProgress(); + return getBasicDownloadProgress(); +} +function getAnimatedDownloadProgress() { + let progressBar; + let lastDownloadedBytes = 0; + return (downloadedBytes, totalBytes) => { + if (!progressBar) { + progressBar = new progress( + `${toMegabytes( + totalBytes + )} [:bar] :percent :etas`, + { + complete: "=", + incomplete: " ", + width: 20, + total: totalBytes + } + ); + } + const delta = downloadedBytes - lastDownloadedBytes; + lastDownloadedBytes = downloadedBytes; + progressBar.tick(delta); + }; +} +function getBasicDownloadProgress() { + const totalRows = 10; + const stepWidth = 8; + let lastRow = -1; + return (downloadedBytes, totalBytes) => { + const percentage = downloadedBytes / totalBytes; + const row = Math.floor(totalRows * percentage); + if (row > lastRow) { + lastRow = row; + const percentageString = String(percentage * 100 | 0).padStart(3); + console.log(`|${"■".repeat(row * stepWidth)}${" ".repeat((totalRows - row) * stepWidth)}| ${percentageString}% of ${toMegabytes(totalBytes)}`); + } + }; +} +function toMegabytes(bytes) { + const mb = bytes / 1024 / 1024; + return `${Math.round(mb * 10) / 10} MiB`; +} +const deps = { + "ubuntu20.04-x64": { + tools: [ + "xvfb", + "fonts-noto-color-emoji", + "ttf-unifont", + "libfontconfig", + "libfreetype6", + "xfonts-cyrillic", + "xfonts-scalable", + "fonts-liberation", + "fonts-ipafont-gothic", + "fonts-wqy-zenhei", + "fonts-tlwg-loma-otf", + "ttf-ubuntu-font-family" + ], + chromium: [ + "fonts-liberation", + "libasound2", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libatspi2.0-0", + "libcairo2", + "libcups2", + "libdbus-1-3", + "libdrm2", + "libegl1", + "libgbm1", + "libglib2.0-0", + "libgtk-3-0", + "libnspr4", + "libnss3", + "libpango-1.0-0", + "libx11-6", + "libx11-xcb1", + "libxcb1", + "libxcomposite1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxrandr2", + "libxshmfence1" + ], + firefox: [ + "ffmpeg", + "libatk1.0-0", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libdbus-glib-1-2", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf2.0-0", + "libglib2.0-0", + "libgtk-3-0", + "libpango-1.0-0", + "libpangocairo-1.0-0", + "libpangoft2-1.0-0", + "libx11-6", + "libx11-xcb1", + "libxcb-shm0", + "libxcb1", + "libxcomposite1", + "libxcursor1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxi6", + "libxrender1", + "libxt6", + "libxtst6" + ], + webkit: [ + "libenchant-2-2", + "libflite1", + "libx264-155", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libcairo2", + "libegl1", + "libenchant1c2a", + "libepoxy0", + "libevdev2", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf2.0-0", + "libgl1", + "libgles2", + "libglib2.0-0", + "libgtk-3-0", + "libgudev-1.0-0", + "libharfbuzz-icu0", + "libharfbuzz0b", + "libhyphen0", + "libicu66", + "libjpeg-turbo8", + "libnghttp2-14", + "libnotify4", + "libopengl0", + "libopenjp2-7", + "libopus0", + "libpango-1.0-0", + "libpng16-16", + "libsecret-1-0", + "libvpx6", + "libwayland-client0", + "libwayland-egl1", + "libwayland-server0", + "libwebp6", + "libwebpdemux2", + "libwoff1", + "libx11-6", + "libxcomposite1", + "libxdamage1", + "libxkbcommon0", + "libxml2", + "libxslt1.1", + "libatomic1", + "libevent-2.1-7" + ], + lib2package: { + "libflite.so.1": "libflite1", + "libflite_usenglish.so.1": "libflite1", + "libflite_cmu_grapheme_lang.so.1": "libflite1", + "libflite_cmu_grapheme_lex.so.1": "libflite1", + "libflite_cmu_indic_lang.so.1": "libflite1", + "libflite_cmu_indic_lex.so.1": "libflite1", + "libflite_cmulex.so.1": "libflite1", + "libflite_cmu_time_awb.so.1": "libflite1", + "libflite_cmu_us_awb.so.1": "libflite1", + "libflite_cmu_us_kal16.so.1": "libflite1", + "libflite_cmu_us_kal.so.1": "libflite1", + "libflite_cmu_us_rms.so.1": "libflite1", + "libflite_cmu_us_slt.so.1": "libflite1", + "libx264.so": "libx264-155", + "libasound.so.2": "libasound2", + "libatk-1.0.so.0": "libatk1.0-0", + "libatk-bridge-2.0.so.0": "libatk-bridge2.0-0", + "libatspi.so.0": "libatspi2.0-0", + "libcairo-gobject.so.2": "libcairo-gobject2", + "libcairo.so.2": "libcairo2", + "libcups.so.2": "libcups2", + "libdbus-1.so.3": "libdbus-1-3", + "libdbus-glib-1.so.2": "libdbus-glib-1-2", + "libdrm.so.2": "libdrm2", + "libEGL.so.1": "libegl1", + "libenchant.so.1": "libenchant1c2a", + "libevdev.so.2": "libevdev2", + "libepoxy.so.0": "libepoxy0", + "libfontconfig.so.1": "libfontconfig1", + "libfreetype.so.6": "libfreetype6", + "libgbm.so.1": "libgbm1", + "libgdk_pixbuf-2.0.so.0": "libgdk-pixbuf2.0-0", + "libgdk-3.so.0": "libgtk-3-0", + "libgdk-x11-2.0.so.0": "libgtk2.0-0", + "libgio-2.0.so.0": "libglib2.0-0", + "libGL.so.1": "libgl1", + "libGLESv2.so.2": "libgles2", + "libglib-2.0.so.0": "libglib2.0-0", + "libgmodule-2.0.so.0": "libglib2.0-0", + "libgobject-2.0.so.0": "libglib2.0-0", + "libgthread-2.0.so.0": "libglib2.0-0", + "libgtk-3.so.0": "libgtk-3-0", + "libgtk-x11-2.0.so.0": "libgtk2.0-0", + "libgudev-1.0.so.0": "libgudev-1.0-0", + "libharfbuzz-icu.so.0": "libharfbuzz-icu0", + "libharfbuzz.so.0": "libharfbuzz0b", + "libhyphen.so.0": "libhyphen0", + "libicui18n.so.66": "libicu66", + "libicuuc.so.66": "libicu66", + "libjpeg.so.8": "libjpeg-turbo8", + "libnotify.so.4": "libnotify4", + "libnspr4.so": "libnspr4", + "libnss3.so": "libnss3", + "libnssutil3.so": "libnss3", + "libOpenGL.so.0": "libopengl0", + "libopenjp2.so.7": "libopenjp2-7", + "libopus.so.0": "libopus0", + "libpango-1.0.so.0": "libpango-1.0-0", + "libpangocairo-1.0.so.0": "libpangocairo-1.0-0", + "libpangoft2-1.0.so.0": "libpangoft2-1.0-0", + "libpng16.so.16": "libpng16-16", + "libsecret-1.so.0": "libsecret-1-0", + "libsmime3.so": "libnss3", + "libvpx.so.6": "libvpx6", + "libwayland-client.so.0": "libwayland-client0", + "libwayland-egl.so.1": "libwayland-egl1", + "libwayland-server.so.0": "libwayland-server0", + "libwebp.so.6": "libwebp6", + "libwebpdemux.so.2": "libwebpdemux2", + "libwoff2dec.so.1.0.2": "libwoff1", + "libX11-xcb.so.1": "libx11-xcb1", + "libX11.so.6": "libx11-6", + "libxcb-dri3.so.0": "libxcb-dri3-0", + "libxcb-shm.so.0": "libxcb-shm0", + "libxcb.so.1": "libxcb1", + "libXcomposite.so.1": "libxcomposite1", + "libXcursor.so.1": "libxcursor1", + "libXdamage.so.1": "libxdamage1", + "libXext.so.6": "libxext6", + "libXfixes.so.3": "libxfixes3", + "libXi.so.6": "libxi6", + "libxkbcommon.so.0": "libxkbcommon0", + "libxml2.so.2": "libxml2", + "libXrandr.so.2": "libxrandr2", + "libXrender.so.1": "libxrender1", + "libxslt.so.1": "libxslt1.1", + "libXt.so.6": "libxt6", + "libXtst.so.6": "libxtst6", + "libxshmfence.so.1": "libxshmfence1", + "libatomic.so.1": "libatomic1", + "libenchant-2.so.2": "libenchant-2-2", + "libevent-2.1.so.7": "libevent-2.1-7" + } + }, + "ubuntu22.04-x64": { + tools: [ + "xvfb", + "fonts-noto-color-emoji", + "fonts-unifont", + "libfontconfig1", + "libfreetype6", + "xfonts-cyrillic", + "xfonts-scalable", + "fonts-liberation", + "fonts-ipafont-gothic", + "fonts-wqy-zenhei", + "fonts-tlwg-loma-otf", + "fonts-freefont-ttf" + ], + chromium: [ + "libasound2", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libatspi2.0-0", + "libcairo2", + "libcups2", + "libdbus-1-3", + "libdrm2", + "libgbm1", + "libglib2.0-0", + "libnspr4", + "libnss3", + "libpango-1.0-0", + "libwayland-client0", + "libx11-6", + "libxcb1", + "libxcomposite1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxkbcommon0", + "libxrandr2" + ], + firefox: [ + "ffmpeg", + "libasound2", + "libatk1.0-0", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libdbus-glib-1-2", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf-2.0-0", + "libglib2.0-0", + "libgtk-3-0", + "libpango-1.0-0", + "libpangocairo-1.0-0", + "libx11-6", + "libx11-xcb1", + "libxcb-shm0", + "libxcb1", + "libxcomposite1", + "libxcursor1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxi6", + "libxrandr2", + "libxrender1", + "libxtst6" + ], + webkit: [ + "libsoup-3.0-0", + "libenchant-2-2", + "gstreamer1.0-libav", + "gstreamer1.0-plugins-bad", + "gstreamer1.0-plugins-base", + "gstreamer1.0-plugins-good", + "libicu70", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libcairo2", + "libdbus-1-3", + "libdrm2", + "libegl1", + "libepoxy0", + "libevdev2", + "libffi7", + "libfontconfig1", + "libfreetype6", + "libgbm1", + "libgdk-pixbuf-2.0-0", + "libgles2", + "libglib2.0-0", + "libglx0", + "libgstreamer-gl1.0-0", + "libgstreamer-plugins-base1.0-0", + "libgstreamer1.0-0", + "libgtk-4-1", + "libgudev-1.0-0", + "libharfbuzz-icu0", + "libharfbuzz0b", + "libhyphen0", + "libjpeg-turbo8", + "liblcms2-2", + "libmanette-0.2-0", + "libnotify4", + "libopengl0", + "libopenjp2-7", + "libopus0", + "libpango-1.0-0", + "libpng16-16", + "libproxy1v5", + "libsecret-1-0", + "libwayland-client0", + "libwayland-egl1", + "libwayland-server0", + "libwebpdemux2", + "libwoff1", + "libx11-6", + "libxcomposite1", + "libxdamage1", + "libxkbcommon0", + "libxml2", + "libxslt1.1", + "libx264-163", + "libatomic1", + "libevent-2.1-7", + "libavif13" + ], + lib2package: { + "libavif.so.13": "libavif13", + "libsoup-3.0.so.0": "libsoup-3.0-0", + "libasound.so.2": "libasound2", + "libatk-1.0.so.0": "libatk1.0-0", + "libatk-bridge-2.0.so.0": "libatk-bridge2.0-0", + "libatspi.so.0": "libatspi2.0-0", + "libcairo-gobject.so.2": "libcairo-gobject2", + "libcairo.so.2": "libcairo2", + "libcups.so.2": "libcups2", + "libdbus-1.so.3": "libdbus-1-3", + "libdbus-glib-1.so.2": "libdbus-glib-1-2", + "libdrm.so.2": "libdrm2", + "libEGL.so.1": "libegl1", + "libepoxy.so.0": "libepoxy0", + "libevdev.so.2": "libevdev2", + "libffi.so.7": "libffi7", + "libfontconfig.so.1": "libfontconfig1", + "libfreetype.so.6": "libfreetype6", + "libgbm.so.1": "libgbm1", + "libgdk_pixbuf-2.0.so.0": "libgdk-pixbuf-2.0-0", + "libgdk-3.so.0": "libgtk-3-0", + "libgio-2.0.so.0": "libglib2.0-0", + "libGLESv2.so.2": "libgles2", + "libglib-2.0.so.0": "libglib2.0-0", + "libGLX.so.0": "libglx0", + "libgmodule-2.0.so.0": "libglib2.0-0", + "libgobject-2.0.so.0": "libglib2.0-0", + "libgstallocators-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstapp-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstaudio-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstbase-1.0.so.0": "libgstreamer1.0-0", + "libgstfft-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstgl-1.0.so.0": "libgstreamer-gl1.0-0", + "libgstpbutils-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstreamer-1.0.so.0": "libgstreamer1.0-0", + "libgsttag-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstvideo-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgtk-3.so.0": "libgtk-3-0", + "libgtk-4.so.1": "libgtk-4-1", + "libgudev-1.0.so.0": "libgudev-1.0-0", + "libharfbuzz-icu.so.0": "libharfbuzz-icu0", + "libharfbuzz.so.0": "libharfbuzz0b", + "libhyphen.so.0": "libhyphen0", + "libjpeg.so.8": "libjpeg-turbo8", + "liblcms2.so.2": "liblcms2-2", + "libmanette-0.2.so.0": "libmanette-0.2-0", + "libnotify.so.4": "libnotify4", + "libnspr4.so": "libnspr4", + "libnss3.so": "libnss3", + "libnssutil3.so": "libnss3", + "libOpenGL.so.0": "libopengl0", + "libopenjp2.so.7": "libopenjp2-7", + "libopus.so.0": "libopus0", + "libpango-1.0.so.0": "libpango-1.0-0", + "libpangocairo-1.0.so.0": "libpangocairo-1.0-0", + "libpng16.so.16": "libpng16-16", + "libproxy.so.1": "libproxy1v5", + "libsecret-1.so.0": "libsecret-1-0", + "libsmime3.so": "libnss3", + "libwayland-client.so.0": "libwayland-client0", + "libwayland-egl.so.1": "libwayland-egl1", + "libwayland-server.so.0": "libwayland-server0", + "libwebpdemux.so.2": "libwebpdemux2", + "libwoff2dec.so.1.0.2": "libwoff1", + "libX11-xcb.so.1": "libx11-xcb1", + "libX11.so.6": "libx11-6", + "libxcb-shm.so.0": "libxcb-shm0", + "libxcb.so.1": "libxcb1", + "libXcomposite.so.1": "libxcomposite1", + "libXcursor.so.1": "libxcursor1", + "libXdamage.so.1": "libxdamage1", + "libXext.so.6": "libxext6", + "libXfixes.so.3": "libxfixes3", + "libXi.so.6": "libxi6", + "libxkbcommon.so.0": "libxkbcommon0", + "libxml2.so.2": "libxml2", + "libXrandr.so.2": "libxrandr2", + "libXrender.so.1": "libxrender1", + "libxslt.so.1": "libxslt1.1", + "libXtst.so.6": "libxtst6", + "libicui18n.so.60": "libicu70", + "libicuuc.so.66": "libicu70", + "libicui18n.so.66": "libicu70", + "libwebp.so.6": "libwebp6", + "libenchant-2.so.2": "libenchant-2-2", + "libx264.so": "libx264-163", + "libvpx.so.7": "libvpx7", + "libatomic.so.1": "libatomic1", + "libevent-2.1.so.7": "libevent-2.1-7" + } + }, + "ubuntu24.04-x64": { + tools: [ + "xvfb", + "fonts-noto-color-emoji", + "fonts-unifont", + "libfontconfig1", + "libfreetype6", + "xfonts-cyrillic", + "xfonts-scalable", + "fonts-liberation", + "fonts-ipafont-gothic", + "fonts-wqy-zenhei", + "fonts-tlwg-loma-otf", + "fonts-freefont-ttf" + ], + chromium: [ + "libasound2t64", + "libatk-bridge2.0-0t64", + "libatk1.0-0t64", + "libatspi2.0-0t64", + "libcairo2", + "libcups2t64", + "libdbus-1-3", + "libdrm2", + "libgbm1", + "libglib2.0-0t64", + "libnspr4", + "libnss3", + "libpango-1.0-0", + "libx11-6", + "libxcb1", + "libxcomposite1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxkbcommon0", + "libxrandr2" + ], + firefox: [ + "libasound2t64", + "libatk1.0-0t64", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf-2.0-0", + "libglib2.0-0t64", + "libgtk-3-0t64", + "libpango-1.0-0", + "libpangocairo-1.0-0", + "libx11-6", + "libx11-xcb1", + "libxcb-shm0", + "libxcb1", + "libxcomposite1", + "libxcursor1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxi6", + "libxrandr2", + "libxrender1" + ], + webkit: [ + "gstreamer1.0-libav", + "gstreamer1.0-plugins-bad", + "gstreamer1.0-plugins-base", + "gstreamer1.0-plugins-good", + "libicu74", + "libatomic1", + "libatk-bridge2.0-0t64", + "libatk1.0-0t64", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libdrm2", + "libenchant-2-2", + "libepoxy0", + "libevent-2.1-7t64", + "libflite1", + "libfontconfig1", + "libfreetype6", + "libgbm1", + "libgdk-pixbuf-2.0-0", + "libgles2", + "libglib2.0-0t64", + "libgstreamer-gl1.0-0", + "libgstreamer-plugins-bad1.0-0", + "libgstreamer-plugins-base1.0-0", + "libgstreamer1.0-0", + "libgtk-4-1", + "libharfbuzz-icu0", + "libharfbuzz0b", + "libhyphen0", + "libicu74", + "libjpeg-turbo8", + "liblcms2-2", + "libmanette-0.2-0", + "libopus0", + "libpango-1.0-0", + "libpangocairo-1.0-0", + "libpng16-16t64", + "libsecret-1-0", + "libvpx9", + "libwayland-client0", + "libwayland-egl1", + "libwayland-server0", + "libwebp7", + "libwebpdemux2", + "libwoff1", + "libx11-6", + "libxkbcommon0", + "libxml2", + "libxslt1.1", + "libx264-164", + "libavif16" + ], + lib2package: { + "libavif.so.16": "libavif16", + "libasound.so.2": "libasound2t64", + "libatk-1.0.so.0": "libatk1.0-0t64", + "libatk-bridge-2.0.so.0": "libatk-bridge2.0-0t64", + "libatomic.so.1": "libatomic1", + "libatspi.so.0": "libatspi2.0-0t64", + "libcairo-gobject.so.2": "libcairo-gobject2", + "libcairo.so.2": "libcairo2", + "libcups.so.2": "libcups2t64", + "libdbus-1.so.3": "libdbus-1-3", + "libdrm.so.2": "libdrm2", + "libenchant-2.so.2": "libenchant-2-2", + "libepoxy.so.0": "libepoxy0", + "libevent-2.1.so.7": "libevent-2.1-7t64", + "libflite_cmu_grapheme_lang.so.1": "libflite1", + "libflite_cmu_grapheme_lex.so.1": "libflite1", + "libflite_cmu_indic_lang.so.1": "libflite1", + "libflite_cmu_indic_lex.so.1": "libflite1", + "libflite_cmu_time_awb.so.1": "libflite1", + "libflite_cmu_us_awb.so.1": "libflite1", + "libflite_cmu_us_kal.so.1": "libflite1", + "libflite_cmu_us_kal16.so.1": "libflite1", + "libflite_cmu_us_rms.so.1": "libflite1", + "libflite_cmu_us_slt.so.1": "libflite1", + "libflite_cmulex.so.1": "libflite1", + "libflite_usenglish.so.1": "libflite1", + "libflite.so.1": "libflite1", + "libfontconfig.so.1": "libfontconfig1", + "libfreetype.so.6": "libfreetype6", + "libgbm.so.1": "libgbm1", + "libgdk_pixbuf-2.0.so.0": "libgdk-pixbuf-2.0-0", + "libgdk-3.so.0": "libgtk-3-0t64", + "libgio-2.0.so.0": "libglib2.0-0t64", + "libGLESv2.so.2": "libgles2", + "libglib-2.0.so.0": "libglib2.0-0t64", + "libgmodule-2.0.so.0": "libglib2.0-0t64", + "libgobject-2.0.so.0": "libglib2.0-0t64", + "libgstallocators-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstapp-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstaudio-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstbase-1.0.so.0": "libgstreamer1.0-0", + "libgstcodecparsers-1.0.so.0": "libgstreamer-plugins-bad1.0-0", + "libgstfft-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstgl-1.0.so.0": "libgstreamer-gl1.0-0", + "libgstpbutils-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstreamer-1.0.so.0": "libgstreamer1.0-0", + "libgsttag-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstvideo-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgtk-3.so.0": "libgtk-3-0t64", + "libgtk-4.so.1": "libgtk-4-1", + "libharfbuzz-icu.so.0": "libharfbuzz-icu0", + "libharfbuzz.so.0": "libharfbuzz0b", + "libhyphen.so.0": "libhyphen0", + "libicudata.so.74": "libicu74", + "libicui18n.so.74": "libicu74", + "libicuuc.so.74": "libicu74", + "libjpeg.so.8": "libjpeg-turbo8", + "liblcms2.so.2": "liblcms2-2", + "libmanette-0.2.so.0": "libmanette-0.2-0", + "libnspr4.so": "libnspr4", + "libnss3.so": "libnss3", + "libnssutil3.so": "libnss3", + "libopus.so.0": "libopus0", + "libpango-1.0.so.0": "libpango-1.0-0", + "libpangocairo-1.0.so.0": "libpangocairo-1.0-0", + "libpng16.so.16": "libpng16-16t64", + "libsecret-1.so.0": "libsecret-1-0", + "libsmime3.so": "libnss3", + "libsoup-3.0.so.0": "libsoup-3.0-0", + "libvpx.so.9": "libvpx9", + "libwayland-client.so.0": "libwayland-client0", + "libwayland-egl.so.1": "libwayland-egl1", + "libwayland-server.so.0": "libwayland-server0", + "libwebp.so.7": "libwebp7", + "libwebpdemux.so.2": "libwebpdemux2", + "libwoff2dec.so.1.0.2": "libwoff1", + "libX11-xcb.so.1": "libx11-xcb1", + "libX11.so.6": "libx11-6", + "libxcb-shm.so.0": "libxcb-shm0", + "libxcb.so.1": "libxcb1", + "libXcomposite.so.1": "libxcomposite1", + "libXcursor.so.1": "libxcursor1", + "libXdamage.so.1": "libxdamage1", + "libXext.so.6": "libxext6", + "libXfixes.so.3": "libxfixes3", + "libXi.so.6": "libxi6", + "libxkbcommon.so.0": "libxkbcommon0", + "libxml2.so.2": "libxml2", + "libXrandr.so.2": "libxrandr2", + "libXrender.so.1": "libxrender1", + "libxslt.so.1": "libxslt1.1", + "libx264.so": "libx264-164" + } + }, + "debian11-x64": { + tools: [ + "xvfb", + "fonts-noto-color-emoji", + "fonts-unifont", + "libfontconfig1", + "libfreetype6", + "xfonts-cyrillic", + "xfonts-scalable", + "fonts-liberation", + "fonts-ipafont-gothic", + "fonts-wqy-zenhei", + "fonts-tlwg-loma-otf", + "fonts-freefont-ttf" + ], + chromium: [ + "libasound2", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libatspi2.0-0", + "libcairo2", + "libcups2", + "libdbus-1-3", + "libdrm2", + "libgbm1", + "libglib2.0-0", + "libnspr4", + "libnss3", + "libpango-1.0-0", + "libwayland-client0", + "libx11-6", + "libxcb1", + "libxcomposite1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxkbcommon0", + "libxrandr2" + ], + firefox: [ + "libasound2", + "libatk1.0-0", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libdbus-glib-1-2", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf-2.0-0", + "libglib2.0-0", + "libgtk-3-0", + "libharfbuzz0b", + "libpango-1.0-0", + "libpangocairo-1.0-0", + "libx11-6", + "libx11-xcb1", + "libxcb-shm0", + "libxcb1", + "libxcomposite1", + "libxcursor1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxi6", + "libxrandr2", + "libxrender1", + "libxtst6" + ], + webkit: [ + "gstreamer1.0-libav", + "gstreamer1.0-plugins-bad", + "gstreamer1.0-plugins-base", + "gstreamer1.0-plugins-good", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libcairo2", + "libdbus-1-3", + "libdrm2", + "libegl1", + "libenchant-2-2", + "libepoxy0", + "libevdev2", + "libfontconfig1", + "libfreetype6", + "libgbm1", + "libgdk-pixbuf-2.0-0", + "libgles2", + "libglib2.0-0", + "libglx0", + "libgstreamer-gl1.0-0", + "libgstreamer-plugins-base1.0-0", + "libgstreamer1.0-0", + "libgtk-3-0", + "libgudev-1.0-0", + "libharfbuzz-icu0", + "libharfbuzz0b", + "libhyphen0", + "libicu67", + "libjpeg62-turbo", + "liblcms2-2", + "libmanette-0.2-0", + "libnghttp2-14", + "libnotify4", + "libopengl0", + "libopenjp2-7", + "libopus0", + "libpango-1.0-0", + "libpng16-16", + "libproxy1v5", + "libsecret-1-0", + "libwayland-client0", + "libwayland-egl1", + "libwayland-server0", + "libwebp6", + "libwebpdemux2", + "libwoff1", + "libx11-6", + "libxcomposite1", + "libxdamage1", + "libxkbcommon0", + "libxml2", + "libxslt1.1", + "libatomic1", + "libevent-2.1-7" + ], + lib2package: { + "libasound.so.2": "libasound2", + "libatk-1.0.so.0": "libatk1.0-0", + "libatk-bridge-2.0.so.0": "libatk-bridge2.0-0", + "libatspi.so.0": "libatspi2.0-0", + "libcairo-gobject.so.2": "libcairo-gobject2", + "libcairo.so.2": "libcairo2", + "libcups.so.2": "libcups2", + "libdbus-1.so.3": "libdbus-1-3", + "libdbus-glib-1.so.2": "libdbus-glib-1-2", + "libdrm.so.2": "libdrm2", + "libEGL.so.1": "libegl1", + "libenchant-2.so.2": "libenchant-2-2", + "libepoxy.so.0": "libepoxy0", + "libevdev.so.2": "libevdev2", + "libfontconfig.so.1": "libfontconfig1", + "libfreetype.so.6": "libfreetype6", + "libgbm.so.1": "libgbm1", + "libgdk_pixbuf-2.0.so.0": "libgdk-pixbuf-2.0-0", + "libgdk-3.so.0": "libgtk-3-0", + "libgio-2.0.so.0": "libglib2.0-0", + "libGLESv2.so.2": "libgles2", + "libglib-2.0.so.0": "libglib2.0-0", + "libGLX.so.0": "libglx0", + "libgmodule-2.0.so.0": "libglib2.0-0", + "libgobject-2.0.so.0": "libglib2.0-0", + "libgstallocators-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstapp-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstaudio-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstbase-1.0.so.0": "libgstreamer1.0-0", + "libgstfft-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstgl-1.0.so.0": "libgstreamer-gl1.0-0", + "libgstpbutils-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstreamer-1.0.so.0": "libgstreamer1.0-0", + "libgsttag-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgstvideo-1.0.so.0": "libgstreamer-plugins-base1.0-0", + "libgtk-3.so.0": "libgtk-3-0", + "libgudev-1.0.so.0": "libgudev-1.0-0", + "libharfbuzz-icu.so.0": "libharfbuzz-icu0", + "libharfbuzz.so.0": "libharfbuzz0b", + "libhyphen.so.0": "libhyphen0", + "libicui18n.so.67": "libicu67", + "libicuuc.so.67": "libicu67", + "libjpeg.so.62": "libjpeg62-turbo", + "liblcms2.so.2": "liblcms2-2", + "libmanette-0.2.so.0": "libmanette-0.2-0", + "libnotify.so.4": "libnotify4", + "libnspr4.so": "libnspr4", + "libnss3.so": "libnss3", + "libnssutil3.so": "libnss3", + "libOpenGL.so.0": "libopengl0", + "libopenjp2.so.7": "libopenjp2-7", + "libopus.so.0": "libopus0", + "libpango-1.0.so.0": "libpango-1.0-0", + "libpangocairo-1.0.so.0": "libpangocairo-1.0-0", + "libpng16.so.16": "libpng16-16", + "libproxy.so.1": "libproxy1v5", + "libsecret-1.so.0": "libsecret-1-0", + "libsmime3.so": "libnss3", + "libwayland-client.so.0": "libwayland-client0", + "libwayland-egl.so.1": "libwayland-egl1", + "libwayland-server.so.0": "libwayland-server0", + "libwebp.so.6": "libwebp6", + "libwebpdemux.so.2": "libwebpdemux2", + "libwoff2dec.so.1.0.2": "libwoff1", + "libX11-xcb.so.1": "libx11-xcb1", + "libX11.so.6": "libx11-6", + "libxcb-shm.so.0": "libxcb-shm0", + "libxcb.so.1": "libxcb1", + "libXcomposite.so.1": "libxcomposite1", + "libXcursor.so.1": "libxcursor1", + "libXdamage.so.1": "libxdamage1", + "libXext.so.6": "libxext6", + "libXfixes.so.3": "libxfixes3", + "libXi.so.6": "libxi6", + "libxkbcommon.so.0": "libxkbcommon0", + "libxml2.so.2": "libxml2", + "libXrandr.so.2": "libxrandr2", + "libXrender.so.1": "libxrender1", + "libxslt.so.1": "libxslt1.1", + "libXtst.so.6": "libxtst6", + "libatomic.so.1": "libatomic1", + "libevent-2.1.so.7": "libevent-2.1-7" + } + }, + "debian12-x64": { + tools: [ + "xvfb", + "fonts-noto-color-emoji", + "fonts-unifont", + "libfontconfig1", + "libfreetype6", + "xfonts-scalable", + "fonts-liberation", + "fonts-ipafont-gothic", + "fonts-wqy-zenhei", + "fonts-tlwg-loma-otf", + "fonts-freefont-ttf" + ], + chromium: [ + "libasound2", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libatspi2.0-0", + "libcairo2", + "libcups2", + "libdbus-1-3", + "libdrm2", + "libgbm1", + "libglib2.0-0", + "libnspr4", + "libnss3", + "libpango-1.0-0", + "libx11-6", + "libxcb1", + "libxcomposite1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxkbcommon0", + "libxrandr2" + ], + firefox: [ + "libasound2", + "libatk1.0-0", + "libcairo-gobject2", + "libcairo2", + "libdbus-1-3", + "libdbus-glib-1-2", + "libfontconfig1", + "libfreetype6", + "libgdk-pixbuf-2.0-0", + "libglib2.0-0", + "libgtk-3-0", + "libharfbuzz0b", + "libpango-1.0-0", + "libpangocairo-1.0-0", + "libx11-6", + "libx11-xcb1", + "libxcb-shm0", + "libxcb1", + "libxcomposite1", + "libxcursor1", + "libxdamage1", + "libxext6", + "libxfixes3", + "libxi6", + "libxrandr2", + "libxrender1", + "libxtst6" + ], + webkit: [ + "libsoup-3.0-0", + "gstreamer1.0-libav", + "gstreamer1.0-plugins-bad", + "gstreamer1.0-plugins-base", + "gstreamer1.0-plugins-good", + "libatk-bridge2.0-0", + "libatk1.0-0", + "libcairo2", + "libdbus-1-3", + "libdrm2", + "libegl1", + "libenchant-2-2", + "libepoxy0", + "libevdev2", + "libfontconfig1", + "libfreetype6", + "libgbm1", + "libgdk-pixbuf-2.0-0", + "libgles2", + "libglib2.0-0", + "libglx0", + "libgstreamer-gl1.0-0", + "libgstreamer-plugins-base1.0-0", + "libgstreamer1.0-0", + "libgtk-4-1", + "libgudev-1.0-0", + "libharfbuzz-icu0", + "libharfbuzz0b", + "libhyphen0", + "libicu72", + "libjpeg62-turbo", + "liblcms2-2", + "libmanette-0.2-0", + "libnotify4", + "libopengl0", + "libopenjp2-7", + "libopus0", + "libpango-1.0-0", + "libpng16-16", + "libproxy1v5", + "libsecret-1-0", + "libwayland-client0", + "libwayland-egl1", + "libwayland-server0", + "libwebp7", + "libwebpdemux2", + "libwoff1", + "libx11-6", + "libxcomposite1", + "libxdamage1", + "libxkbcommon0", + "libxml2", + "libxslt1.1", + "libatomic1", + "libevent-2.1-7", + "libavif15" + ], + lib2package: { + "libavif.so.15": "libavif15", + "libsoup-3.0.so.0": "libsoup-3.0-0", + "libasound.so.2": "libasound2", + "libatk-1.0.so.0": "libatk1.0-0", + "libatk-bridge-2.0.so.0": "libatk-bridge2.0-0", + "libatspi.so.0": "libatspi2.0-0", + "libcairo.so.2": "libcairo2", + "libcups.so.2": "libcups2", + "libdbus-1.so.3": "libdbus-1-3", + "libdrm.so.2": "libdrm2", + "libgbm.so.1": "libgbm1", + "libgio-2.0.so.0": "libglib2.0-0", + "libglib-2.0.so.0": "libglib2.0-0", + "libgobject-2.0.so.0": "libglib2.0-0", + "libnspr4.so": "libnspr4", + "libnss3.so": "libnss3", + "libnssutil3.so": "libnss3", + "libpango-1.0.so.0": "libpango-1.0-0", + "libsmime3.so": "libnss3", + "libX11.so.6": "libx11-6", + "libxcb.so.1": "libxcb1", + "libXcomposite.so.1": "libxcomposite1", + "libXdamage.so.1": "libxdamage1", + "libXext.so.6": "libxext6", + "libXfixes.so.3": "libxfixes3", + "libxkbcommon.so.0": "libxkbcommon0", + "libXrandr.so.2": "libxrandr2", + "libgtk-4.so.1": "libgtk-4-1" + } + } +}; +deps["ubuntu20.04-arm64"] = { + tools: [...deps["ubuntu20.04-x64"].tools], + chromium: [...deps["ubuntu20.04-x64"].chromium], + firefox: [ + ...deps["ubuntu20.04-x64"].firefox + ], + webkit: [ + ...deps["ubuntu20.04-x64"].webkit + ], + lib2package: { + ...deps["ubuntu20.04-x64"].lib2package + } +}; +deps["ubuntu22.04-arm64"] = { + tools: [...deps["ubuntu22.04-x64"].tools], + chromium: [...deps["ubuntu22.04-x64"].chromium], + firefox: [ + ...deps["ubuntu22.04-x64"].firefox + ], + webkit: [ + ...deps["ubuntu22.04-x64"].webkit + ], + lib2package: { + ...deps["ubuntu22.04-x64"].lib2package + } +}; +deps["ubuntu24.04-arm64"] = { + tools: [...deps["ubuntu24.04-x64"].tools], + chromium: [...deps["ubuntu24.04-x64"].chromium], + firefox: [ + ...deps["ubuntu24.04-x64"].firefox + ], + webkit: [ + ...deps["ubuntu24.04-x64"].webkit + ], + lib2package: { + ...deps["ubuntu24.04-x64"].lib2package + } +}; +deps["debian11-arm64"] = { + tools: [...deps["debian11-x64"].tools], + chromium: [...deps["debian11-x64"].chromium], + firefox: [ + ...deps["debian11-x64"].firefox + ], + webkit: [ + ...deps["debian11-x64"].webkit + ], + lib2package: { + ...deps["debian11-x64"].lib2package + } +}; +deps["debian12-arm64"] = { + tools: [...deps["debian12-x64"].tools], + chromium: [...deps["debian12-x64"].chromium], + firefox: [ + ...deps["debian12-x64"].firefox + ], + webkit: [ + ...deps["debian12-x64"].webkit + ], + lib2package: { + ...deps["debian12-x64"].lib2package + } +}; +function wrapInASCIIBox(text, padding = 0) { + const lines = text.split("\n"); + const maxLength = Math.max(...lines.map((line) => line.length)); + return [ + "╔" + "═".repeat(maxLength + padding * 2) + "╗", + ...lines.map((line) => "║" + " ".repeat(padding) + line + " ".repeat(maxLength - line.length + padding) + "║"), + "╚" + "═".repeat(maxLength + padding * 2) + "╝" + ].join("\n"); +} +function calculatePlatform() { + if (define_process_env_default.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE) { + return { + hostPlatform: define_process_env_default.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE, + isOfficiallySupportedPlatform: false + }; + } + const platform = os.platform(); + if (platform === "darwin") { + const ver = os.release().split(".").map((a) => parseInt(a, 10)); + let macVersion = ""; + if (ver[0] < 18) { + macVersion = "mac10.13"; + } else if (ver[0] === 18) { + macVersion = "mac10.14"; + } else if (ver[0] === 19) { + macVersion = "mac10.15"; + } else { + const LAST_STABLE_MACOS_MAJOR_VERSION = 15; + macVersion = "mac" + Math.min(ver[0] - 9, LAST_STABLE_MACOS_MAJOR_VERSION); + if (os.cpus().some((cpu) => cpu.model.includes("Apple"))) + macVersion += "-arm64"; + } + return { hostPlatform: macVersion, isOfficiallySupportedPlatform: true }; + } + if (platform === "linux") { + if (!["x64", "arm64"].includes(os.arch())) + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; + const archSuffix = "-" + os.arch(); + const distroInfo = getLinuxDistributionInfoSync(); + if ((distroInfo == null ? void 0 : distroInfo.id) === "ubuntu" || (distroInfo == null ? void 0 : distroInfo.id) === "pop" || (distroInfo == null ? void 0 : distroInfo.id) === "neon" || (distroInfo == null ? void 0 : distroInfo.id) === "tuxedo") { + const isUbuntu = (distroInfo == null ? void 0 : distroInfo.id) === "ubuntu"; + const version2 = distroInfo == null ? void 0 : distroInfo.version; + const major = parseInt(distroInfo.version, 10); + if (major < 20) + return { hostPlatform: "ubuntu18.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (major < 22) + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version2 === "20.04" }; + if (major < 24) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version2 === "22.04" }; + if (major < 26) + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version2 === "24.04" }; + return { hostPlatform: "ubuntu" + distroInfo.version + archSuffix, isOfficiallySupportedPlatform: false }; + } + if ((distroInfo == null ? void 0 : distroInfo.id) === "linuxmint") { + const mintMajor = parseInt(distroInfo.version, 10); + if (mintMajor <= 20) + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (mintMajor === 21) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: false }; + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if ((distroInfo == null ? void 0 : distroInfo.id) === "debian" || (distroInfo == null ? void 0 : distroInfo.id) === "raspbian") { + const isOfficiallySupportedPlatform2 = (distroInfo == null ? void 0 : distroInfo.id) === "debian"; + if ((distroInfo == null ? void 0 : distroInfo.version) === "11") + return { hostPlatform: "debian11" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if ((distroInfo == null ? void 0 : distroInfo.version) === "12") + return { hostPlatform: "debian12" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if ((distroInfo == null ? void 0 : distroInfo.version) === "") + return { hostPlatform: "debian12" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + } + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (platform === "win32") + return { hostPlatform: "win64", isOfficiallySupportedPlatform: true }; + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; +} +const { hostPlatform, isOfficiallySupportedPlatform } = calculatePlatform(); +function spawnAsync(cmd, args, options2 = {}) { + const process2 = spawn(cmd, args, Object.assign({ windowsHide: true }, options2)); + return new Promise((resolve) => { + let stdout = ""; + let stderr = ""; + if (process2.stdout) + process2.stdout.on("data", (data2) => stdout += data2.toString()); + if (process2.stderr) + process2.stderr.on("data", (data2) => stderr += data2.toString()); + process2.on("close", (code) => resolve({ stdout, stderr, code })); + process2.on("error", (error2) => resolve({ stdout, stderr, code: 0, error: error2 })); + }); +} +const BIN_DIRECTORY = path.join("playwright/packages/playwright-core/src/server/registry", "..", "..", "..", "bin"); +const languageBindingVersion = define_process_env_default.PW_CLI_DISPLAY_VERSION || require$$0$1.version; +const dockerVersionFilePath = "/ms-playwright/.docker-info"; +function dockerVersion(dockerImageNameTemplate) { + return { + driverVersion: languageBindingVersion, + dockerImageName: dockerImageNameTemplate.replace("%version%", languageBindingVersion) + }; +} +function readDockerVersionSync() { + try { + const data2 = JSON.parse(fs.readFileSync(dockerVersionFilePath, "utf8")); + return { + ...data2, + dockerImageNameTemplate: data2.dockerImageName.replace(data2.driverVersion, "%version%") + }; + } catch (e) { + return null; + } +} +const checkExecutable = (filePath) => { + if (process.platform === "win32") + return filePath.endsWith(".exe"); + return fs.promises.access(filePath, fs.constants.X_OK).then(() => true).catch(() => false); +}; +function isSupportedWindowsVersion() { + if (os.platform() !== "win32" || os.arch() !== "x64") + return false; + const [major, minor] = os.release().split(".").map((token) => parseInt(token, 10)); + return major > 6 || major === 6 && minor > 1; +} +async function installDependenciesWindows(targets, dryRun) { + if (targets.has("chromium")) { + const command2 = "powershell.exe"; + const args = ["-ExecutionPolicy", "Bypass", "-File", path.join(BIN_DIRECTORY, "install_media_pack.ps1")]; + if (dryRun) { + console.log(`${command2} ${quoteProcessArgs(args).join(" ")}`); + return; + } + const { code } = await spawnAsync(command2, args, { cwd: BIN_DIRECTORY, stdio: "inherit" }); + if (code !== 0) + throw new Error("Failed to install windows dependencies!"); + } +} +async function installDependenciesLinux(targets, dryRun) { + const libraries = []; + const platform = hostPlatform; + if (!isOfficiallySupportedPlatform) + console.warn(`BEWARE: your OS is not officially supported by Playwright; installing dependencies for ${platform} as a fallback.`); + for (const target of targets) { + const info = deps[platform]; + if (!info) { + console.warn(`Cannot install dependencies for ${platform} with Playwright ${getPlaywrightVersion()}!`); + return; + } + libraries.push(...info[target]); + } + const uniqueLibraries = Array.from(new Set(libraries)); + if (!dryRun) + console.log(`Installing dependencies...`); + const commands = []; + commands.push("apt-get update"); + commands.push([ + "apt-get", + "install", + "-y", + "--no-install-recommends", + ...uniqueLibraries + ].join(" ")); + const { command: command2, args, elevatedPermissions } = await transformCommandsForRoot(commands); + if (dryRun) { + console.log(`${command2} ${quoteProcessArgs(args).join(" ")}`); + return; + } + if (elevatedPermissions) + console.log("Switching to root user to install dependencies..."); + const child = spawn(); + await new Promise((resolve, reject) => { + child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`Installation process exited with code: ${code}`))); + child.on("error", reject); + }); +} +async function validateDependenciesWindows(sdkLanguage, windowsExeAndDllDirectories) { + const directoryPaths = windowsExeAndDllDirectories; + const lddPaths = []; + for (const directoryPath of directoryPaths) + lddPaths.push(...await executablesOrSharedLibraries(directoryPath)); + const allMissingDeps = await Promise.all(lddPaths.map((lddPath) => missingFileDependenciesWindows(sdkLanguage, lddPath))); + const missingDeps = /* @__PURE__ */ new Set(); + for (const deps2 of allMissingDeps) { + for (const dep of deps2) + missingDeps.add(dep); + } + if (!missingDeps.size) + return; + let isCrtMissing = false; + let isMediaFoundationMissing = false; + for (const dep of missingDeps) { + if (dep.startsWith("api-ms-win-crt") || dep === "vcruntime140.dll" || dep === "vcruntime140_1.dll" || dep === "msvcp140.dll") + isCrtMissing = true; + else if (dep === "mf.dll" || dep === "mfplat.dll" || dep === "msmpeg2vdec.dll" || dep === "evr.dll" || dep === "avrt.dll") + isMediaFoundationMissing = true; + } + const details = []; + if (isCrtMissing) { + details.push( + `Some of the Universal C Runtime files cannot be found on the system. You can fix`, + `that by installing Microsoft Visual C++ Redistributable for Visual Studio from:`, + `https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads`, + `` + ); + } + if (isMediaFoundationMissing) { + details.push( + `Some of the Media Foundation files cannot be found on the system. If you are`, + `on Windows Server try fixing this by running the following command in PowerShell`, + `as Administrator:`, + ``, + ` Install-WindowsFeature Server-Media-Foundation`, + ``, + `For Windows N editions visit:`, + `https://support.microsoft.com/en-us/help/3145500/media-feature-pack-list-for-windows-n-editions`, + `` + ); + } + details.push( + `Full list of missing libraries:`, + ` ${[...missingDeps].join("\n ")}`, + `` + ); + const message = `Host system is missing dependencies! + +${details.join("\n")}`; + if (isSupportedWindowsVersion()) { + throw new Error(message); + } else { + console.warn(`WARNING: running on unsupported windows version!`); + console.warn(message); + } +} +async function validateDependenciesLinux(sdkLanguage, linuxLddDirectories, dlOpenLibraries) { + var _a2, _b2; + const directoryPaths = linuxLddDirectories; + const lddPaths = []; + for (const directoryPath of directoryPaths) + lddPaths.push(...await executablesOrSharedLibraries(directoryPath)); + const missingDepsPerFile = await Promise.all(lddPaths.map((lddPath) => missingFileDependencies(lddPath, directoryPaths))); + const missingDeps = /* @__PURE__ */ new Set(); + for (const deps2 of missingDepsPerFile) { + for (const dep of deps2) + missingDeps.add(dep); + } + for (const dep of await missingDLOPENLibraries(dlOpenLibraries)) + missingDeps.add(dep); + if (!missingDeps.size) + return; + const allMissingDeps = new Set(missingDeps); + const missingPackages = /* @__PURE__ */ new Set(); + const libraryToPackageNameMapping = deps[hostPlatform] ? { + ...((_a2 = deps[hostPlatform]) == null ? void 0 : _a2.lib2package) || {}, + ...MANUAL_LIBRARY_TO_PACKAGE_NAME_UBUNTU + } : {}; + for (const missingDep of missingDeps) { + const packageName = libraryToPackageNameMapping[missingDep]; + if (packageName) { + missingPackages.add(packageName); + missingDeps.delete(missingDep); + } + } + const maybeSudo = ((_b2 = process.getuid) == null ? void 0 : _b2.call(process)) && os.platform() !== "win32" ? "sudo " : ""; + const dockerInfo = readDockerVersionSync(); + const errorLines = [ + `Host system is missing dependencies to run browsers.` + ]; + if (dockerInfo && !dockerInfo.driverVersion.startsWith(getPlaywrightVersion( + true + /* majorMinorOnly */ + ) + ".")) { + const pwVersion = getPlaywrightVersion(); + const requiredDockerImage = dockerInfo.dockerImageName.replace(dockerInfo.driverVersion, pwVersion); + errorLines.push(...[ + `This is most likely due to Docker image version not matching Playwright version:`, + `- Playwright : ${pwVersion}`, + `- Docker image: ${dockerInfo.driverVersion}`, + ``, + `Either:`, + `- (recommended) use Docker image "${requiredDockerImage}"`, + `- (alternative 1) run the following command inside Docker to install missing dependencies:`, + ``, + ` ${maybeSudo}${buildPlaywrightCLICommand(sdkLanguage, "install-deps")}`, + ``, + `- (alternative 2) use apt inside Docker:`, + ``, + ` ${maybeSudo}apt-get install ${[...missingPackages].join("\\\n ")}`, + ``, + `<3 Playwright Team` + ]); + } else if (missingPackages.size && !missingDeps.size) { + errorLines.push(...[ + `Please install them with the following command:`, + ``, + ` ${maybeSudo}${buildPlaywrightCLICommand(sdkLanguage, "install-deps")}`, + ``, + `Alternatively, use apt:`, + ` ${maybeSudo}apt-get install ${[...missingPackages].join("\\\n ")}`, + ``, + `<3 Playwright Team` + ]); + } else { + errorLines.push(...[ + `Missing libraries:`, + ...[...allMissingDeps].map((dep) => " " + dep) + ]); + } + throw new Error("\n" + wrapInASCIIBox(errorLines.join("\n"), 1)); +} +function isSharedLib(basename) { + switch (os.platform()) { + case "linux": + return basename.endsWith(".so") || basename.includes(".so."); + case "win32": + return basename.endsWith(".dll"); + default: + return false; + } +} +async function executablesOrSharedLibraries(directoryPath) { + if (!fs.existsSync(directoryPath)) + return []; + const allPaths = (await fs.promises.readdir(directoryPath)).map((file) => path.resolve(directoryPath, file)); + const allStats = await Promise.all(allPaths.map((aPath) => fs.promises.stat(aPath))); + const filePaths = allPaths.filter((aPath, index2) => allStats[index2].isFile()); + const executablersOrLibraries = (await Promise.all(filePaths.map(async (filePath) => { + const basename = path.basename(filePath).toLowerCase(); + if (isSharedLib(basename)) + return filePath; + if (await checkExecutable(filePath)) + return filePath; + return false; + }))).filter(Boolean); + return executablersOrLibraries; +} +async function missingFileDependenciesWindows(sdkLanguage, filePath) { + const executable = registry.findExecutable("winldd").executablePathOrDie(sdkLanguage); + const dirname = path.dirname(filePath); + const { stdout, code } = await spawnAsync(executable, [filePath], { + cwd: dirname, + env: { + ...define_process_env_default, + LD_LIBRARY_PATH: define_process_env_default.LD_LIBRARY_PATH ? `${define_process_env_default.LD_LIBRARY_PATH}:${dirname}` : dirname + } + }); + if (code !== 0) + return []; + const missingDeps = stdout.split("\n").map((line) => line.trim()).filter((line) => line.endsWith("not found") && line.includes("=>")).map((line) => line.split("=>")[0].trim().toLowerCase()); + return missingDeps; +} +async function missingFileDependencies(filePath, extraLDPaths) { + const dirname = path.dirname(filePath); + let LD_LIBRARY_PATH = extraLDPaths.join(":"); + if (define_process_env_default.LD_LIBRARY_PATH) + LD_LIBRARY_PATH = `${define_process_env_default.LD_LIBRARY_PATH}:${LD_LIBRARY_PATH}`; + const { stdout, code } = await spawnAsync("ldd", [filePath], { + cwd: dirname, + env: { + ...define_process_env_default, + LD_LIBRARY_PATH + } + }); + if (code !== 0) + return []; + const missingDeps = stdout.split("\n").map((line) => line.trim()).filter((line) => line.endsWith("not found") && line.includes("=>")).map((line) => line.split("=>")[0].trim()); + return missingDeps; +} +async function missingDLOPENLibraries(libraries) { + if (!libraries.length) + return []; + const { stdout, code, error: error2 } = await spawnAsync("/sbin/ldconfig", ["-p"], {}); + if (code !== 0 || error2) + return []; + const isLibraryAvailable = (library) => stdout.toLowerCase().includes(library.toLowerCase()); + return libraries.filter((library) => !isLibraryAvailable(library)); +} +const MANUAL_LIBRARY_TO_PACKAGE_NAME_UBUNTU = { + // libgstlibav.so (the only actual library provided by gstreamer1.0-libav) is not + // in the ldconfig cache, so we detect the actual library required for playing h.264 + // and if it's missing recommend installing missing gstreamer lib. + // gstreamer1.0-libav -> libavcodec57 -> libx264-152 + "libx264.so": "gstreamer1.0-libav" +}; +function quoteProcessArgs(args) { + return args.map((arg) => { + if (arg.includes(" ")) + return `"${arg}"`; + return arg; + }); +} +async function transformCommandsForRoot(commands) { + var _a2; + const isRoot = ((_a2 = process.getuid) == null ? void 0 : _a2.call(process)) === 0; + if (isRoot) + return { command: "sh", args: ["-c", `${commands.join("&& ")}`], elevatedPermissions: false }; + const sudoExists = await spawnAsync("which", ["sudo"]); + if (sudoExists.code === 0) + return { command: "sudo", args: ["--", "sh", "-c", `${commands.join("&& ")}`], elevatedPermissions: true }; + return { command: "su", args: ["root", "-c", `${commands.join("&& ")}`], elevatedPermissions: true }; +} +function assert(value, message) { + if (!value) + throw new Error(message || "Assertion error"); +} +function headersObjectToArray(headers, separator, setCookieSeparator) { + if (!setCookieSeparator) + setCookieSeparator = separator; + const result = []; + for (const name in headers) { + const values = headers[name]; + if (values === void 0) + continue; + if (separator) { + const sep = name.toLowerCase() === "set-cookie" ? setCookieSeparator : separator; + for (const value of values.split(sep)) + result.push({ name, value: value.trim() }); + } else { + result.push({ name, value: values }); + } + } + return result; +} +function headersArrayToObject(headers, lowerCase) { + const result = {}; + for (const { name, value } of headers) + result[lowerCase ? name.toLowerCase() : name] = value; + return result; +} +const between = function(num, first, last) { + return num >= first && num <= last; +}; +function digit(code) { + return between(code, 48, 57); +} +function hexdigit(code) { + return digit(code) || between(code, 65, 70) || between(code, 97, 102); +} +function uppercaseletter(code) { + return between(code, 65, 90); +} +function lowercaseletter(code) { + return between(code, 97, 122); +} +function letter(code) { + return uppercaseletter(code) || lowercaseletter(code); +} +function nonascii(code) { + return code >= 128; +} +function namestartchar(code) { + return letter(code) || nonascii(code) || code === 95; +} +function namechar(code) { + return namestartchar(code) || digit(code) || code === 45; +} +function nonprintable(code) { + return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127; +} +function newline(code) { + return code === 10; +} +function whitespace(code) { + return newline(code) || code === 9 || code === 32; +} +const maximumallowedcodepoint = 1114111; +class InvalidCharacterError extends Error { + constructor(message) { + super(message); + this.name = "InvalidCharacterError"; + } +} +function preprocess(str) { + const codepoints = []; + for (let i = 0; i < str.length; i++) { + let code = str.charCodeAt(i); + if (code === 13 && str.charCodeAt(i + 1) === 10) { + code = 10; + i++; + } + if (code === 13 || code === 12) + code = 10; + if (code === 0) + code = 65533; + if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) { + const lead = code - 55296; + const trail = str.charCodeAt(i + 1) - 56320; + code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail; + i++; + } + codepoints.push(code); + } + return codepoints; +} +function stringFromCode(code) { + if (code <= 65535) + return String.fromCharCode(code); + code -= Math.pow(2, 16); + const lead = Math.floor(code / Math.pow(2, 10)) + 55296; + const trail = code % Math.pow(2, 10) + 56320; + return String.fromCharCode(lead) + String.fromCharCode(trail); +} +function tokenize2(str1) { + const str = preprocess(str1); + let i = -1; + const tokens = []; + let code; + const codepoint = function(i2) { + if (i2 >= str.length) + return -1; + return str[i2]; + }; + const next = function(num) { + if (num === void 0) + num = 1; + if (num > 3) + throw "Spec Error: no more than three codepoints of lookahead."; + return codepoint(i + num); + }; + const consume = function(num) { + if (num === void 0) + num = 1; + i += num; + code = codepoint(i); + return true; + }; + const reconsume = function() { + i -= 1; + return true; + }; + const eof = function(codepoint2) { + if (codepoint2 === void 0) + codepoint2 = code; + return codepoint2 === -1; + }; + const consumeAToken = function() { + consumeComments(); + consume(); + if (whitespace(code)) { + while (whitespace(next())) + consume(); + return new WhitespaceToken(); + } else if (code === 34) { + return consumeAStringToken(); + } else if (code === 35) { + if (namechar(next()) || areAValidEscape(next(1), next(2))) { + const token = new HashToken(""); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + token.type = "id"; + token.value = consumeAName(); + return token; + } else { + return new DelimToken(code); + } + } else if (code === 36) { + if (next() === 61) { + consume(); + return new SuffixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 39) { + return consumeAStringToken(); + } else if (code === 40) { + return new OpenParenToken(); + } else if (code === 41) { + return new CloseParenToken(); + } else if (code === 42) { + if (next() === 61) { + consume(); + return new SubstringMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 43) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code === 44) { + return new CommaToken(); + } else if (code === 45) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else if (next(1) === 45 && next(2) === 62) { + consume(2); + return new CDCToken(); + } else if (startsWithAnIdentifier()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + return new DelimToken(code); + } + } else if (code === 46) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code === 58) { + return new ColonToken(); + } else if (code === 59) { + return new SemicolonToken(); + } else if (code === 60) { + if (next(1) === 33 && next(2) === 45 && next(3) === 45) { + consume(3); + return new CDOToken(); + } else { + return new DelimToken(code); + } + } else if (code === 64) { + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + return new AtKeywordToken(consumeAName()); + else + return new DelimToken(code); + } else if (code === 91) { + return new OpenSquareToken(); + } else if (code === 92) { + if (startsWithAValidEscape()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + return new DelimToken(code); + } + } else if (code === 93) { + return new CloseSquareToken(); + } else if (code === 94) { + if (next() === 61) { + consume(); + return new PrefixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 123) { + return new OpenCurlyToken(); + } else if (code === 124) { + if (next() === 61) { + consume(); + return new DashMatchToken(); + } else if (next() === 124) { + consume(); + return new ColumnToken(); + } else { + return new DelimToken(code); + } + } else if (code === 125) { + return new CloseCurlyToken(); + } else if (code === 126) { + if (next() === 61) { + consume(); + return new IncludeMatchToken(); + } else { + return new DelimToken(code); + } + } else if (digit(code)) { + reconsume(); + return consumeANumericToken(); + } else if (namestartchar(code)) { + reconsume(); + return consumeAnIdentlikeToken(); + } else if (eof()) { + return new EOFToken(); + } else { + return new DelimToken(code); + } + }; + const consumeComments = function() { + while (next(1) === 47 && next(2) === 42) { + consume(2); + while (true) { + consume(); + if (code === 42 && next() === 47) { + consume(); + break; + } else if (eof()) { + return; + } + } + } + }; + const consumeANumericToken = function() { + const num = consumeANumber(); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) { + const token = new DimensionToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + token.unit = consumeAName(); + return token; + } else if (next() === 37) { + consume(); + const token = new PercentageToken(); + token.value = num.value; + token.repr = num.repr; + return token; + } else { + const token = new NumberToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + return token; + } + }; + const consumeAnIdentlikeToken = function() { + const str2 = consumeAName(); + if (str2.toLowerCase() === "url" && next() === 40) { + consume(); + while (whitespace(next(1)) && whitespace(next(2))) + consume(); + if (next() === 34 || next() === 39) + return new FunctionToken(str2); + else if (whitespace(next()) && (next(2) === 34 || next(2) === 39)) + return new FunctionToken(str2); + else + return consumeAURLToken(); + } else if (next() === 40) { + consume(); + return new FunctionToken(str2); + } else { + return new IdentToken(str2); + } + }; + const consumeAStringToken = function(endingCodePoint) { + if (endingCodePoint === void 0) + endingCodePoint = code; + let string2 = ""; + while (consume()) { + if (code === endingCodePoint || eof()) { + return new StringToken(string2); + } else if (newline(code)) { + reconsume(); + return new BadStringToken(); + } else if (code === 92) { + if (eof(next())) + ; + else if (newline(next())) + consume(); + else + string2 += stringFromCode(consumeEscape()); + } else { + string2 += stringFromCode(code); + } + } + throw new Error("Internal error"); + }; + const consumeAURLToken = function() { + const token = new URLToken(""); + while (whitespace(next())) + consume(); + if (eof(next())) + return token; + while (consume()) { + if (code === 41 || eof()) { + return token; + } else if (whitespace(code)) { + while (whitespace(next())) + consume(); + if (next() === 41 || eof(next())) { + consume(); + return token; + } else { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } else if (code === 92) { + if (startsWithAValidEscape()) { + token.value += stringFromCode(consumeEscape()); + } else { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else { + token.value += stringFromCode(code); + } + } + throw new Error("Internal error"); + }; + const consumeEscape = function() { + consume(); + if (hexdigit(code)) { + const digits = [code]; + for (let total = 0; total < 5; total++) { + if (hexdigit(next())) { + consume(); + digits.push(code); + } else { + break; + } + } + if (whitespace(next())) + consume(); + let value = parseInt(digits.map(function(x) { + return String.fromCharCode(x); + }).join(""), 16); + if (value > maximumallowedcodepoint) + value = 65533; + return value; + } else if (eof()) { + return 65533; + } else { + return code; + } + }; + const areAValidEscape = function(c1, c2) { + if (c1 !== 92) + return false; + if (newline(c2)) + return false; + return true; + }; + const startsWithAValidEscape = function() { + return areAValidEscape(code, next()); + }; + const wouldStartAnIdentifier = function(c1, c2, c3) { + if (c1 === 45) + return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3); + else if (namestartchar(c1)) + return true; + else if (c1 === 92) + return areAValidEscape(c1, c2); + else + return false; + }; + const startsWithAnIdentifier = function() { + return wouldStartAnIdentifier(code, next(1), next(2)); + }; + const wouldStartANumber = function(c1, c2, c3) { + if (c1 === 43 || c1 === 45) { + if (digit(c2)) + return true; + if (c2 === 46 && digit(c3)) + return true; + return false; + } else if (c1 === 46) { + if (digit(c2)) + return true; + return false; + } else if (digit(c1)) { + return true; + } else { + return false; + } + }; + const startsWithANumber = function() { + return wouldStartANumber(code, next(1), next(2)); + }; + const consumeAName = function() { + let result = ""; + while (consume()) { + if (namechar(code)) { + result += stringFromCode(code); + } else if (startsWithAValidEscape()) { + result += stringFromCode(consumeEscape()); + } else { + reconsume(); + return result; + } + } + throw new Error("Internal parse error"); + }; + const consumeANumber = function() { + let repr = ""; + let type2 = "integer"; + if (next() === 43 || next() === 45) { + consume(); + repr += stringFromCode(code); + } + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + if (next(1) === 46 && digit(next(2))) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type2 = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + const c1 = next(1), c2 = next(2), c3 = next(3); + if ((c1 === 69 || c1 === 101) && digit(c2)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type2 = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type2 = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + const value = convertAStringToANumber(repr); + return { type: type2, value, repr }; + }; + const convertAStringToANumber = function(string2) { + return +string2; + }; + const consumeTheRemnantsOfABadURL = function() { + while (consume()) { + if (code === 41 || eof()) { + return; + } else if (startsWithAValidEscape()) { + consumeEscape(); + } else ; + } + }; + let iterationCount = 0; + while (!eof(next())) { + tokens.push(consumeAToken()); + iterationCount++; + if (iterationCount > str.length * 2) + throw new Error("I'm infinite-looping!"); + } + return tokens; +} +class CSSParserToken { + constructor() { + this.tokenType = ""; + } + toJSON() { + return { token: this.tokenType }; + } + toString() { + return this.tokenType; + } + toSource() { + return "" + this; + } +} +class BadStringToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "BADSTRING"; + } +} +class BadURLToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "BADURL"; + } +} +class WhitespaceToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "WHITESPACE"; + } + toString() { + return "WS"; + } + toSource() { + return " "; + } +} +class CDOToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "CDO"; + } + toSource() { + return ""; + } +} +class ColonToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ":"; + } +} +class SemicolonToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ";"; + } +} +class CommaToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ","; + } +} +class GroupingToken extends CSSParserToken { + constructor() { + super(...arguments); + this.value = ""; + this.mirror = ""; + } +} +class OpenCurlyToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "{"; + this.value = "{"; + this.mirror = "}"; + } +} +class CloseCurlyToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "}"; + this.value = "}"; + this.mirror = "{"; + } +} +class OpenSquareToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "["; + this.value = "["; + this.mirror = "]"; + } +} +class CloseSquareToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "]"; + this.value = "]"; + this.mirror = "["; + } +} +class OpenParenToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "("; + this.value = "("; + this.mirror = ")"; + } +} +class CloseParenToken extends GroupingToken { + constructor() { + super(); + this.tokenType = ")"; + this.value = ")"; + this.mirror = "("; + } +} +class IncludeMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "~="; + } +} +class DashMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "|="; + } +} +class PrefixMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "^="; + } +} +class SuffixMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "$="; + } +} +class SubstringMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "*="; + } +} +class ColumnToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "||"; + } +} +class EOFToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "EOF"; + } + toSource() { + return ""; + } +} +class DelimToken extends CSSParserToken { + constructor(code) { + super(); + this.tokenType = "DELIM"; + this.value = ""; + this.value = stringFromCode(code); + } + toString() { + return "DELIM(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + return json; + } + toSource() { + if (this.value === "\\") + return "\\\n"; + else + return this.value; + } +} +class StringValuedToken extends CSSParserToken { + constructor() { + super(...arguments); + this.value = ""; + } + ASCIIMatch(str) { + return this.value.toLowerCase() === str.toLowerCase(); + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + return json; + } +} +class IdentToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "IDENT"; + this.value = val; + } + toString() { + return "IDENT(" + this.value + ")"; + } + toSource() { + return escapeIdent(this.value); + } +} +class FunctionToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "FUNCTION"; + this.value = val; + this.mirror = ")"; + } + toString() { + return "FUNCTION(" + this.value + ")"; + } + toSource() { + return escapeIdent(this.value) + "("; + } +} +class AtKeywordToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "AT-KEYWORD"; + this.value = val; + } + toString() { + return "AT(" + this.value + ")"; + } + toSource() { + return "@" + escapeIdent(this.value); + } +} +class HashToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "HASH"; + this.value = val; + this.type = "unrestricted"; + } + toString() { + return "HASH(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.type = this.type; + return json; + } + toSource() { + if (this.type === "id") + return "#" + escapeIdent(this.value); + else + return "#" + escapeHash(this.value); + } +} +class StringToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "STRING"; + this.value = val; + } + toString() { + return '"' + escapeString(this.value) + '"'; + } +} +class URLToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "URL"; + this.value = val; + } + toString() { + return "URL(" + this.value + ")"; + } + toSource() { + return 'url("' + escapeString(this.value) + '")'; + } +} +class NumberToken extends CSSParserToken { + constructor() { + super(); + this.tokenType = "NUMBER"; + this.type = "integer"; + this.repr = ""; + } + toString() { + if (this.type === "integer") + return "INT(" + this.value + ")"; + return "NUMBER(" + this.value + ")"; + } + toJSON() { + const json = super.toJSON(); + json.value = this.value; + json.type = this.type; + json.repr = this.repr; + return json; + } + toSource() { + return this.repr; + } +} +class PercentageToken extends CSSParserToken { + constructor() { + super(); + this.tokenType = "PERCENTAGE"; + this.repr = ""; + } + toString() { + return "PERCENTAGE(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.repr = this.repr; + return json; + } + toSource() { + return this.repr + "%"; + } +} +class DimensionToken extends CSSParserToken { + constructor() { + super(); + this.tokenType = "DIMENSION"; + this.type = "integer"; + this.repr = ""; + this.unit = ""; + } + toString() { + return "DIM(" + this.value + "," + this.unit + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.type = this.type; + json.repr = this.repr; + json.unit = this.unit; + return json; + } + toSource() { + const source2 = this.repr; + let unit = escapeIdent(this.unit); + if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) { + unit = "\\65 " + unit.slice(1, unit.length); + } + return source2 + unit; + } +} +function escapeIdent(string2) { + string2 = "" + string2; + let result = ""; + const firstcode = string2.charCodeAt(0); + for (let i = 0; i < string2.length; i++) { + const code = string2.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45) + result += "\\" + code.toString(16) + " "; + else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122)) + result += string2[i]; + else + result += "\\" + string2[i]; + } + return result; +} +function escapeHash(string2) { + string2 = "" + string2; + let result = ""; + for (let i = 0; i < string2.length; i++) { + const code = string2.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122)) + result += string2[i]; + else + result += "\\" + code.toString(16) + " "; + } + return result; +} +function escapeString(string2) { + string2 = "" + string2; + let result = ""; + for (let i = 0; i < string2.length; i++) { + const code = string2.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (between(code, 1, 31) || code === 127) + result += "\\" + code.toString(16) + " "; + else if (code === 34 || code === 92) + result += "\\" + string2[i]; + else + result += string2[i]; + } + return result; +} +class InvalidSelectorError extends Error { +} +function isInvalidSelectorError(error2) { + return error2 instanceof InvalidSelectorError; +} +function parseCSS(selector, customNames) { + let tokens; + try { + tokens = tokenize2(selector); + if (!(tokens[tokens.length - 1] instanceof EOFToken)) + tokens.push(new EOFToken()); + } catch (e) { + const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`; + const index2 = (e.stack || "").indexOf(e.message); + if (index2 !== -1) + e.stack = e.stack.substring(0, index2) + newMessage + e.stack.substring(index2 + e.message.length); + e.message = newMessage; + throw e; + } + const unsupportedToken = tokens.find((token) => { + return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings. + // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz } + // Or this way :xpath( {complex-xpath-goes-here("hello")} ) + token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings? + token instanceof URLToken || token instanceof PercentageToken; + }); + if (unsupportedToken) + throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + let pos = 0; + const names = /* @__PURE__ */ new Set(); + function unexpected() { + return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + } + function skipWhitespace() { + while (tokens[pos] instanceof WhitespaceToken) + pos++; + } + function isIdent(p = pos) { + return tokens[p] instanceof IdentToken; + } + function isString2(p = pos) { + return tokens[p] instanceof StringToken; + } + function isNumber(p = pos) { + return tokens[p] instanceof NumberToken; + } + function isComma(p = pos) { + return tokens[p] instanceof CommaToken; + } + function isOpenParen(p = pos) { + return tokens[p] instanceof OpenParenToken; + } + function isCloseParen(p = pos) { + return tokens[p] instanceof CloseParenToken; + } + function isFunction(p = pos) { + return tokens[p] instanceof FunctionToken; + } + function isStar(p = pos) { + return tokens[p] instanceof DelimToken && tokens[p].value === "*"; + } + function isEOF(p = pos) { + return tokens[p] instanceof EOFToken; + } + function isClauseCombinator(p = pos) { + return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value); + } + function isSelectorClauseEnd(p = pos) { + return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken; + } + function consumeFunctionArguments() { + const result2 = [consumeArgument()]; + while (true) { + skipWhitespace(); + if (!isComma()) + break; + pos++; + result2.push(consumeArgument()); + } + return result2; + } + function consumeArgument() { + skipWhitespace(); + if (isNumber()) + return tokens[pos++].value; + if (isString2()) + return tokens[pos++].value; + return consumeComplexSelector(); + } + function consumeComplexSelector() { + const result2 = { simples: [] }; + skipWhitespace(); + if (isClauseCombinator()) { + result2.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" }); + } else { + result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" }); + } + while (true) { + skipWhitespace(); + if (isClauseCombinator()) { + result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value; + skipWhitespace(); + } else if (isSelectorClauseEnd()) { + break; + } + result2.simples.push({ combinator: "", selector: consumeSimpleSelector() }); + } + return result2; + } + function consumeSimpleSelector() { + let rawCSSString = ""; + const functions = []; + while (!isSelectorClauseEnd()) { + if (isIdent() || isStar()) { + rawCSSString += tokens[pos++].toSource(); + } else if (tokens[pos] instanceof HashToken) { + rawCSSString += tokens[pos++].toSource(); + } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") { + pos++; + if (isIdent()) + rawCSSString += "." + tokens[pos++].toSource(); + else + throw unexpected(); + } else if (tokens[pos] instanceof ColonToken) { + pos++; + if (isIdent()) { + if (!customNames.has(tokens[pos].value.toLowerCase())) { + rawCSSString += ":" + tokens[pos++].toSource(); + } else { + const name = tokens[pos++].value.toLowerCase(); + functions.push({ name, args: [] }); + names.add(name); + } + } else if (isFunction()) { + const name = tokens[pos++].value.toLowerCase(); + if (!customNames.has(name)) { + rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`; + } else { + functions.push({ name, args: consumeFunctionArguments() }); + names.add(name); + } + skipWhitespace(); + if (!isCloseParen()) + throw unexpected(); + pos++; + } else { + throw unexpected(); + } + } else if (tokens[pos] instanceof OpenSquareToken) { + rawCSSString += "["; + pos++; + while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF()) + rawCSSString += tokens[pos++].toSource(); + if (!(tokens[pos] instanceof CloseSquareToken)) + throw unexpected(); + rawCSSString += "]"; + pos++; + } else { + throw unexpected(); + } + } + if (!rawCSSString && !functions.length) + throw unexpected(); + return { css: rawCSSString || void 0, functions }; + } + function consumeBuiltinFunctionArguments() { + let s = ""; + let balance = 1; + while (!isEOF()) { + if (isOpenParen() || isFunction()) + balance++; + if (isCloseParen()) + balance--; + if (!balance) + break; + s += tokens[pos++].toSource(); + } + return s; + } + const result = consumeFunctionArguments(); + if (!isEOF()) + throw unexpected(); + if (result.some((arg) => typeof arg !== "object" || !("simples" in arg))) + throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + return { selector: result, names: Array.from(names) }; +} +const kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]); +const kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]); +const customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]); +function parseSelector(selector) { + const parsedStrings = parseSelectorString(selector); + const parts = []; + for (const part of parsedStrings.parts) { + if (part.name === "css" || part.name === "css:light") { + if (part.name === "css:light") + part.body = ":light(" + part.body + ")"; + const parsedCSS = parseCSS(part.body, customCSSNames); + parts.push({ + name: "css", + body: parsedCSS.selector, + source: part.body + }); + continue; + } + if (kNestedSelectorNames.has(part.name)) { + let innerSelector; + let distance; + try { + const unescaped = JSON.parse("[" + part.body + "]"); + if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string") + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + innerSelector = unescaped[0]; + if (unescaped.length === 2) { + if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name)) + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + distance = unescaped[1]; + } + } catch (e) { + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + } + const nested = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } }; + const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame"); + const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1; + if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), parts.slice(0, lastFrameIndex + 1))) + nested.body.parsed.parts.splice(0, lastFrameIndex + 1); + parts.push(nested); + continue; + } + parts.push({ ...part, source: part.body }); + } + if (kNestedSelectorNames.has(parts[0].name)) + throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`); + return { + capture: parsedStrings.capture, + parts + }; +} +function splitSelectorByFrame(selectorText) { + const selector = parseSelector(selectorText); + const result = []; + let chunk = { + parts: [] + }; + let chunkStartIndex = 0; + for (let i = 0; i < selector.parts.length; ++i) { + const part = selector.parts[i]; + if (part.name === "internal:control" && part.body === "enter-frame") { + if (!chunk.parts.length) + throw new InvalidSelectorError("Selector cannot start with entering frame, select the iframe first"); + result.push(chunk); + chunk = { parts: [] }; + chunkStartIndex = i + 1; + continue; + } + if (selector.capture === i) + chunk.capture = i - chunkStartIndex; + chunk.parts.push(part); + } + if (!chunk.parts.length) + throw new InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${selectorText}`); + result.push(chunk); + if (typeof selector.capture === "number" && typeof result[result.length - 1].capture !== "number") + throw new InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`); + return result; +} +function selectorPartsEqual(list1, list2) { + return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 }); +} +function stringifySelector(selector, forceEngineName) { + if (typeof selector === "string") + return selector; + return selector.parts.map((p, i) => { + let includeEngine = true; + if (!forceEngineName && i !== selector.capture) { + if (p.name === "css") + includeEngine = false; + else if (p.name === "xpath" && p.source.startsWith("//") || p.source.startsWith("..")) + includeEngine = false; + } + const prefix = includeEngine ? p.name + "=" : ""; + return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`; + }).join(" >> "); +} +function visitAllSelectorParts(selector, visitor) { + const visit2 = (selector2, nested) => { + for (const part of selector2.parts) { + visitor(part, nested); + if (kNestedSelectorNames.has(part.name)) + visit2(part.body.parsed, true); + } + }; + visit2(selector, false); +} +function parseSelectorString(selector) { + let index2 = 0; + let quote2; + let start = 0; + const result = { parts: [] }; + const append = () => { + const part = selector.substring(start, index2).trim(); + const eqIndex = part.indexOf("="); + let name; + let body; + if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) { + name = part.substring(0, eqIndex).trim(); + body = part.substring(eqIndex + 1); + } else if (part.length > 1 && part[0] === '"' && part[part.length - 1] === '"') { + name = "text"; + body = part; + } else if (part.length > 1 && part[0] === "'" && part[part.length - 1] === "'") { + name = "text"; + body = part; + } else if (/^\(*\/\//.test(part) || part.startsWith("..")) { + name = "xpath"; + body = part; + } else { + name = "css"; + body = part; + } + let capture = false; + if (name[0] === "*") { + capture = true; + name = name.substring(1); + } + result.parts.push({ name, body }); + if (capture) { + if (result.capture !== void 0) + throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`); + result.capture = result.parts.length - 1; + } + }; + if (!selector.includes(">>")) { + index2 = selector.length; + append(); + return result; + } + const shouldIgnoreTextSelectorQuote = () => { + const prefix = selector.substring(start, index2); + const match = prefix.match(/^\s*text\s*=(.*)$/); + return !!match && !!match[1]; + }; + while (index2 < selector.length) { + const c = selector[index2]; + if (c === "\\" && index2 + 1 < selector.length) { + index2 += 2; + } else if (c === quote2) { + quote2 = void 0; + index2++; + } else if (!quote2 && (c === '"' || c === "'" || c === "`") && !shouldIgnoreTextSelectorQuote()) { + quote2 = c; + index2++; + } else if (!quote2 && c === ">" && selector[index2 + 1] === ">") { + append(); + index2 += 2; + start = index2; + } else { + index2++; + } + } + append(); + return result; +} +function parseAttributeSelector(selector, allowUnquotedStrings) { + let wp = 0; + let EOL = selector.length === 0; + const next = () => selector[wp] || ""; + const eat1 = () => { + const result2 = next(); + ++wp; + EOL = wp >= selector.length; + return result2; + }; + const syntaxError = (stage) => { + if (EOL) + throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \`${selector}\``); + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : "")); + }; + function skipSpaces() { + while (!EOL && /\s/.test(next())) + eat1(); + } + function isCSSNameChar(char) { + return char >= "€" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-"; + } + function readIdentifier() { + let result2 = ""; + skipSpaces(); + while (!EOL && isCSSNameChar(next())) + result2 += eat1(); + return result2; + } + function readQuotedString(quote2) { + let result2 = eat1(); + if (result2 !== quote2) + syntaxError("parsing quoted string"); + while (!EOL && next() !== quote2) { + if (next() === "\\") + eat1(); + result2 += eat1(); + } + if (next() !== quote2) + syntaxError("parsing quoted string"); + result2 += eat1(); + return result2; + } + function readRegularExpression() { + if (eat1() !== "/") + syntaxError("parsing regular expression"); + let source2 = ""; + let inClass = false; + while (!EOL) { + if (next() === "\\") { + source2 += eat1(); + if (EOL) + syntaxError("parsing regular expression"); + } else if (inClass && next() === "]") { + inClass = false; + } else if (!inClass && next() === "[") { + inClass = true; + } else if (!inClass && next() === "/") { + break; + } + source2 += eat1(); + } + if (eat1() !== "/") + syntaxError("parsing regular expression"); + let flags = ""; + while (!EOL && next().match(/[dgimsuy]/)) + flags += eat1(); + try { + return new RegExp(source2, flags); + } catch (e) { + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\`: ${e.message}`); + } + } + function readAttributeToken() { + let token = ""; + skipSpaces(); + if (next() === `'` || next() === `"`) + token = readQuotedString(next()).slice(1, -1); + else + token = readIdentifier(); + if (!token) + syntaxError("parsing property path"); + return token; + } + function readOperator() { + skipSpaces(); + let op = ""; + if (!EOL) + op += eat1(); + if (!EOL && op !== "=") + op += eat1(); + if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op)) + syntaxError("parsing operator"); + return op; + } + function readAttribute() { + eat1(); + const jsonPath = []; + jsonPath.push(readAttributeToken()); + skipSpaces(); + while (next() === ".") { + eat1(); + jsonPath.push(readAttributeToken()); + skipSpaces(); + } + if (next() === "]") { + eat1(); + return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false }; + } + const operator = readOperator(); + let value = void 0; + let caseSensitive = true; + skipSpaces(); + if (next() === "/") { + if (operator !== "=") + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with regular expression`); + value = readRegularExpression(); + } else if (next() === `'` || next() === `"`) { + value = readQuotedString(next()).slice(1, -1); + skipSpaces(); + if (next() === "i" || next() === "I") { + caseSensitive = false; + eat1(); + } else if (next() === "s" || next() === "S") { + caseSensitive = true; + eat1(); + } + } else { + value = ""; + while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === ".")) + value += eat1(); + if (value === "true") { + value = true; + } else if (value === "false") { + value = false; + } else ; + } + skipSpaces(); + if (next() !== "]") + syntaxError("parsing attribute value"); + eat1(); + if (operator !== "=" && typeof value !== "string") + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value}`); + return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive }; + } + const result = { + name: "", + attributes: [] + }; + result.name = readIdentifier(); + skipSpaces(); + while (next() === "[") { + result.attributes.push(readAttribute()); + skipSpaces(); + } + if (!EOL) + syntaxError(void 0); + if (!result.name && !result.attributes.length) + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - selector cannot be empty`); + return result; +} +function escapeWithQuotes(text, char = "'") { + const stringified = JSON.stringify(text); + const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"'); + if (char === "'") + return char + escapedText.replace(/[']/g, "\\'") + char; + if (char === '"') + return char + escapedText.replace(/["]/g, '\\"') + char; + if (char === "`") + return char + escapedText.replace(/[`]/g, "`") + char; + throw new Error("Invalid escape char"); +} +function isString(obj) { + return typeof obj === "string" || obj instanceof String; +} +function toTitleCase(name) { + return name.charAt(0).toUpperCase() + name.substring(1); +} +function toSnakeCase(name) { + return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase(); +} +function quoteCSSAttributeValue(text) { + return `"${text.replace(/["\\]/g, (char) => "\\" + char)}"`; +} +function normalizeEscapedRegexQuotes(source2) { + return source2.replace(/(^|[^\\])(\\\\)*\\(['"`])/g, "$1$2$3"); +} +function escapeRegexForSelector(re2) { + if (re2.unicode || re2.unicodeSets) + return String(re2); + return String(re2).replace(/(^|[^\\])(\\\\)*(["'`])/g, "$1$2\\$3").replace(/>>/g, "\\>\\>"); +} +function escapeForTextSelector(text, exact) { + if (typeof text !== "string") + return escapeRegexForSelector(text); + return `${JSON.stringify(text)}${exact ? "s" : "i"}`; +} +function escapeForAttributeSelector(value, exact) { + if (typeof value !== "string") + return escapeRegexForSelector(value); + return `"${value.replace(/\\/g, "\\\\").replace(/["]/g, '\\"')}"${exact ? "s" : "i"}`; +} +function trimString(input, cap, suffix = "") { + if (input.length <= cap) + return input; + const chars = [...input]; + if (chars.length > cap) + return chars.slice(0, cap - suffix.length).join("") + suffix; + return chars.join(""); +} +function trimStringWithEllipsis(input, cap) { + return trimString(input, cap, "…"); +} +const escaped = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }; +function escapeHTML(s) { + return s.replace(/[&<]/ug, (char) => escaped[char]); +} +function asLocator(lang, selector, isFrameLocator = false) { + return asLocators(lang, selector, isFrameLocator, 1)[0]; +} +function asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) { + try { + return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize); + } catch (e) { + return [selector]; + } +} +function innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) { + const parts = [...parsed.parts]; + const tokens = []; + let nextBase = isFrameLocator ? "frame-locator" : "page"; + for (let index2 = 0; index2 < parts.length; index2++) { + const part = parts[index2]; + const base2 = nextBase; + nextBase = "locator"; + if (part.name === "internal:describe") + continue; + if (part.name === "nth") { + if (part.body === "0") + tokens.push([factory.generateLocator(base2, "first", ""), factory.generateLocator(base2, "nth", "0")]); + else if (part.body === "-1") + tokens.push([factory.generateLocator(base2, "last", ""), factory.generateLocator(base2, "nth", "-1")]); + else + tokens.push([factory.generateLocator(base2, "nth", part.body)]); + continue; + } + if (part.name === "visible") { + tokens.push([factory.generateLocator(base2, "visible", part.body), factory.generateLocator(base2, "default", `visible=${part.body}`)]); + continue; + } + if (part.name === "internal:text") { + const { exact, text } = detectExact(part.body); + tokens.push([factory.generateLocator(base2, "text", text, { exact })]); + continue; + } + if (part.name === "internal:has-text") { + const { exact, text } = detectExact(part.body); + if (!exact) { + tokens.push([factory.generateLocator(base2, "has-text", text, { exact })]); + continue; + } + } + if (part.name === "internal:has-not-text") { + const { exact, text } = detectExact(part.body); + if (!exact) { + tokens.push([factory.generateLocator(base2, "has-not-text", text, { exact })]); + continue; + } + } + if (part.name === "internal:has") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base2, "has", inner))); + continue; + } + if (part.name === "internal:has-not") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base2, "hasNot", inner))); + continue; + } + if (part.name === "internal:and") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base2, "and", inner))); + continue; + } + if (part.name === "internal:or") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base2, "or", inner))); + continue; + } + if (part.name === "internal:chain") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base2, "chain", inner))); + continue; + } + if (part.name === "internal:label") { + const { exact, text } = detectExact(part.body); + tokens.push([factory.generateLocator(base2, "label", text, { exact })]); + continue; + } + if (part.name === "internal:role") { + const attrSelector = parseAttributeSelector(part.body); + const options2 = { attrs: [] }; + for (const attr of attrSelector.attributes) { + if (attr.name === "name") { + options2.exact = attr.caseSensitive; + options2.name = attr.value; + } else { + if (attr.name === "level" && typeof attr.value === "string") + attr.value = +attr.value; + options2.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value }); + } + } + tokens.push([factory.generateLocator(base2, "role", attrSelector.name, options2)]); + continue; + } + if (part.name === "internal:testid") { + const attrSelector = parseAttributeSelector(part.body); + const { value } = attrSelector.attributes[0]; + tokens.push([factory.generateLocator(base2, "test-id", value)]); + continue; + } + if (part.name === "internal:attr") { + const attrSelector = parseAttributeSelector(part.body); + const { name, value, caseSensitive } = attrSelector.attributes[0]; + const text = value; + const exact = !!caseSensitive; + if (name === "placeholder") { + tokens.push([factory.generateLocator(base2, "placeholder", text, { exact })]); + continue; + } + if (name === "alt") { + tokens.push([factory.generateLocator(base2, "alt", text, { exact })]); + continue; + } + if (name === "title") { + tokens.push([factory.generateLocator(base2, "title", text, { exact })]); + continue; + } + } + if (part.name === "internal:control" && part.body === "enter-frame") { + const lastTokens = tokens[tokens.length - 1]; + const lastPart = parts[index2 - 1]; + const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base2, "frame", "")])); + if (["xpath", "css"].includes(lastPart.name)) { + transformed.push( + factory.generateLocator(base2, "frame-locator", stringifySelector({ parts: [lastPart] })), + factory.generateLocator(base2, "frame-locator", stringifySelector({ parts: [lastPart] }, true)) + ); + } + lastTokens.splice(0, lastTokens.length, ...transformed); + nextBase = "frame-locator"; + continue; + } + const nextPart = parts[index2 + 1]; + const selectorPart = stringifySelector({ parts: [part] }); + const locatorPart = factory.generateLocator(base2, "default", selectorPart); + if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) { + const { exact, text } = detectExact(nextPart.body); + if (!exact) { + const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text, { exact }); + const options2 = {}; + if (nextPart.name === "internal:has-text") + options2.hasText = text; + else + options2.hasNotText = text; + const combinedPart = factory.generateLocator(base2, "default", selectorPart, options2); + tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]); + index2++; + continue; + } + } + let locatorPartWithEngine; + if (["xpath", "css"].includes(part.name)) { + const selectorPart2 = stringifySelector( + { parts: [part] }, + /* forceEngineName */ + true + ); + locatorPartWithEngine = factory.generateLocator(base2, "default", selectorPart2); + } + tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean)); + } + return combineTokens(factory, tokens, maxOutputSize); +} +function combineTokens(factory, tokens, maxOutputSize) { + const currentTokens = tokens.map(() => ""); + const result = []; + const visit2 = (index2) => { + if (index2 === tokens.length) { + result.push(factory.chainLocators(currentTokens)); + return result.length < maxOutputSize; + } + for (const taken of tokens[index2]) { + currentTokens[index2] = taken; + if (!visit2(index2 + 1)) + return false; + } + return true; + }; + visit2(0); + return result; +} +function detectExact(text) { + let exact = false; + const match = text.match(/^\/(.*)\/([igm]*)$/); + if (match) + return { text: new RegExp(match[1], match[2]) }; + if (text.endsWith('"')) { + text = JSON.parse(text); + exact = true; + } else if (text.endsWith('"s')) { + text = JSON.parse(text.substring(0, text.length - 1)); + exact = true; + } else if (text.endsWith('"i')) { + text = JSON.parse(text.substring(0, text.length - 1)); + exact = false; + } + return { exact, text }; +} +class JavaScriptLocatorFactory { + constructor(preferredQuote) { + this.preferredQuote = preferredQuote; + } + generateLocator(base2, kind, body, options2 = {}) { + switch (kind) { + case "default": + if (options2.hasText !== void 0) + return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options2.hasText)} })`; + if (options2.hasNotText !== void 0) + return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options2.hasNotText)} })`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frameLocator(${this.quote(body)})`; + case "frame": + return `contentFrame()`; + case "nth": + return `nth(${body})`; + case "first": + return `first()`; + case "last": + return `last()`; + case "visible": + return `filter({ visible: ${body === "true" ? "true" : "false"} })`; + case "role": + const attrs = []; + if (isRegExp$5(options2.name)) { + attrs.push(`name: ${this.regexToSourceString(options2.name)}`); + } else if (typeof options2.name === "string") { + attrs.push(`name: ${this.quote(options2.name)}`); + if (options2.exact) + attrs.push(`exact: true`); + } + for (const { name, value } of options2.attrs) + attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`); + const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : ""; + return `getByRole(${this.quote(body)}${attrString})`; + case "has-text": + return `filter({ hasText: ${this.toHasText(body)} })`; + case "has-not-text": + return `filter({ hasNotText: ${this.toHasText(body)} })`; + case "has": + return `filter({ has: ${body} })`; + case "hasNot": + return `filter({ hasNot: ${body} })`; + case "and": + return `and(${body})`; + case "or": + return `or(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `getByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("getByText", body, !!options2.exact); + case "alt": + return this.toCallWithExact("getByAltText", body, !!options2.exact); + case "placeholder": + return this.toCallWithExact("getByPlaceholder", body, !!options2.exact); + case "label": + return this.toCallWithExact("getByLabel", body, !!options2.exact); + case "title": + return this.toCallWithExact("getByTitle", body, !!options2.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToSourceString(re2) { + return normalizeEscapedRegexQuotes(String(re2)); + } + toCallWithExact(method, body, exact) { + if (isRegExp$5(body)) + return `${method}(${this.regexToSourceString(body)})`; + return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp$5(body)) + return this.regexToSourceString(body); + return this.quote(body); + } + toTestIdValue(value) { + if (isRegExp$5(value)) + return this.regexToSourceString(value); + return this.quote(value); + } + quote(text) { + return escapeWithQuotes(text, this.preferredQuote ?? "'"); + } +} +class PythonLocatorFactory { + generateLocator(base2, kind, body, options2 = {}) { + switch (kind) { + case "default": + if (options2.hasText !== void 0) + return `locator(${this.quote(body)}, has_text=${this.toHasText(options2.hasText)})`; + if (options2.hasNotText !== void 0) + return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options2.hasNotText)})`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frame_locator(${this.quote(body)})`; + case "frame": + return `content_frame`; + case "nth": + return `nth(${body})`; + case "first": + return `first`; + case "last": + return `last`; + case "visible": + return `filter(visible=${body === "true" ? "True" : "False"})`; + case "role": + const attrs = []; + if (isRegExp$5(options2.name)) { + attrs.push(`name=${this.regexToString(options2.name)}`); + } else if (typeof options2.name === "string") { + attrs.push(`name=${this.quote(options2.name)}`); + if (options2.exact) + attrs.push(`exact=True`); + } + for (const { name, value } of options2.attrs) { + let valueString = typeof value === "string" ? this.quote(value) : value; + if (typeof value === "boolean") + valueString = value ? "True" : "False"; + attrs.push(`${toSnakeCase(name)}=${valueString}`); + } + const attrString = attrs.length ? `, ${attrs.join(", ")}` : ""; + return `get_by_role(${this.quote(body)}${attrString})`; + case "has-text": + return `filter(has_text=${this.toHasText(body)})`; + case "has-not-text": + return `filter(has_not_text=${this.toHasText(body)})`; + case "has": + return `filter(has=${body})`; + case "hasNot": + return `filter(has_not=${body})`; + case "and": + return `and_(${body})`; + case "or": + return `or_(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `get_by_test_id(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("get_by_text", body, !!options2.exact); + case "alt": + return this.toCallWithExact("get_by_alt_text", body, !!options2.exact); + case "placeholder": + return this.toCallWithExact("get_by_placeholder", body, !!options2.exact); + case "label": + return this.toCallWithExact("get_by_label", body, !!options2.exact); + case "title": + return this.toCallWithExact("get_by_title", body, !!options2.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = body.flags.includes("i") ? ", re.IGNORECASE" : ""; + return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\//, "/").replace(/"/g, '\\"')}"${suffix})`; + } + toCallWithExact(method, body, exact) { + if (isRegExp$5(body)) + return `${method}(${this.regexToString(body)})`; + if (exact) + return `${method}(${this.quote(body)}, exact=True)`; + return `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp$5(body)) + return this.regexToString(body); + return `${this.quote(body)}`; + } + toTestIdValue(value) { + if (isRegExp$5(value)) + return this.regexToString(value); + return this.quote(value); + } + quote(text) { + return escapeWithQuotes(text, '"'); + } +} +class JavaLocatorFactory { + generateLocator(base2, kind, body, options2 = {}) { + let clazz; + switch (base2) { + case "page": + clazz = "Page"; + break; + case "frame-locator": + clazz = "FrameLocator"; + break; + case "locator": + clazz = "Locator"; + break; + } + switch (kind) { + case "default": + if (options2.hasText !== void 0) + return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options2.hasText)}))`; + if (options2.hasNotText !== void 0) + return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options2.hasNotText)}))`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frameLocator(${this.quote(body)})`; + case "frame": + return `contentFrame()`; + case "nth": + return `nth(${body})`; + case "first": + return `first()`; + case "last": + return `last()`; + case "visible": + return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`; + case "role": + const attrs = []; + if (isRegExp$5(options2.name)) { + attrs.push(`.setName(${this.regexToString(options2.name)})`); + } else if (typeof options2.name === "string") { + attrs.push(`.setName(${this.quote(options2.name)})`); + if (options2.exact) + attrs.push(`.setExact(true)`); + } + for (const { name, value } of options2.attrs) + attrs.push(`.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`); + const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : ""; + return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`; + case "has-text": + return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`; + case "has-not-text": + return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`; + case "has": + return `filter(new ${clazz}.FilterOptions().setHas(${body}))`; + case "hasNot": + return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`; + case "and": + return `and(${body})`; + case "or": + return `or(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `getByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact(clazz, "getByText", body, !!options2.exact); + case "alt": + return this.toCallWithExact(clazz, "getByAltText", body, !!options2.exact); + case "placeholder": + return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options2.exact); + case "label": + return this.toCallWithExact(clazz, "getByLabel", body, !!options2.exact); + case "title": + return this.toCallWithExact(clazz, "getByTitle", body, !!options2.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = body.flags.includes("i") ? ", Pattern.CASE_INSENSITIVE" : ""; + return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`; + } + toCallWithExact(clazz, method, body, exact) { + if (isRegExp$5(body)) + return `${method}(${this.regexToString(body)})`; + if (exact) + return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`; + return `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp$5(body)) + return this.regexToString(body); + return this.quote(body); + } + toTestIdValue(value) { + if (isRegExp$5(value)) + return this.regexToString(value); + return this.quote(value); + } + quote(text) { + return escapeWithQuotes(text, '"'); + } +} +class CSharpLocatorFactory { + generateLocator(base2, kind, body, options2 = {}) { + switch (kind) { + case "default": + if (options2.hasText !== void 0) + return `Locator(${this.quote(body)}, new() { ${this.toHasText(options2.hasText)} })`; + if (options2.hasNotText !== void 0) + return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options2.hasNotText)} })`; + return `Locator(${this.quote(body)})`; + case "frame-locator": + return `FrameLocator(${this.quote(body)})`; + case "frame": + return `ContentFrame`; + case "nth": + return `Nth(${body})`; + case "first": + return `First`; + case "last": + return `Last`; + case "visible": + return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`; + case "role": + const attrs = []; + if (isRegExp$5(options2.name)) { + attrs.push(`NameRegex = ${this.regexToString(options2.name)}`); + } else if (typeof options2.name === "string") { + attrs.push(`Name = ${this.quote(options2.name)}`); + if (options2.exact) + attrs.push(`Exact = true`); + } + for (const { name, value } of options2.attrs) + attrs.push(`${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`); + const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : ""; + return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`; + case "has-text": + return `Filter(new() { ${this.toHasText(body)} })`; + case "has-not-text": + return `Filter(new() { ${this.toHasNotText(body)} })`; + case "has": + return `Filter(new() { Has = ${body} })`; + case "hasNot": + return `Filter(new() { HasNot = ${body} })`; + case "and": + return `And(${body})`; + case "or": + return `Or(${body})`; + case "chain": + return `Locator(${body})`; + case "test-id": + return `GetByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("GetByText", body, !!options2.exact); + case "alt": + return this.toCallWithExact("GetByAltText", body, !!options2.exact); + case "placeholder": + return this.toCallWithExact("GetByPlaceholder", body, !!options2.exact); + case "label": + return this.toCallWithExact("GetByLabel", body, !!options2.exact); + case "title": + return this.toCallWithExact("GetByTitle", body, !!options2.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = body.flags.includes("i") ? ", RegexOptions.IgnoreCase" : ""; + return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`; + } + toCallWithExact(method, body, exact) { + if (isRegExp$5(body)) + return `${method}(${this.regexToString(body)})`; + if (exact) + return `${method}(${this.quote(body)}, new() { Exact = true })`; + return `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp$5(body)) + return `HasTextRegex = ${this.regexToString(body)}`; + return `HasText = ${this.quote(body)}`; + } + toTestIdValue(value) { + if (isRegExp$5(value)) + return this.regexToString(value); + return this.quote(value); + } + toHasNotText(body) { + if (isRegExp$5(body)) + return `HasNotTextRegex = ${this.regexToString(body)}`; + return `HasNotText = ${this.quote(body)}`; + } + quote(text) { + return escapeWithQuotes(text, '"'); + } +} +class JsonlLocatorFactory { + generateLocator(base2, kind, body, options2 = {}) { + return JSON.stringify({ + kind, + body, + options: options2 + }); + } + chainLocators(locators) { + const objects = locators.map((l) => JSON.parse(l)); + for (let i = 0; i < objects.length - 1; ++i) + objects[i].next = objects[i + 1]; + return JSON.stringify(objects[0]); + } +} +const generators = { + javascript: JavaScriptLocatorFactory, + python: PythonLocatorFactory, + java: JavaLocatorFactory, + csharp: CSharpLocatorFactory, + jsonl: JsonlLocatorFactory +}; +function isRegExp$5(obj) { + return obj instanceof RegExp; +} +function isTextualMimeType(mimeType) { + return !!mimeType.match(/^(text\/.*?|application\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\/svg(\+xml)?|application\/.*?(\+json|\+xml))(;\s*charset=.*)?$/); +} +function getMimeTypeForPath(path2) { + const dotIndex = path2.lastIndexOf("."); + if (dotIndex === -1) + return null; + const extension = path2.substring(dotIndex + 1); + return types$2.get(extension) || null; +} +const types$2 = /* @__PURE__ */ new Map([ + ["ez", "application/andrew-inset"], + ["aw", "application/applixware"], + ["atom", "application/atom+xml"], + ["atomcat", "application/atomcat+xml"], + ["atomdeleted", "application/atomdeleted+xml"], + ["atomsvc", "application/atomsvc+xml"], + ["dwd", "application/atsc-dwd+xml"], + ["held", "application/atsc-held+xml"], + ["rsat", "application/atsc-rsat+xml"], + ["bdoc", "application/bdoc"], + ["xcs", "application/calendar+xml"], + ["ccxml", "application/ccxml+xml"], + ["cdfx", "application/cdfx+xml"], + ["cdmia", "application/cdmi-capability"], + ["cdmic", "application/cdmi-container"], + ["cdmid", "application/cdmi-domain"], + ["cdmio", "application/cdmi-object"], + ["cdmiq", "application/cdmi-queue"], + ["cu", "application/cu-seeme"], + ["mpd", "application/dash+xml"], + ["davmount", "application/davmount+xml"], + ["dbk", "application/docbook+xml"], + ["dssc", "application/dssc+der"], + ["xdssc", "application/dssc+xml"], + ["ecma", "application/ecmascript"], + ["es", "application/ecmascript"], + ["emma", "application/emma+xml"], + ["emotionml", "application/emotionml+xml"], + ["epub", "application/epub+zip"], + ["exi", "application/exi"], + ["exp", "application/express"], + ["fdt", "application/fdt+xml"], + ["pfr", "application/font-tdpfr"], + ["geojson", "application/geo+json"], + ["gml", "application/gml+xml"], + ["gpx", "application/gpx+xml"], + ["gxf", "application/gxf"], + ["gz", "application/gzip"], + ["hjson", "application/hjson"], + ["stk", "application/hyperstudio"], + ["ink", "application/inkml+xml"], + ["inkml", "application/inkml+xml"], + ["ipfix", "application/ipfix"], + ["its", "application/its+xml"], + ["ear", "application/java-archive"], + ["jar", "application/java-archive"], + ["war", "application/java-archive"], + ["ser", "application/java-serialized-object"], + ["class", "application/java-vm"], + ["js", "application/javascript"], + ["mjs", "application/javascript"], + ["json", "application/json"], + ["map", "application/json"], + ["json5", "application/json5"], + ["jsonml", "application/jsonml+json"], + ["jsonld", "application/ld+json"], + ["lgr", "application/lgr+xml"], + ["lostxml", "application/lost+xml"], + ["hqx", "application/mac-binhex40"], + ["cpt", "application/mac-compactpro"], + ["mads", "application/mads+xml"], + ["webmanifest", "application/manifest+json"], + ["mrc", "application/marc"], + ["mrcx", "application/marcxml+xml"], + ["ma", "application/mathematica"], + ["mb", "application/mathematica"], + ["nb", "application/mathematica"], + ["mathml", "application/mathml+xml"], + ["mbox", "application/mbox"], + ["mscml", "application/mediaservercontrol+xml"], + ["metalink", "application/metalink+xml"], + ["meta4", "application/metalink4+xml"], + ["mets", "application/mets+xml"], + ["maei", "application/mmt-aei+xml"], + ["musd", "application/mmt-usd+xml"], + ["mods", "application/mods+xml"], + ["m21", "application/mp21"], + ["mp21", "application/mp21"], + ["m4p", "application/mp4"], + ["mp4s", "application/mp4"], + ["doc", "application/msword"], + ["dot", "application/msword"], + ["mxf", "application/mxf"], + ["nq", "application/n-quads"], + ["nt", "application/n-triples"], + ["cjs", "application/node"], + ["bin", "application/octet-stream"], + ["bpk", "application/octet-stream"], + ["buffer", "application/octet-stream"], + ["deb", "application/octet-stream"], + ["deploy", "application/octet-stream"], + ["dist", "application/octet-stream"], + ["distz", "application/octet-stream"], + ["dll", "application/octet-stream"], + ["dmg", "application/octet-stream"], + ["dms", "application/octet-stream"], + ["dump", "application/octet-stream"], + ["elc", "application/octet-stream"], + ["exe", "application/octet-stream"], + ["img", "application/octet-stream"], + ["iso", "application/octet-stream"], + ["lrf", "application/octet-stream"], + ["mar", "application/octet-stream"], + ["msi", "application/octet-stream"], + ["msm", "application/octet-stream"], + ["msp", "application/octet-stream"], + ["pkg", "application/octet-stream"], + ["so", "application/octet-stream"], + ["oda", "application/oda"], + ["opf", "application/oebps-package+xml"], + ["ogx", "application/ogg"], + ["omdoc", "application/omdoc+xml"], + ["onepkg", "application/onenote"], + ["onetmp", "application/onenote"], + ["onetoc", "application/onenote"], + ["onetoc2", "application/onenote"], + ["oxps", "application/oxps"], + ["relo", "application/p2p-overlay+xml"], + ["xer", "application/patch-ops-error+xml"], + ["pdf", "application/pdf"], + ["pgp", "application/pgp-encrypted"], + ["asc", "application/pgp-signature"], + ["sig", "application/pgp-signature"], + ["prf", "application/pics-rules"], + ["p10", "application/pkcs10"], + ["p7c", "application/pkcs7-mime"], + ["p7m", "application/pkcs7-mime"], + ["p7s", "application/pkcs7-signature"], + ["p8", "application/pkcs8"], + ["ac", "application/pkix-attr-cert"], + ["cer", "application/pkix-cert"], + ["crl", "application/pkix-crl"], + ["pkipath", "application/pkix-pkipath"], + ["pki", "application/pkixcmp"], + ["pls", "application/pls+xml"], + ["ai", "application/postscript"], + ["eps", "application/postscript"], + ["ps", "application/postscript"], + ["provx", "application/provenance+xml"], + ["pskcxml", "application/pskc+xml"], + ["raml", "application/raml+yaml"], + ["owl", "application/rdf+xml"], + ["rdf", "application/rdf+xml"], + ["rif", "application/reginfo+xml"], + ["rnc", "application/relax-ng-compact-syntax"], + ["rl", "application/resource-lists+xml"], + ["rld", "application/resource-lists-diff+xml"], + ["rs", "application/rls-services+xml"], + ["rapd", "application/route-apd+xml"], + ["sls", "application/route-s-tsid+xml"], + ["rusd", "application/route-usd+xml"], + ["gbr", "application/rpki-ghostbusters"], + ["mft", "application/rpki-manifest"], + ["roa", "application/rpki-roa"], + ["rsd", "application/rsd+xml"], + ["rss", "application/rss+xml"], + ["rtf", "application/rtf"], + ["sbml", "application/sbml+xml"], + ["scq", "application/scvp-cv-request"], + ["scs", "application/scvp-cv-response"], + ["spq", "application/scvp-vp-request"], + ["spp", "application/scvp-vp-response"], + ["sdp", "application/sdp"], + ["senmlx", "application/senml+xml"], + ["sensmlx", "application/sensml+xml"], + ["setpay", "application/set-payment-initiation"], + ["setreg", "application/set-registration-initiation"], + ["shf", "application/shf+xml"], + ["sieve", "application/sieve"], + ["siv", "application/sieve"], + ["smi", "application/smil+xml"], + ["smil", "application/smil+xml"], + ["rq", "application/sparql-query"], + ["srx", "application/sparql-results+xml"], + ["gram", "application/srgs"], + ["grxml", "application/srgs+xml"], + ["sru", "application/sru+xml"], + ["ssdl", "application/ssdl+xml"], + ["ssml", "application/ssml+xml"], + ["swidtag", "application/swid+xml"], + ["tei", "application/tei+xml"], + ["teicorpus", "application/tei+xml"], + ["tfi", "application/thraud+xml"], + ["tsd", "application/timestamped-data"], + ["toml", "application/toml"], + ["trig", "application/trig"], + ["ttml", "application/ttml+xml"], + ["ubj", "application/ubjson"], + ["rsheet", "application/urc-ressheet+xml"], + ["td", "application/urc-targetdesc+xml"], + ["vxml", "application/voicexml+xml"], + ["wasm", "application/wasm"], + ["wgt", "application/widget"], + ["hlp", "application/winhlp"], + ["wsdl", "application/wsdl+xml"], + ["wspolicy", "application/wspolicy+xml"], + ["xaml", "application/xaml+xml"], + ["xav", "application/xcap-att+xml"], + ["xca", "application/xcap-caps+xml"], + ["xdf", "application/xcap-diff+xml"], + ["xel", "application/xcap-el+xml"], + ["xns", "application/xcap-ns+xml"], + ["xenc", "application/xenc+xml"], + ["xht", "application/xhtml+xml"], + ["xhtml", "application/xhtml+xml"], + ["xlf", "application/xliff+xml"], + ["rng", "application/xml"], + ["xml", "application/xml"], + ["xsd", "application/xml"], + ["xsl", "application/xml"], + ["dtd", "application/xml-dtd"], + ["xop", "application/xop+xml"], + ["xpl", "application/xproc+xml"], + ["*xsl", "application/xslt+xml"], + ["xslt", "application/xslt+xml"], + ["xspf", "application/xspf+xml"], + ["mxml", "application/xv+xml"], + ["xhvml", "application/xv+xml"], + ["xvm", "application/xv+xml"], + ["xvml", "application/xv+xml"], + ["yang", "application/yang"], + ["yin", "application/yin+xml"], + ["zip", "application/zip"], + ["*3gpp", "audio/3gpp"], + ["adp", "audio/adpcm"], + ["amr", "audio/amr"], + ["au", "audio/basic"], + ["snd", "audio/basic"], + ["kar", "audio/midi"], + ["mid", "audio/midi"], + ["midi", "audio/midi"], + ["rmi", "audio/midi"], + ["mxmf", "audio/mobile-xmf"], + ["*mp3", "audio/mp3"], + ["m4a", "audio/mp4"], + ["mp4a", "audio/mp4"], + ["m2a", "audio/mpeg"], + ["m3a", "audio/mpeg"], + ["mp2", "audio/mpeg"], + ["mp2a", "audio/mpeg"], + ["mp3", "audio/mpeg"], + ["mpga", "audio/mpeg"], + ["oga", "audio/ogg"], + ["ogg", "audio/ogg"], + ["opus", "audio/ogg"], + ["spx", "audio/ogg"], + ["s3m", "audio/s3m"], + ["sil", "audio/silk"], + ["wav", "audio/wav"], + ["*wav", "audio/wave"], + ["weba", "audio/webm"], + ["xm", "audio/xm"], + ["ttc", "font/collection"], + ["otf", "font/otf"], + ["ttf", "font/ttf"], + ["woff", "font/woff"], + ["woff2", "font/woff2"], + ["exr", "image/aces"], + ["apng", "image/apng"], + ["avif", "image/avif"], + ["bmp", "image/bmp"], + ["cgm", "image/cgm"], + ["drle", "image/dicom-rle"], + ["emf", "image/emf"], + ["fits", "image/fits"], + ["g3", "image/g3fax"], + ["gif", "image/gif"], + ["heic", "image/heic"], + ["heics", "image/heic-sequence"], + ["heif", "image/heif"], + ["heifs", "image/heif-sequence"], + ["hej2", "image/hej2k"], + ["hsj2", "image/hsj2"], + ["ief", "image/ief"], + ["jls", "image/jls"], + ["jp2", "image/jp2"], + ["jpg2", "image/jp2"], + ["jpe", "image/jpeg"], + ["jpeg", "image/jpeg"], + ["jpg", "image/jpeg"], + ["jph", "image/jph"], + ["jhc", "image/jphc"], + ["jpm", "image/jpm"], + ["jpf", "image/jpx"], + ["jpx", "image/jpx"], + ["jxr", "image/jxr"], + ["jxra", "image/jxra"], + ["jxrs", "image/jxrs"], + ["jxs", "image/jxs"], + ["jxsc", "image/jxsc"], + ["jxsi", "image/jxsi"], + ["jxss", "image/jxss"], + ["ktx", "image/ktx"], + ["ktx2", "image/ktx2"], + ["png", "image/png"], + ["sgi", "image/sgi"], + ["svg", "image/svg+xml"], + ["svgz", "image/svg+xml"], + ["t38", "image/t38"], + ["tif", "image/tiff"], + ["tiff", "image/tiff"], + ["tfx", "image/tiff-fx"], + ["webp", "image/webp"], + ["wmf", "image/wmf"], + ["disposition-notification", "message/disposition-notification"], + ["u8msg", "message/global"], + ["u8dsn", "message/global-delivery-status"], + ["u8mdn", "message/global-disposition-notification"], + ["u8hdr", "message/global-headers"], + ["eml", "message/rfc822"], + ["mime", "message/rfc822"], + ["3mf", "model/3mf"], + ["gltf", "model/gltf+json"], + ["glb", "model/gltf-binary"], + ["iges", "model/iges"], + ["igs", "model/iges"], + ["mesh", "model/mesh"], + ["msh", "model/mesh"], + ["silo", "model/mesh"], + ["mtl", "model/mtl"], + ["obj", "model/obj"], + ["stpx", "model/step+xml"], + ["stpz", "model/step+zip"], + ["stpxz", "model/step-xml+zip"], + ["stl", "model/stl"], + ["vrml", "model/vrml"], + ["wrl", "model/vrml"], + ["*x3db", "model/x3d+binary"], + ["x3dbz", "model/x3d+binary"], + ["x3db", "model/x3d+fastinfoset"], + ["*x3dv", "model/x3d+vrml"], + ["x3dvz", "model/x3d+vrml"], + ["x3d", "model/x3d+xml"], + ["x3dz", "model/x3d+xml"], + ["x3dv", "model/x3d-vrml"], + ["appcache", "text/cache-manifest"], + ["manifest", "text/cache-manifest"], + ["ics", "text/calendar"], + ["ifb", "text/calendar"], + ["coffee", "text/coffeescript"], + ["litcoffee", "text/coffeescript"], + ["css", "text/css"], + ["csv", "text/csv"], + ["htm", "text/html"], + ["html", "text/html"], + ["shtml", "text/html"], + ["jade", "text/jade"], + ["jsx", "text/jsx"], + ["less", "text/less"], + ["markdown", "text/markdown"], + ["md", "text/markdown"], + ["mml", "text/mathml"], + ["mdx", "text/mdx"], + ["n3", "text/n3"], + ["conf", "text/plain"], + ["def", "text/plain"], + ["in", "text/plain"], + ["ini", "text/plain"], + ["list", "text/plain"], + ["log", "text/plain"], + ["text", "text/plain"], + ["txt", "text/plain"], + ["rtx", "text/richtext"], + ["*rtf", "text/rtf"], + ["sgm", "text/sgml"], + ["sgml", "text/sgml"], + ["shex", "text/shex"], + ["slim", "text/slim"], + ["slm", "text/slim"], + ["spdx", "text/spdx"], + ["styl", "text/stylus"], + ["stylus", "text/stylus"], + ["tsv", "text/tab-separated-values"], + ["man", "text/troff"], + ["me", "text/troff"], + ["ms", "text/troff"], + ["roff", "text/troff"], + ["t", "text/troff"], + ["tr", "text/troff"], + ["ttl", "text/turtle"], + ["uri", "text/uri-list"], + ["uris", "text/uri-list"], + ["urls", "text/uri-list"], + ["vcard", "text/vcard"], + ["vtt", "text/vtt"], + ["*xml", "text/xml"], + ["yaml", "text/yaml"], + ["yml", "text/yaml"], + ["3gp", "video/3gpp"], + ["3gpp", "video/3gpp"], + ["3g2", "video/3gpp2"], + ["h261", "video/h261"], + ["h263", "video/h263"], + ["h264", "video/h264"], + ["m4s", "video/iso.segment"], + ["jpgv", "video/jpeg"], + ["jpm", "video/jpm"], + ["jpgm", "video/jpm"], + ["mj2", "video/mj2"], + ["mjp2", "video/mj2"], + ["ts", "video/mp2t"], + ["mp4", "video/mp4"], + ["mp4v", "video/mp4"], + ["mpg4", "video/mp4"], + ["m1v", "video/mpeg"], + ["m2v", "video/mpeg"], + ["mpe", "video/mpeg"], + ["mpeg", "video/mpeg"], + ["mpg", "video/mpeg"], + ["ogv", "video/ogg"], + ["mov", "video/quicktime"], + ["qt", "video/quicktime"], + ["webm", "video/webm"] +]); +class MultiMap { + constructor() { + this._map = /* @__PURE__ */ new Map(); + } + set(key2, value) { + let values = this._map.get(key2); + if (!values) { + values = []; + this._map.set(key2, values); + } + values.push(value); + } + get(key2) { + return this._map.get(key2) || []; + } + has(key2) { + return this._map.has(key2); + } + delete(key2, value) { + const values = this._map.get(key2); + if (!values) + return; + if (values.includes(value)) + this._map.set(key2, values.filter((v) => value !== v)); + } + deleteAll(key2) { + this._map.delete(key2); + } + hasValue(key2, value) { + const values = this._map.get(key2); + if (!values) + return false; + return values.includes(value); + } + get size() { + return this._map.size; + } + [Symbol.iterator]() { + return this._map[Symbol.iterator](); + } + keys() { + return this._map.keys(); + } + values() { + const result = []; + for (const key2 of this.keys()) + result.push(...this.get(key2)); + return result; + } + clear() { + this._map.clear(); + } +} +const methodMetainfo = /* @__PURE__ */ new Map([ + ["APIRequestContext.fetch", { title: 'Fetch "{url}"' }], + ["APIRequestContext.fetchResponseBody", { internal: true }], + ["APIRequestContext.fetchLog", { internal: true }], + ["APIRequestContext.storageState", { internal: true }], + ["APIRequestContext.disposeAPIResponse", { internal: true }], + ["APIRequestContext.dispose", { internal: true }], + ["LocalUtils.zip", { internal: true }], + ["LocalUtils.harOpen", { internal: true }], + ["LocalUtils.harLookup", { internal: true }], + ["LocalUtils.harClose", { internal: true }], + ["LocalUtils.harUnzip", { internal: true }], + ["LocalUtils.connect", { internal: true }], + ["LocalUtils.tracingStarted", { internal: true }], + ["LocalUtils.addStackToTracingNoReply", { internal: true }], + ["LocalUtils.traceDiscarded", { internal: true }], + ["LocalUtils.globToRegex", { internal: true }], + ["Root.initialize", { internal: true }], + ["Playwright.newRequest", { title: "Create request context" }], + ["DebugController.initialize", { internal: true }], + ["DebugController.setReportStateChanged", { internal: true }], + ["DebugController.resetForReuse", { internal: true }], + ["DebugController.navigate", { internal: true }], + ["DebugController.setRecorderMode", { internal: true }], + ["DebugController.highlight", { internal: true }], + ["DebugController.hideHighlight", { internal: true }], + ["DebugController.resume", { internal: true }], + ["DebugController.kill", { internal: true }], + ["DebugController.closeAllBrowsers", { internal: true }], + ["SocksSupport.socksConnected", { internal: true }], + ["SocksSupport.socksFailed", { internal: true }], + ["SocksSupport.socksData", { internal: true }], + ["SocksSupport.socksError", { internal: true }], + ["SocksSupport.socksEnd", { internal: true }], + ["BrowserType.launch", { title: "Launch browser" }], + ["BrowserType.launchPersistentContext", { title: "Launch persistent context" }], + ["BrowserType.connectOverCDP", { title: "Connect over CDP" }], + ["Browser.close", { title: "Close browser" }], + ["Browser.killForTests", { internal: true }], + ["Browser.defaultUserAgentForTest", { internal: true }], + ["Browser.newContext", { title: "Create context" }], + ["Browser.newContextForReuse", { internal: true }], + ["Browser.stopPendingOperations", { internal: true, title: "Stop pending operations" }], + ["Browser.newBrowserCDPSession", { internal: true, title: "Create CDP session" }], + ["Browser.startTracing", { internal: true }], + ["Browser.stopTracing", { internal: true }], + ["EventTarget.waitForEventInfo", { title: 'Wait for event "{info.event}"', snapshot: true }], + ["BrowserContext.waitForEventInfo", { title: 'Wait for event "{info.event}"', snapshot: true }], + ["Page.waitForEventInfo", { title: 'Wait for event "{info.event}"', snapshot: true }], + ["WebSocket.waitForEventInfo", { title: 'Wait for event "{info.event}"', snapshot: true }], + ["ElectronApplication.waitForEventInfo", { title: 'Wait for event "{info.event}"', snapshot: true }], + ["AndroidDevice.waitForEventInfo", { title: 'Wait for event "{info.event}"', snapshot: true }], + ["BrowserContext.addCookies", { title: "Add cookies" }], + ["BrowserContext.addInitScript", { title: "Add init script" }], + ["BrowserContext.clearCookies", { title: "Clear cookies" }], + ["BrowserContext.clearPermissions", { title: "Clear permissions" }], + ["BrowserContext.close", { title: "Close context" }], + ["BrowserContext.cookies", { title: "Get cookies" }], + ["BrowserContext.exposeBinding", { title: "Expose binding" }], + ["BrowserContext.grantPermissions", { title: "Grant permissions" }], + ["BrowserContext.newPage", { title: "Create page" }], + ["BrowserContext.registerSelectorEngine", { internal: true }], + ["BrowserContext.setTestIdAttributeName", { internal: true }], + ["BrowserContext.setExtraHTTPHeaders", { title: "Set extra HTTP headers" }], + ["BrowserContext.setGeolocation", { title: "Set geolocation" }], + ["BrowserContext.setHTTPCredentials", { title: "Set HTTP credentials" }], + ["BrowserContext.setNetworkInterceptionPatterns", { internal: true }], + ["BrowserContext.setWebSocketInterceptionPatterns", { internal: true }], + ["BrowserContext.setOffline", { title: "Set offline mode" }], + ["BrowserContext.storageState", { title: "Get storage state" }], + ["BrowserContext.pause", { title: "Pause" }], + ["BrowserContext.enableRecorder", { internal: true }], + ["BrowserContext.newCDPSession", { internal: true }], + ["BrowserContext.harStart", { internal: true }], + ["BrowserContext.harExport", { internal: true }], + ["BrowserContext.createTempFiles", { internal: true }], + ["BrowserContext.updateSubscription", { internal: true }], + ["BrowserContext.clockFastForward", { title: 'Fast forward clock "{ticksNumber}{ticksString}"' }], + ["BrowserContext.clockInstall", { title: 'Install clock "{timeNumber}{timeString}"' }], + ["BrowserContext.clockPauseAt", { title: 'Pause clock "{timeNumber}{timeString}"' }], + ["BrowserContext.clockResume", { title: "Resume clock" }], + ["BrowserContext.clockRunFor", { title: 'Run clock "{ticksNumber}{ticksString}"' }], + ["BrowserContext.clockSetFixedTime", { title: 'Set fixed time "{timeNumber}{timeString}"' }], + ["BrowserContext.clockSetSystemTime", { title: 'Set system time "{timeNumber}{timeString}"' }], + ["Page.addInitScript", {}], + ["Page.close", { title: "Close" }], + ["Page.emulateMedia", { title: "Emulate media", snapshot: true }], + ["Page.exposeBinding", { title: "Expose binding" }], + ["Page.goBack", { title: "Go back", slowMo: true, snapshot: true }], + ["Page.goForward", { title: "Go forward", slowMo: true, snapshot: true }], + ["Page.requestGC", { title: "Request garbage collection" }], + ["Page.registerLocatorHandler", { title: "Register locator handler" }], + ["Page.resolveLocatorHandlerNoReply", { internal: true }], + ["Page.unregisterLocatorHandler", { title: "Unregister locator handler" }], + ["Page.reload", { title: "Reload", slowMo: true, snapshot: true }], + ["Page.expectScreenshot", { title: "Expect screenshot", snapshot: true }], + ["Page.screenshot", { title: "Screenshot", snapshot: true }], + ["Page.setExtraHTTPHeaders", { title: "Set extra HTTP headers" }], + ["Page.setNetworkInterceptionPatterns", { internal: true }], + ["Page.setWebSocketInterceptionPatterns", { internal: true }], + ["Page.setViewportSize", { title: "Set viewport size", snapshot: true }], + ["Page.keyboardDown", { title: 'Key down "{key}"', slowMo: true, snapshot: true }], + ["Page.keyboardUp", { title: 'Key up "{key}"', slowMo: true, snapshot: true }], + ["Page.keyboardInsertText", { title: 'Insert "{text}"', slowMo: true, snapshot: true }], + ["Page.keyboardType", { title: 'Type "{text}"', slowMo: true, snapshot: true }], + ["Page.keyboardPress", { title: 'Press "{key}"', slowMo: true, snapshot: true }], + ["Page.mouseMove", { title: "Mouse move", slowMo: true, snapshot: true }], + ["Page.mouseDown", { title: "Mouse down", slowMo: true, snapshot: true }], + ["Page.mouseUp", { title: "Mouse up", slowMo: true, snapshot: true }], + ["Page.mouseClick", { title: "Click", slowMo: true, snapshot: true }], + ["Page.mouseWheel", { title: "Mouse wheel", slowMo: true, snapshot: true }], + ["Page.touchscreenTap", { title: "Tap", slowMo: true, snapshot: true }], + ["Page.accessibilitySnapshot", { internal: true, snapshot: true }], + ["Page.pdf", { title: "PDF" }], + ["Page.snapshotForAI", { internal: true, snapshot: true }], + ["Page.startJSCoverage", { internal: true }], + ["Page.stopJSCoverage", { internal: true }], + ["Page.startCSSCoverage", { internal: true }], + ["Page.stopCSSCoverage", { internal: true }], + ["Page.bringToFront", { title: "Bring to front" }], + ["Page.updateSubscription", { internal: true }], + ["Frame.evalOnSelector", { title: "Evaluate", snapshot: true }], + ["Frame.evalOnSelectorAll", { title: "Evaluate", snapshot: true }], + ["Frame.addScriptTag", { title: "Add script tag", snapshot: true }], + ["Frame.addStyleTag", { title: "Add style tag", snapshot: true }], + ["Frame.ariaSnapshot", { title: "Aria snapshot", snapshot: true }], + ["Frame.blur", { title: "Blur", slowMo: true, snapshot: true }], + ["Frame.check", { title: "Check", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.click", { title: "Click", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.content", { title: "Get content", snapshot: true }], + ["Frame.dragAndDrop", { title: "Drag and drop", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.dblclick", { title: "Double click", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.dispatchEvent", { title: 'Dispatch "{type}"', slowMo: true, snapshot: true }], + ["Frame.evaluateExpression", { title: "Evaluate", snapshot: true }], + ["Frame.evaluateExpressionHandle", { title: "Evaluate", snapshot: true }], + ["Frame.fill", { title: 'Fill "{value}"', slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.focus", { title: "Focus", slowMo: true, snapshot: true }], + ["Frame.frameElement", { internal: true }], + ["Frame.highlight", { internal: true }], + ["Frame.getAttribute", { internal: true, snapshot: true }], + ["Frame.goto", { title: 'Navigate to "{url}"', slowMo: true, snapshot: true }], + ["Frame.hover", { title: "Hover", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.innerHTML", { title: "Get HTML", snapshot: true }], + ["Frame.innerText", { title: "Get inner text", snapshot: true }], + ["Frame.inputValue", { title: "Get input value", snapshot: true }], + ["Frame.isChecked", { title: "Is checked", snapshot: true }], + ["Frame.isDisabled", { title: "Is disabled", snapshot: true }], + ["Frame.isEnabled", { title: "Is enabled", snapshot: true }], + ["Frame.isHidden", { title: "Is hidden", snapshot: true }], + ["Frame.isVisible", { title: "Is visible", snapshot: true }], + ["Frame.isEditable", { title: "Is editable", snapshot: true }], + ["Frame.press", { title: 'Press "{key}"', slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.querySelector", { title: "Query selector", snapshot: true }], + ["Frame.querySelectorAll", { title: "Query selector all", snapshot: true }], + ["Frame.queryCount", { title: "Query count", snapshot: true }], + ["Frame.selectOption", { title: "Select option", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.setContent", { title: "Set content", snapshot: true }], + ["Frame.setInputFiles", { title: "Set input files", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.tap", { title: "Tap", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.textContent", { title: "Get text content", snapshot: true }], + ["Frame.title", { internal: true }], + ["Frame.type", { title: "Type", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.uncheck", { title: "Uncheck", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["Frame.waitForTimeout", { title: "Wait for timeout", snapshot: true }], + ["Frame.waitForFunction", { title: "Wait for function", snapshot: true }], + ["Frame.waitForSelector", { title: "Wait for selector", snapshot: true }], + ["Frame.expect", { title: 'Expect "{expression}"', snapshot: true }], + ["Worker.evaluateExpression", { title: "Evaluate" }], + ["Worker.evaluateExpressionHandle", { title: "Evaluate" }], + ["JSHandle.dispose", {}], + ["ElementHandle.dispose", {}], + ["JSHandle.evaluateExpression", { title: "Evaluate", snapshot: true }], + ["ElementHandle.evaluateExpression", { title: "Evaluate", snapshot: true }], + ["JSHandle.evaluateExpressionHandle", { title: "Evaluate", snapshot: true }], + ["ElementHandle.evaluateExpressionHandle", { title: "Evaluate", snapshot: true }], + ["JSHandle.getPropertyList", { internal: true }], + ["ElementHandle.getPropertyList", { internal: true }], + ["JSHandle.getProperty", { internal: true }], + ["ElementHandle.getProperty", { internal: true }], + ["JSHandle.jsonValue", { internal: true }], + ["ElementHandle.jsonValue", { internal: true }], + ["ElementHandle.evalOnSelector", { title: "Evaluate", snapshot: true }], + ["ElementHandle.evalOnSelectorAll", { title: "Evaluate", snapshot: true }], + ["ElementHandle.boundingBox", { title: "Get bounding box", snapshot: true }], + ["ElementHandle.check", { title: "Check", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.click", { title: "Click", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.contentFrame", { internal: true, snapshot: true }], + ["ElementHandle.dblclick", { title: "Double click", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.dispatchEvent", { title: "Dispatch event", slowMo: true, snapshot: true }], + ["ElementHandle.fill", { title: 'Fill "{value}"', slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.focus", { title: "Focus", slowMo: true, snapshot: true }], + ["ElementHandle.generateLocatorString", { internal: true }], + ["ElementHandle.getAttribute", { internal: true }], + ["ElementHandle.hover", { title: "Hover", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.innerHTML", { title: "Get HTML", snapshot: true }], + ["ElementHandle.innerText", { title: "Get inner text", snapshot: true }], + ["ElementHandle.inputValue", { title: "Get input value", snapshot: true }], + ["ElementHandle.isChecked", { title: "Is checked", snapshot: true }], + ["ElementHandle.isDisabled", { title: "Is disabled", snapshot: true }], + ["ElementHandle.isEditable", { title: "Is editable", snapshot: true }], + ["ElementHandle.isEnabled", { title: "Is enabled", snapshot: true }], + ["ElementHandle.isHidden", { title: "Is hidden", snapshot: true }], + ["ElementHandle.isVisible", { title: "Is visible", snapshot: true }], + ["ElementHandle.ownerFrame", { title: "Get owner frame" }], + ["ElementHandle.press", { title: 'Press "{key}"', slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.querySelector", { title: "Query selector", snapshot: true }], + ["ElementHandle.querySelectorAll", { title: "Query selector all", snapshot: true }], + ["ElementHandle.screenshot", { title: "Screenshot", snapshot: true }], + ["ElementHandle.scrollIntoViewIfNeeded", { title: "Scroll into view", slowMo: true, snapshot: true }], + ["ElementHandle.selectOption", { title: "Select option", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.selectText", { title: "Select text", slowMo: true, snapshot: true }], + ["ElementHandle.setInputFiles", { title: "Set input files", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.tap", { title: "Tap", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.textContent", { title: "Get text content", snapshot: true }], + ["ElementHandle.type", { title: "Type", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.uncheck", { title: "Uncheck", slowMo: true, snapshot: true, pausesBeforeInput: true }], + ["ElementHandle.waitForElementState", { title: "Wait for state", snapshot: true }], + ["ElementHandle.waitForSelector", { title: "Wait for selector", snapshot: true }], + ["Request.response", { internal: true }], + ["Request.rawRequestHeaders", { internal: true }], + ["Route.redirectNavigationRequest", { internal: true }], + ["Route.abort", {}], + ["Route.continue", { internal: true }], + ["Route.fulfill", { internal: true }], + ["WebSocketRoute.connect", { internal: true }], + ["WebSocketRoute.ensureOpened", { internal: true }], + ["WebSocketRoute.sendToPage", { internal: true }], + ["WebSocketRoute.sendToServer", { internal: true }], + ["WebSocketRoute.closePage", { internal: true }], + ["WebSocketRoute.closeServer", { internal: true }], + ["Response.body", { internal: true }], + ["Response.securityDetails", { internal: true }], + ["Response.serverAddr", { internal: true }], + ["Response.rawResponseHeaders", { internal: true }], + ["Response.sizes", { internal: true }], + ["BindingCall.reject", { internal: true }], + ["BindingCall.resolve", { internal: true }], + ["Dialog.accept", { title: "Accept dialog" }], + ["Dialog.dismiss", { title: "Dismiss dialog" }], + ["Tracing.tracingStart", { internal: true }], + ["Tracing.tracingStartChunk", { internal: true }], + ["Tracing.tracingGroup", { title: 'Trace "{name}"' }], + ["Tracing.tracingGroupEnd", { title: "Group end" }], + ["Tracing.tracingStopChunk", { internal: true }], + ["Tracing.tracingStop", { internal: true }], + ["Artifact.pathAfterFinished", { internal: true }], + ["Artifact.saveAs", { internal: true }], + ["Artifact.saveAsStream", { internal: true }], + ["Artifact.failure", { internal: true }], + ["Artifact.stream", { internal: true }], + ["Artifact.cancel", { internal: true }], + ["Artifact.delete", { internal: true }], + ["Stream.read", { internal: true }], + ["Stream.close", { internal: true }], + ["WritableStream.write", { internal: true }], + ["WritableStream.close", { internal: true }], + ["CDPSession.send", { internal: true }], + ["CDPSession.detach", { internal: true }], + ["Electron.launch", { title: "Launch electron" }], + ["ElectronApplication.browserWindow", { internal: true }], + ["ElectronApplication.evaluateExpression", { title: "Evaluate" }], + ["ElectronApplication.evaluateExpressionHandle", { title: "Evaluate" }], + ["ElectronApplication.updateSubscription", { internal: true }], + ["Android.devices", { internal: true }], + ["AndroidSocket.write", { internal: true }], + ["AndroidSocket.close", { internal: true }], + ["AndroidDevice.wait", {}], + ["AndroidDevice.fill", { title: 'Fill "{text}"' }], + ["AndroidDevice.tap", { title: "Tap" }], + ["AndroidDevice.drag", { title: "Drag" }], + ["AndroidDevice.fling", { title: "Fling" }], + ["AndroidDevice.longTap", { title: "Long tap" }], + ["AndroidDevice.pinchClose", { title: "Pinch close" }], + ["AndroidDevice.pinchOpen", { title: "Pinch open" }], + ["AndroidDevice.scroll", { title: "Scroll" }], + ["AndroidDevice.swipe", { title: "Swipe" }], + ["AndroidDevice.info", { internal: true }], + ["AndroidDevice.screenshot", { title: "Screenshot" }], + ["AndroidDevice.inputType", { title: "Type" }], + ["AndroidDevice.inputPress", { title: "Press" }], + ["AndroidDevice.inputTap", { title: "Tap" }], + ["AndroidDevice.inputSwipe", { title: "Swipe" }], + ["AndroidDevice.inputDrag", { title: "Drag" }], + ["AndroidDevice.launchBrowser", { title: "Launch browser" }], + ["AndroidDevice.open", { title: "Open app" }], + ["AndroidDevice.shell", { internal: true }], + ["AndroidDevice.installApk", { title: "Install apk" }], + ["AndroidDevice.push", { title: "Push" }], + ["AndroidDevice.connectToWebView", { internal: true }], + ["AndroidDevice.close", { internal: true }], + ["JsonPipe.send", { internal: true }], + ["JsonPipe.close", { internal: true }] +]); +function formatProtocolParam(params, name) { + if (!params) + return ""; + if (name === "url") { + try { + const urlObject = new URL(params[name]); + if (urlObject.protocol === "data:") + return urlObject.protocol; + if (urlObject.protocol === "about:") + return params[name]; + return urlObject.pathname + urlObject.search; + } catch (error2) { + return params[name]; + } + } + if (name === "timeNumber") { + return new Date(params[name]).toString(); + } + return deepParam(params, name); +} +function deepParam(params, name) { + const tokens = name.split("."); + let current2 = params; + for (const token of tokens) { + if (typeof current2 !== "object" || current2 === null) + return ""; + current2 = current2[token]; + } + if (current2 === void 0) + return ""; + return String(current2); +} +function renderTitleForCall(metadata) { + var _a2; + const titleFormat = metadata.title ?? ((_a2 = methodMetainfo.get(metadata.type + "." + metadata.method)) == null ? void 0 : _a2.title) ?? metadata.method; + return titleFormat.replace(/\{([^}]+)\}/g, (_, p1) => { + return formatProtocolParam(metadata.params, p1); + }); +} +function isRegExp$4(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function isObject(obj) { + return typeof obj === "object" && obj !== null; +} +function isError$2(obj) { + var _a2; + return obj instanceof Error || obj && ((_a2 = Object.getPrototypeOf(obj)) == null ? void 0 : _a2.name) === "Error"; +} +let _timeShift = 0; +function monotonicTime() { + return Math.floor((performance.now() + _timeShift) * 1e3) / 1e3; +} +const DEFAULT_PLAYWRIGHT_TIMEOUT = 3e4; +const DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1e3; +async function raceAgainstDeadline(cb, deadline) { + let timer; + return Promise.race([ + cb().then((result) => { + return { result, timedOut: false }; + }), + new Promise((resolve) => { + const kMaxDeadline = 2147483647; + const timeout = (deadline || kMaxDeadline) - monotonicTime(); + timer = setTimeout(() => resolve({ timedOut: true }), timeout); + }) + ]).finally(() => { + clearTimeout(timer); + }); +} +const escapedChars = /* @__PURE__ */ new Set(["$", "^", "+", ".", "*", "(", ")", "|", "\\", "?", "{", "}", "[", "]"]); +function globToRegexPattern(glob) { + const tokens = ["^"]; + let inGroup = false; + for (let i = 0; i < glob.length; ++i) { + const c = glob[i]; + if (c === "\\" && i + 1 < glob.length) { + const char = glob[++i]; + tokens.push(escapedChars.has(char) ? "\\" + char : char); + continue; + } + if (c === "*") { + const beforeDeep = glob[i - 1]; + let starCount = 1; + while (glob[i + 1] === "*") { + starCount++; + i++; + } + const afterDeep = glob[i + 1]; + const isDeep = starCount > 1 && (beforeDeep === "/" || beforeDeep === void 0) && (afterDeep === "/" || afterDeep === void 0); + if (isDeep) { + tokens.push("((?:[^/]*(?:/|$))*)"); + i++; + } else { + tokens.push("([^/]*)"); + } + continue; + } + switch (c) { + case "{": + inGroup = true; + tokens.push("("); + break; + case "}": + inGroup = false; + tokens.push(")"); + break; + case ",": + if (inGroup) { + tokens.push("|"); + break; + } + tokens.push("\\" + c); + break; + default: + tokens.push(escapedChars.has(c) ? "\\" + c : c); + } + } + tokens.push("$"); + return tokens.join(""); +} +function isRegExp$3(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function urlMatchesEqual(match1, match2) { + if (isRegExp$3(match1) && isRegExp$3(match2)) + return match1.source === match2.source && match1.flags === match2.flags; + return match1 === match2; +} +function urlMatches(baseURL, urlString, match, webSocketUrl) { + if (match === void 0 || match === "") + return true; + if (isString(match)) + match = new RegExp(resolveGlobToRegexPattern(baseURL, match, webSocketUrl)); + if (isRegExp$3(match)) { + const r = match.test(urlString); + return r; + } + const url2 = parseURL$1(urlString); + if (!url2) + return false; + if (typeof match !== "function") + throw new Error("url parameter should be string, RegExp or function"); + return match(url2); +} +function resolveGlobToRegexPattern(baseURL, glob, webSocketUrl) { + if (webSocketUrl) + baseURL = toWebSocketBaseUrl(baseURL); + glob = resolveGlobBase(baseURL, glob); + return globToRegexPattern(glob); +} +function toWebSocketBaseUrl(baseURL) { + if (baseURL && /^https?:\/\//.test(baseURL)) + baseURL = baseURL.replace(/^http/, "ws"); + return baseURL; +} +function resolveGlobBase(baseURL, match) { + if (!match.startsWith("*")) { + let mapToken = function(original, replacement) { + if (original.length === 0) + return ""; + tokenMap.set(replacement, original); + return replacement; + }; + const tokenMap = /* @__PURE__ */ new Map(); + match = match.replaceAll(/\\\\\?/g, "?"); + const relativePath = match.split("/").map((token, index2) => { + if (token === "." || token === ".." || token === "") + return token; + if (index2 === 0 && token.endsWith(":")) + return mapToken(token, "http:"); + const questionIndex = token.indexOf("?"); + if (questionIndex === -1) + return mapToken(token, `$_${index2}_$`); + const newPrefix = mapToken(token.substring(0, questionIndex), `$_${index2}_$`); + const newSuffix = mapToken(token.substring(questionIndex), `?$_${index2}_$`); + return newPrefix + newSuffix; + }).join("/"); + let resolved = constructURLBasedOnBaseURL(baseURL, relativePath); + for (const [token, original] of tokenMap) + resolved = resolved.replace(token, original); + match = resolved; + } + return match; +} +function parseURL$1(url2) { + try { + return new URL(url2); + } catch (e) { + return null; + } +} +function constructURLBasedOnBaseURL(baseURL, givenURL) { + try { + return new URL(givenURL, baseURL).toString(); + } catch (e) { + return givenURL; + } +} +function blendWithWhite(c, a) { + return 255 + (c - 255) * a; +} +function rgb2gray(r, g, b) { + return 77 * r + 150 * g + 29 * b + 128 >> 8; +} +function colorDeltaE94(rgb1, rgb2) { + const [l1, a1, b1] = xyz2lab(srgb2xyz(rgb1)); + const [l2, a2, b2] = xyz2lab(srgb2xyz(rgb2)); + const deltaL = l1 - l2; + const deltaA = a1 - a2; + const deltaB = b1 - b2; + const c1 = Math.sqrt(a1 ** 2 + b1 ** 2); + const c2 = Math.sqrt(a2 ** 2 + b2 ** 2); + const deltaC = c1 - c2; + let deltaH = deltaA ** 2 + deltaB ** 2 - deltaC ** 2; + deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH); + const k1 = 0.045; + const k2 = 0.015; + const kL = 1; + const kC = 1; + const kH = 1; + const sC = 1 + k1 * c1; + const sH = 1 + k2 * c1; + const sL = 1; + return Math.sqrt((deltaL / sL / kL) ** 2 + (deltaC / sC / kC) ** 2 + (deltaH / sH / kH) ** 2); +} +function srgb2xyz(rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + return [ + r * 0.4124 + g * 0.3576 + b * 0.1805, + r * 0.2126 + g * 0.7152 + b * 0.0722, + r * 0.0193 + g * 0.1192 + b * 0.9505 + ]; +} +const sigma_pow2 = 6 * 6 / 29 / 29; +const sigma_pow3 = 6 * 6 * 6 / 29 / 29 / 29; +function xyz2lab(xyz) { + const x = xyz[0] / 0.950489; + const y = xyz[1]; + const z = xyz[2] / 1.08884; + const fx = x > sigma_pow3 ? x ** (1 / 3) : x / 3 / sigma_pow2 + 4 / 29; + const fy = y > sigma_pow3 ? y ** (1 / 3) : y / 3 / sigma_pow2 + 4 / 29; + const fz = z > sigma_pow3 ? z ** (1 / 3) : z / 3 / sigma_pow2 + 4 / 29; + const l = 116 * fy - 16; + const a = 500 * (fx - fy); + const b = 200 * (fy - fz); + return [l, a, b]; +} +class ImageChannel { + static intoRGB(width, height, data2, options2 = {}) { + const { + paddingSize = 0, + paddingColorOdd = [255, 0, 255], + paddingColorEven = [0, 255, 0] + } = options2; + const newWidth = width + 2 * paddingSize; + const newHeight = height + 2 * paddingSize; + const r = new Uint8Array(newWidth * newHeight); + const g = new Uint8Array(newWidth * newHeight); + const b = new Uint8Array(newWidth * newHeight); + for (let y = 0; y < newHeight; ++y) { + for (let x = 0; x < newWidth; ++x) { + const index2 = y * newWidth + x; + if (y >= paddingSize && y < newHeight - paddingSize && x >= paddingSize && x < newWidth - paddingSize) { + const offset2 = ((y - paddingSize) * width + (x - paddingSize)) * 4; + const alpha = data2[offset2 + 3] === 255 ? 1 : data2[offset2 + 3] / 255; + r[index2] = blendWithWhite(data2[offset2], alpha); + g[index2] = blendWithWhite(data2[offset2 + 1], alpha); + b[index2] = blendWithWhite(data2[offset2 + 2], alpha); + } else { + const color = (y + x) % 2 === 0 ? paddingColorEven : paddingColorOdd; + r[index2] = color[0]; + g[index2] = color[1]; + b[index2] = color[2]; + } + } + } + return [ + new ImageChannel(newWidth, newHeight, r), + new ImageChannel(newWidth, newHeight, g), + new ImageChannel(newWidth, newHeight, b) + ]; + } + constructor(width, height, data2) { + this.data = data2; + this.width = width; + this.height = height; + } + get(x, y) { + return this.data[y * this.width + x]; + } + boundXY(x, y) { + return [ + Math.min(Math.max(x, 0), this.width - 1), + Math.min(Math.max(y, 0), this.height - 1) + ]; + } +} +const DYNAMIC_RANGE = 2 ** 8 - 1; +function ssim(stats, x1, y1, x2, y2) { + const mean1 = stats.meanC1(x1, y1, x2, y2); + const mean2 = stats.meanC2(x1, y1, x2, y2); + const var1 = stats.varianceC1(x1, y1, x2, y2); + const var2 = stats.varianceC2(x1, y1, x2, y2); + const cov = stats.covariance(x1, y1, x2, y2); + const c1 = (0.01 * DYNAMIC_RANGE) ** 2; + const c2 = (0.03 * DYNAMIC_RANGE) ** 2; + return (2 * mean1 * mean2 + c1) * (2 * cov + c2) / (mean1 ** 2 + mean2 ** 2 + c1) / (var1 + var2 + c2); +} +class FastStats { + constructor(c1, c2) { + this.c1 = c1; + this.c2 = c2; + const { width, height } = c1; + this._partialSumC1 = new Array(width * height); + this._partialSumC2 = new Array(width * height); + this._partialSumSq1 = new Array(width * height); + this._partialSumSq2 = new Array(width * height); + this._partialSumMult = new Array(width * height); + const recalc = (mx, idx, initial, x, y) => { + mx[idx] = initial; + if (y > 0) + mx[idx] += mx[(y - 1) * width + x]; + if (x > 0) + mx[idx] += mx[y * width + x - 1]; + if (x > 0 && y > 0) + mx[idx] -= mx[(y - 1) * width + x - 1]; + }; + for (let y = 0; y < height; ++y) { + for (let x = 0; x < width; ++x) { + const idx = y * width + x; + recalc(this._partialSumC1, idx, this.c1.data[idx], x, y); + recalc(this._partialSumC2, idx, this.c2.data[idx], x, y); + recalc(this._partialSumSq1, idx, this.c1.data[idx] * this.c1.data[idx], x, y); + recalc(this._partialSumSq2, idx, this.c2.data[idx] * this.c2.data[idx], x, y); + recalc(this._partialSumMult, idx, this.c1.data[idx] * this.c2.data[idx], x, y); + } + } + } + _sum(partialSum, x1, y1, x2, y2) { + const width = this.c1.width; + let result = partialSum[y2 * width + x2]; + if (y1 > 0) + result -= partialSum[(y1 - 1) * width + x2]; + if (x1 > 0) + result -= partialSum[y2 * width + x1 - 1]; + if (x1 > 0 && y1 > 0) + result += partialSum[(y1 - 1) * width + x1 - 1]; + return result; + } + meanC1(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return this._sum(this._partialSumC1, x1, y1, x2, y2) / N; + } + meanC2(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return this._sum(this._partialSumC2, x1, y1, x2, y2) / N; + } + varianceC1(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumSq1, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) ** 2 / N) / N; + } + varianceC2(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumSq2, x1, y1, x2, y2) - this._sum(this._partialSumC2, x1, y1, x2, y2) ** 2 / N) / N; + } + covariance(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumMult, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) * this._sum(this._partialSumC2, x1, y1, x2, y2) / N) / N; + } +} +const SSIM_WINDOW_RADIUS = 15; +const VARIANCE_WINDOW_RADIUS = 1; +function drawPixel(width, data2, x, y, r, g, b) { + const idx = (y * width + x) * 4; + data2[idx + 0] = r; + data2[idx + 1] = g; + data2[idx + 2] = b; + data2[idx + 3] = 255; +} +function compare(actual, expected, diff3, width, height, options2 = {}) { + const { + maxColorDeltaE94 = 1 + } = options2; + const paddingSize = Math.max(VARIANCE_WINDOW_RADIUS, SSIM_WINDOW_RADIUS); + const paddingColorEven = [255, 0, 255]; + const paddingColorOdd = [0, 255, 0]; + const [r1, g1, b1] = ImageChannel.intoRGB(width, height, expected, { + paddingSize, + paddingColorEven, + paddingColorOdd + }); + const [r2, g2, b2] = ImageChannel.intoRGB(width, height, actual, { + paddingSize, + paddingColorEven, + paddingColorOdd + }); + const noop2 = (x, y) => { + }; + const drawRedPixel = diff3 ? (x, y) => drawPixel(width, diff3, x - paddingSize, y - paddingSize, 255, 0, 0) : noop2; + const drawYellowPixel = diff3 ? (x, y) => drawPixel(width, diff3, x - paddingSize, y - paddingSize, 255, 255, 0) : noop2; + const drawGrayPixel = diff3 ? (x, y) => { + const gray = rgb2gray(r1.get(x, y), g1.get(x, y), b1.get(x, y)); + const value = blendWithWhite(gray, 0.1); + drawPixel(width, diff3, x - paddingSize, y - paddingSize, value, value, value); + } : noop2; + let fastR, fastG, fastB; + let diffCount = 0; + for (let y = paddingSize; y < r1.height - paddingSize; ++y) { + for (let x = paddingSize; x < r1.width - paddingSize; ++x) { + if (r1.get(x, y) === r2.get(x, y) && g1.get(x, y) === g2.get(x, y) && b1.get(x, y) === b2.get(x, y)) { + drawGrayPixel(x, y); + continue; + } + const delta = colorDeltaE94( + [r1.get(x, y), g1.get(x, y), b1.get(x, y)], + [r2.get(x, y), g2.get(x, y), b2.get(x, y)] + ); + if (delta <= maxColorDeltaE94) { + drawGrayPixel(x, y); + continue; + } + if (!fastR || !fastG || !fastB) { + fastR = new FastStats(r1, r2); + fastG = new FastStats(g1, g2); + fastB = new FastStats(b1, b2); + } + const [varX1, varY1] = r1.boundXY(x - VARIANCE_WINDOW_RADIUS, y - VARIANCE_WINDOW_RADIUS); + const [varX2, varY2] = r1.boundXY(x + VARIANCE_WINDOW_RADIUS, y + VARIANCE_WINDOW_RADIUS); + const var1 = fastR.varianceC1(varX1, varY1, varX2, varY2) + fastG.varianceC1(varX1, varY1, varX2, varY2) + fastB.varianceC1(varX1, varY1, varX2, varY2); + const var2 = fastR.varianceC2(varX1, varY1, varX2, varY2) + fastG.varianceC2(varX1, varY1, varX2, varY2) + fastB.varianceC2(varX1, varY1, varX2, varY2); + if (var1 === 0 || var2 === 0) { + drawRedPixel(x, y); + ++diffCount; + continue; + } + const [ssimX1, ssimY1] = r1.boundXY(x - SSIM_WINDOW_RADIUS, y - SSIM_WINDOW_RADIUS); + const [ssimX2, ssimY2] = r1.boundXY(x + SSIM_WINDOW_RADIUS, y + SSIM_WINDOW_RADIUS); + const ssimRGB = (ssim(fastR, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastG, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastB, ssimX1, ssimY1, ssimX2, ssimY2)) / 3; + const isAntialiased = ssimRGB >= 0.99; + if (isAntialiased) { + drawYellowPixel(x, y); + } else { + drawRedPixel(x, y); + ++diffCount; + } + } + } + return diffCount; +} +var pixelmatch_1; +var hasRequiredPixelmatch; +function requirePixelmatch() { + if (hasRequiredPixelmatch) return pixelmatch_1; + hasRequiredPixelmatch = 1; + pixelmatch_1 = pixelmatch2; + const defaultOptions2 = { + threshold: 0.1, + // matching threshold (0 to 1); smaller is more sensitive + includeAA: false, + // whether to skip anti-aliasing detection + alpha: 0.1, + // opacity of original image in diff output + aaColor: [255, 255, 0], + // color of anti-aliased pixels in diff output + diffColor: [255, 0, 0], + // color of different pixels in diff output + diffColorAlt: null, + // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two + diffMask: false + // draw the diff over a transparent background (a mask) + }; + function pixelmatch2(img1, img2, output, width, height, options2) { + if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output)) + throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected."); + if (img1.length !== img2.length || output && output.length !== img1.length) + throw new Error("Image sizes do not match."); + if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height."); + options2 = Object.assign({}, defaultOptions2, options2); + const len = width * height; + const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len); + const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len); + let identical = true; + for (let i = 0; i < len; i++) { + if (a32[i] !== b32[i]) { + identical = false; + break; + } + } + if (identical) { + if (output && !options2.diffMask) { + for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options2.alpha, output); + } + return 0; + } + const maxDelta = 35215 * options2.threshold * options2.threshold; + let diff3 = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const pos = (y * width + x) * 4; + const delta = colorDelta(img1, img2, pos, pos); + if (Math.abs(delta) > maxDelta) { + if (!options2.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) { + if (output && !options2.diffMask) drawPixel2(output, pos, ...options2.aaColor); + } else { + if (output) { + drawPixel2(output, pos, ...delta < 0 && options2.diffColorAlt || options2.diffColor); + } + diff3++; + } + } else if (output) { + if (!options2.diffMask) drawGrayPixel(img1, pos, options2.alpha, output); + } + } + } + return diff3; + } + function isPixelData(arr) { + return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1; + } + function antialiased(img, x1, y1, width, height, img2) { + const x0 = Math.max(x1 - 1, 0); + const y0 = Math.max(y1 - 1, 0); + const x2 = Math.min(x1 + 1, width - 1); + const y2 = Math.min(y1 + 1, height - 1); + const pos = (y1 * width + x1) * 4; + let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; + let min2 = 0; + let max2 = 0; + let minX, minY, maxX, maxY; + for (let x = x0; x <= x2; x++) { + for (let y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + const delta = colorDelta(img, img, pos, (y * width + x) * 4, true); + if (delta === 0) { + zeroes++; + if (zeroes > 2) return false; + } else if (delta < min2) { + min2 = delta; + minX = x; + minY = y; + } else if (delta > max2) { + max2 = delta; + maxX = x; + maxY = y; + } + } + } + if (min2 === 0 || max2 === 0) return false; + return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height); + } + function hasManySiblings(img, x1, y1, width, height) { + const x0 = Math.max(x1 - 1, 0); + const y0 = Math.max(y1 - 1, 0); + const x2 = Math.min(x1 + 1, width - 1); + const y2 = Math.min(y1 + 1, height - 1); + const pos = (y1 * width + x1) * 4; + let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; + for (let x = x0; x <= x2; x++) { + for (let y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + const pos2 = (y * width + x) * 4; + if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++; + if (zeroes > 2) return true; + } + } + return false; + } + function colorDelta(img1, img2, k, m, yOnly) { + let r1 = img1[k + 0]; + let g1 = img1[k + 1]; + let b1 = img1[k + 2]; + let a1 = img1[k + 3]; + let r2 = img2[m + 0]; + let g2 = img2[m + 1]; + let b2 = img2[m + 2]; + let a2 = img2[m + 3]; + if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0; + if (a1 < 255) { + a1 /= 255; + r1 = blend(r1, a1); + g1 = blend(g1, a1); + b1 = blend(b1, a1); + } + if (a2 < 255) { + a2 /= 255; + r2 = blend(r2, a2); + g2 = blend(g2, a2); + b2 = blend(b2, a2); + } + const y1 = rgb2y(r1, g1, b1); + const y2 = rgb2y(r2, g2, b2); + const y = y1 - y2; + if (yOnly) return y; + const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2); + const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2); + const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q; + return y1 > y2 ? -delta : delta; + } + function rgb2y(r, g, b) { + return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; + } + function rgb2i(r, g, b) { + return r * 0.59597799 - g * 0.2741761 - b * 0.32180189; + } + function rgb2q(r, g, b) { + return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; + } + function blend(c, a) { + return 255 + (c - 255) * a; + } + function drawPixel2(output, pos, r, g, b) { + output[pos + 0] = r; + output[pos + 1] = g; + output[pos + 2] = b; + output[pos + 3] = 255; + } + function drawGrayPixel(img, i, alpha, output) { + const r = img[i + 0]; + const g = img[i + 1]; + const b = img[i + 2]; + const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255); + drawPixel2(output, i, val, val, val); + } + return pixelmatch_1; +} +var pixelmatchExports = requirePixelmatch(); +const pixelmatch = /* @__PURE__ */ getDefaultExportFromCjs(pixelmatchExports); +function getComparator(mimeType) { + return compareImages.bind(null, "image/png"); +} +const JPEG_JS_MAX_BUFFER_SIZE_IN_MB = 5 * 1024; +function compareImages(mimeType, actualBuffer, expectedBuffer, options2 = {}) { + if (!actualBuffer || !(actualBuffer instanceof Buffer)) + return { errorMessage: "Actual result should be a Buffer." }; + validateBuffer(expectedBuffer, mimeType); + let actual = mimeType === "image/png" ? PNG.sync.read(actualBuffer) : jpegjs.decode(actualBuffer, { maxMemoryUsageInMB: JPEG_JS_MAX_BUFFER_SIZE_IN_MB }); + let expected = mimeType === "image/png" ? PNG.sync.read(expectedBuffer) : jpegjs.decode(expectedBuffer, { maxMemoryUsageInMB: JPEG_JS_MAX_BUFFER_SIZE_IN_MB }); + const size = { width: Math.max(expected.width, actual.width), height: Math.max(expected.height, actual.height) }; + let sizesMismatchError = ""; + if (expected.width !== actual.width || expected.height !== actual.height) { + sizesMismatchError = `Expected an image ${expected.width}px by ${expected.height}px, received ${actual.width}px by ${actual.height}px. `; + actual = resizeImage(actual, size); + expected = resizeImage(expected, size); + } + const diff22 = new PNG({ width: size.width, height: size.height }); + let count; + if (options2.comparator === "ssim-cie94") { + count = compare(expected.data, actual.data, diff22.data, size.width, size.height, { + // All ΔE* formulae are originally designed to have the difference of 1.0 stand for a "just noticeable difference" (JND). + // See https://en.wikipedia.org/wiki/Color_difference#CIELAB_%CE%94E* + maxColorDeltaE94: 1 + }); + } else if ((options2.comparator ?? "pixelmatch") === "pixelmatch") { + count = pixelmatch(expected.data, actual.data, diff22.data, size.width, size.height, { + threshold: options2.threshold ?? 0.2 + }); + } else { + throw new Error(`Configuration specifies unknown comparator "${options2.comparator}"`); + } + const maxDiffPixels1 = options2.maxDiffPixels; + const maxDiffPixels2 = options2.maxDiffPixelRatio !== void 0 ? expected.width * expected.height * options2.maxDiffPixelRatio : void 0; + let maxDiffPixels; + if (maxDiffPixels1 !== void 0 && maxDiffPixels2 !== void 0) + maxDiffPixels = Math.min(maxDiffPixels1, maxDiffPixels2); + else + maxDiffPixels = maxDiffPixels1 ?? maxDiffPixels2 ?? 0; + const ratio = Math.ceil(count / (expected.width * expected.height) * 100) / 100; + const pixelsMismatchError = count > maxDiffPixels ? `${count} pixels (ratio ${ratio.toFixed(2)} of all image pixels) are different.` : ""; + if (pixelsMismatchError || sizesMismatchError) + return { errorMessage: sizesMismatchError + pixelsMismatchError, diff: PNG.sync.write(diff22) }; + return null; +} +function validateBuffer(buffer2, mimeType) { + if (mimeType === "image/png") { + const pngMagicNumber = [137, 80, 78, 71, 13, 10, 26, 10]; + if (buffer2.length < pngMagicNumber.length || !pngMagicNumber.every((byte, index2) => buffer2[index2] === byte)) + throw new Error("could not decode image as PNG."); + } else if (mimeType === "image/jpeg") { + const jpegMagicNumber = [255, 216]; + if (buffer2.length < jpegMagicNumber.length || !jpegMagicNumber.every((byte, index2) => buffer2[index2] === byte)) + throw new Error("could not decode image as JPEG."); + } +} +function resizeImage(image, size) { + if (image.width === size.width && image.height === size.height) + return image; + const buffer2 = new Uint8Array(size.width * size.height * 4); + for (let y = 0; y < size.height; y++) { + for (let x = 0; x < size.width; x++) { + const to = (y * size.width + x) * 4; + if (y < image.height && x < image.width) { + const from2 = (y * image.width + x) * 4; + buffer2[to] = image.data[from2]; + buffer2[to + 1] = image.data[from2 + 1]; + buffer2[to + 2] = image.data[from2 + 2]; + buffer2[to + 3] = image.data[from2 + 3]; + } else { + buffer2[to] = 0; + buffer2[to + 1] = 0; + buffer2[to + 2] = 0; + buffer2[to + 3] = 0; + } + } + } + return { data: Buffer.from(buffer2), width: size.width, height: size.height }; +} +var cryptoBrowserifyExports = requireCryptoBrowserify(); +const crypto = /* @__PURE__ */ getDefaultExportFromCjs(cryptoBrowserifyExports); +function createGuid() { + return crypto.randomBytes(16).toString("hex"); +} +function calculateSha1(buffer2) { + const hash2 = crypto.createHash("sha1"); + hash2.update(buffer2); + return hash2.digest("hex"); +} +function encodeBase128(value) { + const bytes = []; + do { + let byte = value & 127; + value >>>= 7; + if (bytes.length > 0) + byte |= 128; + bytes.push(byte); + } while (value > 0); + return Buffer.from(bytes.reverse()); +} +class DER { + static encodeSequence(data2) { + return this._encode(48, Buffer.concat(data2)); + } + static encodeInteger(data2) { + assert(data2 >= -128 && data2 <= 127); + return this._encode(2, Buffer.from([data2])); + } + static encodeObjectIdentifier(oid) { + const parts = oid.split(".").map((v) => Number(v)); + const output = [encodeBase128(40 * parts[0] + parts[1])]; + for (let i = 2; i < parts.length; i++) + output.push(encodeBase128(parts[i])); + return this._encode(6, Buffer.concat(output)); + } + static encodeNull() { + return Buffer.from([5, 0]); + } + static encodeSet(data2) { + assert(data2.length === 1, "Only one item in the set is supported. We'd need to sort the data to support more."); + return this._encode(49, Buffer.concat(data2)); + } + static encodeExplicitContextDependent(tag, data2) { + return this._encode(160 + tag, data2); + } + static encodePrintableString(data2) { + return this._encode(19, Buffer.from(data2)); + } + static encodeBitString(data2) { + const unusedBits = 0; + const content = Buffer.concat([Buffer.from([unusedBits]), data2]); + return this._encode(3, content); + } + static encodeDate(date) { + const year = date.getUTCFullYear(); + const isGeneralizedTime = year >= 2050; + const parts = [ + isGeneralizedTime ? year.toString() : year.toString().slice(-2), + (date.getUTCMonth() + 1).toString().padStart(2, "0"), + date.getUTCDate().toString().padStart(2, "0"), + date.getUTCHours().toString().padStart(2, "0"), + date.getUTCMinutes().toString().padStart(2, "0"), + date.getUTCSeconds().toString().padStart(2, "0") + ]; + const encodedDate = parts.join("") + "Z"; + const tag = isGeneralizedTime ? 24 : 23; + return this._encode(tag, Buffer.from(encodedDate)); + } + static _encode(tag, data2) { + const lengthBytes = this._encodeLength(data2.length); + return Buffer.concat([Buffer.from([tag]), lengthBytes, data2]); + } + static _encodeLength(length) { + if (length < 128) { + return Buffer.from([length]); + } else { + const lengthBytes = []; + while (length > 0) { + lengthBytes.unshift(length & 255); + length >>= 8; + } + return Buffer.from([128 | lengthBytes.length, ...lengthBytes]); + } + } +} +function generateSelfSignedCertificate() { + const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }); + const publicKeyDer = publicKey.export({ type: "pkcs1", format: "der" }); + const oneYearInMilliseconds = 365 * 24 * 60 * 60 * 1e3; + const notBefore = new Date((/* @__PURE__ */ new Date()).getTime() - oneYearInMilliseconds); + const notAfter = new Date((/* @__PURE__ */ new Date()).getTime() + oneYearInMilliseconds); + const tbsCertificate = DER.encodeSequence([ + DER.encodeExplicitContextDependent(0, DER.encodeInteger(1)), + // version + DER.encodeInteger(1), + // serialNumber + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + // signature + DER.encodeSequence([ + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.3"), + // commonName X.520 DN component + DER.encodePrintableString("localhost") + ]) + ]), + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.10"), + // organizationName X.520 DN component + DER.encodePrintableString("Playwright Client Certificate Support") + ]) + ]) + ]), + // issuer + DER.encodeSequence([ + DER.encodeDate(notBefore), + // notBefore + DER.encodeDate(notAfter) + // notAfter + ]), + // validity + DER.encodeSequence([ + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.3"), + // commonName X.520 DN component + DER.encodePrintableString("localhost") + ]) + ]), + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.10"), + // organizationName X.520 DN component + DER.encodePrintableString("Playwright Client Certificate Support") + ]) + ]) + ]), + // subject + DER.encodeSequence([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.1"), + // rsaEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(publicKeyDer) + ]) + // SubjectPublicKeyInfo + ]); + const signature2 = crypto.sign("sha256", tbsCertificate, privateKey); + const certificate2 = DER.encodeSequence([ + tbsCertificate, + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(signature2) + ]); + const certPem = [ + "-----BEGIN CERTIFICATE-----", + // Split the base64 string into lines of 64 characters + certificate2.toString("base64").match(/.{1,64}/g).join("\n"), + "-----END CERTIFICATE-----" + ].join("\n"); + return { + cert: certPem, + key: privateKey.export({ type: "pkcs1", format: "pem" }) + }; +} +function getFromENV(name) { + let value = define_process_env_default[name]; + value = value === void 0 ? define_process_env_default[`npm_config_${name.toLowerCase()}`] : value; + value = value === void 0 ? define_process_env_default[`npm_package_config_${name.toLowerCase()}`] : value; + return value; +} +function getAsBooleanFromENV(name, defaultValue) { + const value = getFromENV(name); + if (value === "false" || value === "0") + return false; + if (value) + return true; + return false; +} +function getPackageManager() { + const env = define_process_env_default.npm_config_user_agent || ""; + if (env.includes("yarn")) + return "yarn"; + if (env.includes("pnpm")) + return "pnpm"; + return "npm"; +} +function getPackageManagerExecCommand() { + const packageManager = getPackageManager(); + if (packageManager === "yarn") + return "yarn"; + if (packageManager === "pnpm") + return "pnpm exec"; + return "npx"; +} +const _debugMode = getFromENV("PWDEBUG") || ""; +function debugMode() { + if (_debugMode === "console") + return "console"; + if (_debugMode === "0" || _debugMode === "false") + return ""; + return _debugMode ? "inspector" : ""; +} +let _isUnderTest = getAsBooleanFromENV("PWTEST_UNDER_TEST"); +function setUnderTest() { + _isUnderTest = true; +} +function isUnderTest() { + return _isUnderTest; +} +class EventsHelper { + static addEventListener(emitter, eventName, handler) { + emitter.on(eventName, handler); + return { emitter, eventName, handler }; + } + static removeEventListeners(listeners) { + for (const listener of listeners) + listener.emitter.removeListener(listener.eventName, listener.handler); + listeners.splice(0, listeners.length); + } +} +const eventsHelper = EventsHelper; +function serializeExpectedTextValues(items, options2 = {}) { + return items.map((i) => ({ + string: isString(i) ? i : void 0, + regexSource: isRegExp$4(i) ? i.source : void 0, + regexFlags: isRegExp$4(i) ? i.flags : void 0, + matchSubstring: options2.matchSubstring, + ignoreCase: options2.ignoreCase, + normalizeWhiteSpace: options2.normalizeWhiteSpace + })); +} +var streamHttp = {}; +var request = { exports: {} }; +var capability = {}; +var hasRequiredCapability; +function requireCapability() { + if (hasRequiredCapability) return capability; + hasRequiredCapability = 1; + (function(exports) { + exports.fetch = isFunction(commonjsGlobal.fetch) && isFunction(commonjsGlobal.ReadableStream); + exports.writableStream = isFunction(commonjsGlobal.WritableStream); + exports.abortController = isFunction(commonjsGlobal.AbortController); + var xhr; + function getXHR() { + if (xhr !== void 0) return xhr; + if (commonjsGlobal.XMLHttpRequest) { + xhr = new commonjsGlobal.XMLHttpRequest(); + try { + xhr.open("GET", commonjsGlobal.XDomainRequest ? "/" : "https://example.com"); + } catch (e) { + xhr = null; + } + } else { + xhr = null; + } + return xhr; + } + function checkTypeSupport(type2) { + var xhr2 = getXHR(); + if (!xhr2) return false; + try { + xhr2.responseType = type2; + return xhr2.responseType === type2; + } catch (e) { + } + return false; + } + exports.arraybuffer = exports.fetch || checkTypeSupport("arraybuffer"); + exports.msstream = !exports.fetch && checkTypeSupport("ms-stream"); + exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport("moz-chunked-arraybuffer"); + exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false); + function isFunction(value) { + return typeof value === "function"; + } + xhr = null; + })(capability); + return capability; +} +var response = {}; +var readableBrowser = { exports: {} }; +var streamBrowser; +var hasRequiredStreamBrowser; +function requireStreamBrowser() { + if (hasRequiredStreamBrowser) return streamBrowser; + hasRequiredStreamBrowser = 1; + streamBrowser = requireEvents().EventEmitter; + return streamBrowser; +} +var buffer_list; +var hasRequiredBuffer_list; +function requireBuffer_list() { + if (hasRequiredBuffer_list) return buffer_list; + hasRequiredBuffer_list = 1; + function ownKeys2(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source2 = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys2(Object(source2), true).forEach(function(key2) { + _defineProperty2(target, key2, source2[key2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source2)) : ownKeys2(Object(source2)).forEach(function(key2) { + Object.defineProperty(target, key2, Object.getOwnPropertyDescriptor(source2, key2)); + }); + } + return target; + } + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey2(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return typeof key2 === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return String(input); + } + var _require = requireBuffer$2(), Buffer2 = _require.Buffer; + var _require2 = require$$3, inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src2, target, offset2) { + Buffer2.prototype.copy.call(src2, target, offset2); + } + buffer_list = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join2(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer2.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options2) { + return inspect(this, _objectSpread(_objectSpread({}, options2), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + return buffer_list; +} +var destroy_1; +var hasRequiredDestroy; +function requireDestroy() { + if (hasRequiredDestroy) return destroy_1; + hasRequiredDestroy = 1; + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err2); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) return; + if (self2._readableState && !self2._readableState.emitClose) return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream2, err) { + var rState = stream2._readableState; + var wState = stream2._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream2.destroy(err); + else stream2.emit("error", err); + } + destroy_1 = { + destroy, + undestroy, + errorOrDestroy + }; + return destroy_1; +} +var errorsBrowser = {}; +var hasRequiredErrorsBrowser; +function requireErrorsBrowser() { + if (hasRequiredErrorsBrowser) return errorsBrowser; + hasRequiredErrorsBrowser = 1; + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; + } + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /* @__PURE__ */ function(_Base) { + _inheritsLoose(NodeError2, _Base); + function NodeError2(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + return NodeError2; + }(Base); + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function(i) { + return String(i); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } + function startsWith(str, search, pos) { + return str.substr(0, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + var determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + var msg; + if (endsWith(name, " argument")) { + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } else { + var type2 = includes(name, ".") ? "property" : "argument"; + msg = 'The "'.concat(name, '" ').concat(type2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { + return "The " + name + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name) { + return "Cannot call " + name + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + errorsBrowser.codes = codes; + return errorsBrowser; +} +var state; +var hasRequiredState; +function requireState() { + if (hasRequiredState) return state; + hasRequiredState = 1; + var ERR_INVALID_OPT_VALUE = requireErrorsBrowser().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options2, isDuplex, duplexKey) { + return options2.highWaterMark != null ? options2.highWaterMark : isDuplex ? options2[duplexKey] : null; + } + function getHighWaterMark(state2, options2, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options2, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + return state2.objectMode ? 16 : 16 * 1024; + } + state = { + getHighWaterMark + }; + return state; +} +var _stream_writable; +var hasRequired_stream_writable; +function require_stream_writable() { + if (hasRequired_stream_writable) return _stream_writable; + hasRequired_stream_writable = 1; + _stream_writable = Writable; + function CorkedRequest(state2) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state2); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: requireBrowser$d() + }; + var Stream2 = requireStreamBrowser(); + var Buffer2 = requireBuffer$2().Buffer; + var OurUint8Array = (typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = requireDestroy(); + var _require = requireState(), getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrorsBrowser().codes, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + requireInherits_browser$1()(Writable, Stream2); + function nop() { + } + function WritableState(options2, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options2 = options2 || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof Duplex; + this.objectMode = !!options2.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options2.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options2, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options2.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options2.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream2, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options2.emitClose !== false; + this.autoDestroy = !!options2.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current2 = this.bufferedRequest; + var out = []; + while (current2) { + out.push(current2); + current2 = current2.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable(options2) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options2); + this._writableState = new WritableState(options2, this, isDuplex); + this.writable = true; + if (options2) { + if (typeof options2.write === "function") this._write = options2.write; + if (typeof options2.writev === "function") this._writev = options2.writev; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + if (typeof options2.final === "function") this._final = options2.final; + } + Stream2.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream2, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + } + function validChunk(stream2, state2, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream2, er); + process.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding2, cb) { + var state2 = this._writableState; + var ret = false; + var isBuf = !state2.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + if (isBuf) encoding2 = "buffer"; + else if (!encoding2) encoding2 = state2.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state2.ending) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state2, chunk, cb)) { + state2.pendingcb++; + ret = writeOrBuffer(this, state2, isBuf, chunk, encoding2, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state2 = this._writableState; + if (state2.corked) { + state2.corked--; + if (!state2.writing && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) clearBuffer(this, state2); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding2) { + if (typeof encoding2 === "string") encoding2 = encoding2.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding2 + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding2); + this._writableState.defaultEncoding = encoding2; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state2, chunk, encoding2) { + if (!state2.objectMode && state2.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding2); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream2, state2, isBuf, chunk, encoding2, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state2, chunk, encoding2); + if (chunk !== newChunk) { + isBuf = true; + encoding2 = "buffer"; + chunk = newChunk; + } + } + var len = state2.objectMode ? 1 : chunk.length; + state2.length += len; + var ret = state2.length < state2.highWaterMark; + if (!ret) state2.needDrain = true; + if (state2.writing || state2.corked) { + var last = state2.lastBufferedRequest; + state2.lastBufferedRequest = { + chunk, + encoding: encoding2, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state2.lastBufferedRequest; + } else { + state2.bufferedRequest = state2.lastBufferedRequest; + } + state2.bufferedRequestCount += 1; + } else { + doWrite(stream2, state2, false, len, chunk, encoding2, cb); + } + return ret; + } + function doWrite(stream2, state2, writev2, len, chunk, encoding2, cb) { + state2.writelen = len; + state2.writecb = cb; + state2.writing = true; + state2.sync = true; + if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev2) stream2._writev(chunk, state2.onwrite); + else stream2._write(chunk, encoding2, state2.onwrite); + state2.sync = false; + } + function onwriteError(stream2, state2, sync, er, cb) { + --state2.pendingcb; + if (sync) { + process.nextTick(cb, er); + process.nextTick(finishMaybe, stream2, state2); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + } else { + cb(er); + stream2._writableState.errorEmitted = true; + errorOrDestroy(stream2, er); + finishMaybe(stream2, state2); + } + } + function onwriteStateUpdate(state2) { + state2.writing = false; + state2.writecb = null; + state2.length -= state2.writelen; + state2.writelen = 0; + } + function onwrite(stream2, er) { + var state2 = stream2._writableState; + var sync = state2.sync; + var cb = state2.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state2); + if (er) onwriteError(stream2, state2, sync, er, cb); + else { + var finished = needFinish(state2) || stream2.destroyed; + if (!finished && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) { + clearBuffer(stream2, state2); + } + if (sync) { + process.nextTick(afterWrite, stream2, state2, finished, cb); + } else { + afterWrite(stream2, state2, finished, cb); + } + } + } + function afterWrite(stream2, state2, finished, cb) { + if (!finished) onwriteDrain(stream2, state2); + state2.pendingcb--; + cb(); + finishMaybe(stream2, state2); + } + function onwriteDrain(stream2, state2) { + if (state2.length === 0 && state2.needDrain) { + state2.needDrain = false; + stream2.emit("drain"); + } + } + function clearBuffer(stream2, state2) { + state2.bufferProcessing = true; + var entry = state2.bufferedRequest; + if (stream2._writev && entry && entry.next) { + var l = state2.bufferedRequestCount; + var buffer2 = new Array(l); + var holder = state2.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer2[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer2.allBuffers = allBuffers; + doWrite(stream2, state2, true, state2.length, buffer2, "", holder.finish); + state2.pendingcb++; + state2.lastBufferedRequest = null; + if (holder.next) { + state2.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state2.corkedRequestsFree = new CorkedRequest(state2); + } + state2.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding2 = entry.encoding; + var cb = entry.callback; + var len = state2.objectMode ? 1 : chunk.length; + doWrite(stream2, state2, false, len, chunk, encoding2, cb); + entry = entry.next; + state2.bufferedRequestCount--; + if (state2.writing) { + break; + } + } + if (entry === null) state2.lastBufferedRequest = null; + } + state2.bufferedRequest = entry; + state2.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding2, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding2, cb) { + var state2 = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding2 = null; + } else if (typeof encoding2 === "function") { + cb = encoding2; + encoding2 = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding2); + if (state2.corked) { + state2.corked = 1; + this.uncork(); + } + if (!state2.ending) endWritable(this, state2, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function needFinish(state2) { + return state2.ending && state2.length === 0 && state2.bufferedRequest === null && !state2.finished && !state2.writing; + } + function callFinal(stream2, state2) { + stream2._final(function(err) { + state2.pendingcb--; + if (err) { + errorOrDestroy(stream2, err); + } + state2.prefinished = true; + stream2.emit("prefinish"); + finishMaybe(stream2, state2); + }); + } + function prefinish(stream2, state2) { + if (!state2.prefinished && !state2.finalCalled) { + if (typeof stream2._final === "function" && !state2.destroyed) { + state2.pendingcb++; + state2.finalCalled = true; + process.nextTick(callFinal, stream2, state2); + } else { + state2.prefinished = true; + stream2.emit("prefinish"); + } + } + } + function finishMaybe(stream2, state2) { + var need = needFinish(state2); + if (need) { + prefinish(stream2, state2); + if (state2.pendingcb === 0) { + state2.finished = true; + stream2.emit("finish"); + if (state2.autoDestroy) { + var rState = stream2._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream2.destroy(); + } + } + } + } + return need; + } + function endWritable(stream2, state2, cb) { + state2.ending = true; + finishMaybe(stream2, state2); + if (cb) { + if (state2.finished) process.nextTick(cb); + else stream2.once("finish", cb); + } + state2.ended = true; + stream2.writable = false; + } + function onCorkedFinish(corkReq, state2, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state2.pendingcb--; + cb(err); + entry = entry.next; + } + state2.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set2(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + return _stream_writable; +} +var _stream_duplex; +var hasRequired_stream_duplex; +function require_stream_duplex() { + if (hasRequired_stream_duplex) return _stream_duplex; + hasRequired_stream_duplex = 1; + var objectKeys2 = Object.keys || function(obj) { + var keys2 = []; + for (var key2 in obj) keys2.push(key2); + return keys2; + }; + _stream_duplex = Duplex; + var Readable = require_stream_readable(); + var Writable = require_stream_writable(); + requireInherits_browser$1()(Duplex, Readable); + { + var keys = objectKeys2(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options2) { + if (!(this instanceof Duplex)) return new Duplex(options2); + Readable.call(this, options2); + Writable.call(this, options2); + this.allowHalfOpen = true; + if (options2) { + if (options2.readable === false) this.readable = false; + if (options2.writable === false) this.writable = false; + if (options2.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) return; + process.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set2(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + return _stream_duplex; +} +var endOfStream; +var hasRequiredEndOfStream; +function requireEndOfStream() { + if (hasRequiredEndOfStream) return endOfStream; + hasRequiredEndOfStream = 1; + var ERR_STREAM_PREMATURE_CLOSE = requireErrorsBrowser().codes.ERR_STREAM_PREMATURE_CLOSE; + function once2(callback) { + var called = false; + return function() { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop2() { + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function eos(stream2, opts, callback) { + if (typeof opts === "function") return eos(stream2, null, opts); + if (!opts) opts = {}; + callback = once2(callback || noop2); + var readable2 = opts.readable || opts.readable !== false && stream2.readable; + var writable2 = opts.writable || opts.writable !== false && stream2.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream2.writable) onfinish(); + }; + var writableEnded = stream2._writableState && stream2._writableState.finished; + var onfinish = function onfinish2() { + writable2 = false; + writableEnded = true; + if (!readable2) callback.call(stream2); + }; + var readableEnded = stream2._readableState && stream2._readableState.endEmitted; + var onend = function onend2() { + readable2 = false; + readableEnded = true; + if (!writable2) callback.call(stream2); + }; + var onerror = function onerror2(err) { + callback.call(stream2, err); + }; + var onclose = function onclose2() { + var err; + if (readable2 && !readableEnded) { + if (!stream2._readableState || !stream2._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + if (writable2 && !writableEnded) { + if (!stream2._writableState || !stream2._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream2, err); + } + }; + var onrequest = function onrequest2() { + stream2.req.on("finish", onfinish); + }; + if (isRequest(stream2)) { + stream2.on("complete", onfinish); + stream2.on("abort", onclose); + if (stream2.req) onrequest(); + else stream2.on("request", onrequest); + } else if (writable2 && !stream2._writableState) { + stream2.on("end", onlegacyfinish); + stream2.on("close", onlegacyfinish); + } + stream2.on("end", onend); + stream2.on("finish", onfinish); + if (opts.error !== false) stream2.on("error", onerror); + stream2.on("close", onclose); + return function() { + stream2.removeListener("complete", onfinish); + stream2.removeListener("abort", onclose); + stream2.removeListener("request", onrequest); + if (stream2.req) stream2.req.removeListener("finish", onfinish); + stream2.removeListener("end", onlegacyfinish); + stream2.removeListener("close", onlegacyfinish); + stream2.removeListener("finish", onfinish); + stream2.removeListener("end", onend); + stream2.removeListener("error", onerror); + stream2.removeListener("close", onclose); + }; + } + endOfStream = eos; + return endOfStream; +} +var async_iterator; +var hasRequiredAsync_iterator; +function requireAsync_iterator() { + if (hasRequiredAsync_iterator) return async_iterator; + hasRequiredAsync_iterator = 1; + var _Object$setPrototypeO; + function _defineProperty2(obj, key2, value) { + key2 = _toPropertyKey2(key2); + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; + } + return obj; + } + function _toPropertyKey2(arg) { + var key2 = _toPrimitive2(arg, "string"); + return typeof key2 === "symbol" ? key2 : String(key2); + } + function _toPrimitive2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = requireEndOfStream(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data2 = iter[kStream].read(); + if (data2 !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data2, false)); + } + } + } + function onReadable(iter) { + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error2 = this[kError]; + if (error2 !== null) { + return Promise.reject(error2); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + process.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data2 = this[kStream].read(); + if (data2 !== null) { + return Promise.resolve(createIterResult(data2, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty2(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty2(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream2) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty2(_Object$create, kStream, { + value: stream2, + writable: true + }), _defineProperty2(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty2(_Object$create, kEnded, { + value: stream2._readableState.endEmitted, + writable: true + }), _defineProperty2(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data2 = iterator[kStream].read(); + if (data2) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data2, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream2, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator[kLastReject]; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(void 0, true)); + } + iterator[kEnded] = true; + }); + stream2.on("readable", onReadable.bind(null, iterator)); + return iterator; + }; + async_iterator = createReadableStreamAsyncIterator; + return async_iterator; +} +var fromBrowser; +var hasRequiredFromBrowser; +function requireFromBrowser() { + if (hasRequiredFromBrowser) return fromBrowser; + hasRequiredFromBrowser = 1; + fromBrowser = function() { + throw new Error("Readable.from is not available in the browser"); + }; + return fromBrowser; +} +var _stream_readable; +var hasRequired_stream_readable; +function require_stream_readable() { + if (hasRequired_stream_readable) return _stream_readable; + hasRequired_stream_readable = 1; + _stream_readable = Readable; + var Duplex; + Readable.ReadableState = ReadableState; + requireEvents().EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type2) { + return emitter.listeners(type2).length; + }; + var Stream2 = requireStreamBrowser(); + var Buffer2 = requireBuffer$2().Buffer; + var OurUint8Array = (typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = require$$3; + var debug2; + if (debugUtil && debugUtil.debuglog) { + debug2 = debugUtil.debuglog("stream"); + } else { + debug2 = function debug3() { + }; + } + var BufferList = requireBuffer_list(); + var destroyImpl = requireDestroy(); + var _require = requireState(), getHighWaterMark = _require.getHighWaterMark; + var _require$codes = requireErrorsBrowser().codes, ERR_INVALID_ARG_TYPE2 = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from2; + requireInherits_browser$1()(Readable, Stream2); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options2, stream2, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options2 = options2 || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream2 instanceof Duplex; + this.objectMode = !!options2.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options2.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options2, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options2.emitClose !== false; + this.autoDestroy = !!options2.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options2.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options2.encoding) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + this.decoder = new StringDecoder(options2.encoding); + this.encoding = options2.encoding; + } + } + function Readable(options2) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable)) return new Readable(options2); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options2, this, isDuplex); + this.readable = true; + if (options2) { + if (typeof options2.read === "function") this._read = options2.read; + if (typeof options2.destroy === "function") this._destroy = options2.destroy; + } + Stream2.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set2(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype.push = function(chunk, encoding2) { + var state2 = this._readableState; + var skipChunkCheck; + if (!state2.objectMode) { + if (typeof chunk === "string") { + encoding2 = encoding2 || state2.defaultEncoding; + if (encoding2 !== state2.encoding) { + chunk = Buffer2.from(chunk, encoding2); + encoding2 = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding2, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream2, chunk, encoding2, addToFront, skipChunkCheck) { + debug2("readableAddChunk", chunk); + var state2 = stream2._readableState; + if (chunk === null) { + state2.reading = false; + onEofChunk(stream2, state2); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state2, chunk); + if (er) { + errorOrDestroy(stream2, er); + } else if (state2.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state2.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state2.endEmitted) errorOrDestroy(stream2, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream2, state2, chunk, true); + } else if (state2.ended) { + errorOrDestroy(stream2, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state2.destroyed) { + return false; + } else { + state2.reading = false; + if (state2.decoder && !encoding2) { + chunk = state2.decoder.write(chunk); + if (state2.objectMode || chunk.length !== 0) addChunk(stream2, state2, chunk, false); + else maybeReadMore(stream2, state2); + } else { + addChunk(stream2, state2, chunk, false); + } + } + } else if (!addToFront) { + state2.reading = false; + maybeReadMore(stream2, state2); + } + } + return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0); + } + function addChunk(stream2, state2, chunk, addToFront) { + if (state2.flowing && state2.length === 0 && !state2.sync) { + state2.awaitDrain = 0; + stream2.emit("data", chunk); + } else { + state2.length += state2.objectMode ? 1 : chunk.length; + if (addToFront) state2.buffer.unshift(chunk); + else state2.buffer.push(chunk); + if (state2.needReadable) emitReadable(stream2); + } + maybeReadMore(stream2, state2); + } + function chunkInvalid(state2, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = requireString_decoder().StringDecoder; + var decoder2 = new StringDecoder(enc); + this._readableState.decoder = decoder2; + this._readableState.encoding = this._readableState.decoder.encoding; + var p = this._readableState.buffer.head; + var content = ""; + while (p !== null) { + content += decoder2.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== "") this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state2) { + if (n <= 0 || state2.length === 0 && state2.ended) return 0; + if (state2.objectMode) return 1; + if (n !== n) { + if (state2.flowing && state2.length) return state2.buffer.head.data.length; + else return state2.length; + } + if (n > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n); + if (n <= state2.length) return n; + if (!state2.ended) { + state2.needReadable = true; + return 0; + } + return state2.length; + } + Readable.prototype.read = function(n) { + debug2("read", n); + n = parseInt(n, 10); + var state2 = this._readableState; + var nOrig = n; + if (n !== 0) state2.emittedReadable = false; + if (n === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) { + debug2("read: emitReadable", state2.length, state2.ended); + if (state2.length === 0 && state2.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state2); + if (n === 0 && state2.ended) { + if (state2.length === 0) endReadable(this); + return null; + } + var doRead = state2.needReadable; + debug2("need readable", doRead); + if (state2.length === 0 || state2.length - n < state2.highWaterMark) { + doRead = true; + debug2("length less than watermark", doRead); + } + if (state2.ended || state2.reading) { + doRead = false; + debug2("reading or ended", doRead); + } else if (doRead) { + debug2("do read"); + state2.reading = true; + state2.sync = true; + if (state2.length === 0) state2.needReadable = true; + this._read(state2.highWaterMark); + state2.sync = false; + if (!state2.reading) n = howMuchToRead(nOrig, state2); + } + var ret; + if (n > 0) ret = fromList(n, state2); + else ret = null; + if (ret === null) { + state2.needReadable = state2.length <= state2.highWaterMark; + n = 0; + } else { + state2.length -= n; + state2.awaitDrain = 0; + } + if (state2.length === 0) { + if (!state2.ended) state2.needReadable = true; + if (nOrig !== n && state2.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream2, state2) { + debug2("onEofChunk"); + if (state2.ended) return; + if (state2.decoder) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) { + state2.buffer.push(chunk); + state2.length += state2.objectMode ? 1 : chunk.length; + } + } + state2.ended = true; + if (state2.sync) { + emitReadable(stream2); + } else { + state2.needReadable = false; + if (!state2.emittedReadable) { + state2.emittedReadable = true; + emitReadable_(stream2); + } + } + } + function emitReadable(stream2) { + var state2 = stream2._readableState; + debug2("emitReadable", state2.needReadable, state2.emittedReadable); + state2.needReadable = false; + if (!state2.emittedReadable) { + debug2("emitReadable", state2.flowing); + state2.emittedReadable = true; + process.nextTick(emitReadable_, stream2); + } + } + function emitReadable_(stream2) { + var state2 = stream2._readableState; + debug2("emitReadable_", state2.destroyed, state2.length, state2.ended); + if (!state2.destroyed && (state2.length || state2.ended)) { + stream2.emit("readable"); + state2.emittedReadable = false; + } + state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark; + flow(stream2); + } + function maybeReadMore(stream2, state2) { + if (!state2.readingMore) { + state2.readingMore = true; + process.nextTick(maybeReadMore_, stream2, state2); + } + } + function maybeReadMore_(stream2, state2) { + while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) { + var len = state2.length; + debug2("maybeReadMore read 0"); + stream2.read(0); + if (len === state2.length) + break; + } + state2.readingMore = false; + } + Readable.prototype._read = function(n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src2 = this; + var state2 = this._readableState; + switch (state2.pipesCount) { + case 0: + state2.pipes = dest; + break; + case 1: + state2.pipes = [state2.pipes, dest]; + break; + default: + state2.pipes.push(dest); + break; + } + state2.pipesCount += 1; + debug2("pipe count=%d opts=%j", state2.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state2.endEmitted) process.nextTick(endFn); + else src2.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable2, unpipeInfo) { + debug2("onunpipe"); + if (readable2 === src2) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug2("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src2); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug2("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src2.removeListener("end", onend); + src2.removeListener("end", unpipe); + src2.removeListener("data", ondata); + cleanedUp = true; + if (state2.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src2.on("data", ondata); + function ondata(chunk) { + debug2("ondata"); + var ret = dest.write(chunk); + debug2("dest.write", ret); + if (ret === false) { + if ((state2.pipesCount === 1 && state2.pipes === dest || state2.pipesCount > 1 && indexOf(state2.pipes, dest) !== -1) && !cleanedUp) { + debug2("false write response, pause", state2.awaitDrain); + state2.awaitDrain++; + } + src2.pause(); + } + } + function onerror(er) { + debug2("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug2("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug2("unpipe"); + src2.unpipe(dest); + } + dest.emit("pipe", src2); + if (!state2.flowing) { + debug2("pipe resume"); + src2.resume(); + } + return dest; + }; + function pipeOnDrain(src2) { + return function pipeOnDrainFunctionResult() { + var state2 = src2._readableState; + debug2("pipeOnDrain", state2.awaitDrain); + if (state2.awaitDrain) state2.awaitDrain--; + if (state2.awaitDrain === 0 && EElistenerCount(src2, "data")) { + state2.flowing = true; + flow(src2); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state2 = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state2.pipesCount === 0) return this; + if (state2.pipesCount === 1) { + if (dest && dest !== state2.pipes) return this; + if (!dest) dest = state2.pipes; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state2.pipes; + var len = state2.pipesCount; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index2 = indexOf(state2.pipes, dest); + if (index2 === -1) return this; + state2.pipes.splice(index2, 1); + state2.pipesCount -= 1; + if (state2.pipesCount === 1) state2.pipes = state2.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream2.prototype.on.call(this, ev, fn); + var state2 = this._readableState; + if (ev === "data") { + state2.readableListening = this.listenerCount("readable") > 0; + if (state2.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state2.endEmitted && !state2.readableListening) { + state2.readableListening = state2.needReadable = true; + state2.flowing = false; + state2.emittedReadable = false; + debug2("on readable", state2.length, state2.reading); + if (state2.length) { + emitReadable(this); + } else if (!state2.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + var res = Stream2.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + process.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.removeAllListeners = function(ev) { + var res = Stream2.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state2 = self2._readableState; + state2.readableListening = self2.listenerCount("readable") > 0; + if (state2.resumeScheduled && !state2.paused) { + state2.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug2("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + var state2 = this._readableState; + if (!state2.flowing) { + debug2("resume"); + state2.flowing = !state2.readableListening; + resume(this, state2); + } + state2.paused = false; + return this; + }; + function resume(stream2, state2) { + if (!state2.resumeScheduled) { + state2.resumeScheduled = true; + process.nextTick(resume_, stream2, state2); + } + } + function resume_(stream2, state2) { + debug2("resume", state2.reading); + if (!state2.reading) { + stream2.read(0); + } + state2.resumeScheduled = false; + stream2.emit("resume"); + flow(stream2); + if (state2.flowing && !state2.reading) stream2.read(0); + } + Readable.prototype.pause = function() { + debug2("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug2("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream2) { + var state2 = stream2._readableState; + debug2("flow", state2.flowing); + while (state2.flowing && stream2.read() !== null) ; + } + Readable.prototype.wrap = function(stream2) { + var _this = this; + var state2 = this._readableState; + var paused = false; + stream2.on("end", function() { + debug2("wrapped end"); + if (state2.decoder && !state2.ended) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream2.on("data", function(chunk) { + debug2("wrapped data"); + if (state2.decoder) chunk = state2.decoder.write(chunk); + if (state2.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state2.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream2.pause(); + } + }); + for (var i in stream2) { + if (this[i] === void 0 && typeof stream2[i] === "function") { + this[i] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream2[method].apply(stream2, arguments); + }; + }(i); + } + } + for (var n = 0; n < kProxyEvents.length; n++) { + stream2.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + this._read = function(n2) { + debug2("wrapped _read", n2); + if (paused) { + paused = false; + stream2.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = requireAsync_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.flowing; + }, + set: function set2(state2) { + if (this._readableState) { + this._readableState.flowing = state2; + } + } + }); + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.length; + } + }); + function fromList(n, state2) { + if (state2.length === 0) return null; + var ret; + if (state2.objectMode) ret = state2.buffer.shift(); + else if (!n || n >= state2.length) { + if (state2.decoder) ret = state2.buffer.join(""); + else if (state2.buffer.length === 1) ret = state2.buffer.first(); + else ret = state2.buffer.concat(state2.length); + state2.buffer.clear(); + } else { + ret = state2.buffer.consume(n, state2.decoder); + } + return ret; + } + function endReadable(stream2) { + var state2 = stream2._readableState; + debug2("endReadable", state2.endEmitted); + if (!state2.endEmitted) { + state2.ended = true; + process.nextTick(endReadableNT, state2, stream2); + } + } + function endReadableNT(state2, stream2) { + debug2("endReadableNT", state2.endEmitted, state2.length); + if (!state2.endEmitted && state2.length === 0) { + state2.endEmitted = true; + stream2.readable = false; + stream2.emit("end"); + if (state2.autoDestroy) { + var wState = stream2._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream2.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable.from = function(iterable, opts) { + if (from2 === void 0) { + from2 = requireFromBrowser(); + } + return from2(Readable, iterable, opts); + }; + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + return _stream_readable; +} +var _stream_transform; +var hasRequired_stream_transform; +function require_stream_transform() { + if (hasRequired_stream_transform) return _stream_transform; + hasRequired_stream_transform = 1; + _stream_transform = Transform; + var _require$codes = requireErrorsBrowser().codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + requireInherits_browser$1()(Transform, Duplex); + function afterTransform(er, data2) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data2 != null) + this.push(data2); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options2) { + if (!(this instanceof Transform)) return new Transform(options2); + Duplex.call(this, options2); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options2) { + if (typeof options2.transform === "function") this._transform = options2.transform; + if (typeof options2.flush === "function") this._flush = options2.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er, data2) { + done(_this, er, data2); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding2) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding2); + }; + Transform.prototype._transform = function(chunk, encoding2, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding2, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding2; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream2, er, data2) { + if (er) return stream2.emit("error", er); + if (data2 != null) + stream2.push(data2); + if (stream2._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream2._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream2.push(null); + } + return _stream_transform; +} +var _stream_passthrough; +var hasRequired_stream_passthrough; +function require_stream_passthrough() { + if (hasRequired_stream_passthrough) return _stream_passthrough; + hasRequired_stream_passthrough = 1; + _stream_passthrough = PassThrough; + var Transform = require_stream_transform(); + requireInherits_browser$1()(PassThrough, Transform); + function PassThrough(options2) { + if (!(this instanceof PassThrough)) return new PassThrough(options2); + Transform.call(this, options2); + } + PassThrough.prototype._transform = function(chunk, encoding2, cb) { + cb(null, chunk); + }; + return _stream_passthrough; +} +var pipeline_1; +var hasRequiredPipeline; +function requirePipeline() { + if (hasRequiredPipeline) return pipeline_1; + hasRequiredPipeline = 1; + var eos; + function once2(callback) { + var called = false; + return function() { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = requireErrorsBrowser().codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop2(err) { + if (err) throw err; + } + function isRequest(stream2) { + return stream2.setHeader && typeof stream2.abort === "function"; + } + function destroyer(stream2, reading, writing, callback) { + callback = once2(callback); + var closed = false; + stream2.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = requireEndOfStream(); + eos(stream2, { + readable: reading, + writable: writing + }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isRequest(stream2)) return stream2.abort(); + if (typeof stream2.destroy === "function") return stream2.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe(from2, to) { + return from2.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop2; + if (typeof streams[streams.length - 1] !== "function") return noop2; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error2; + var destroys = streams.map(function(stream2, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream2, reading, writing, function(err) { + if (!error2) error2 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error2); + }); + }); + return streams.reduce(pipe); + } + pipeline_1 = pipeline; + return pipeline_1; +} +var hasRequiredReadableBrowser; +function requireReadableBrowser() { + if (hasRequiredReadableBrowser) return readableBrowser.exports; + hasRequiredReadableBrowser = 1; + (function(module, exports) { + exports = module.exports = require_stream_readable(); + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = require_stream_writable(); + exports.Duplex = require_stream_duplex(); + exports.Transform = require_stream_transform(); + exports.PassThrough = require_stream_passthrough(); + exports.finished = requireEndOfStream(); + exports.pipeline = requirePipeline(); + })(readableBrowser, readableBrowser.exports); + return readableBrowser.exports; +} +var hasRequiredResponse; +function requireResponse() { + if (hasRequiredResponse) return response; + hasRequiredResponse = 1; + var capability2 = requireCapability(); + var inherits = requireInherits_browser$1(); + var stream2 = requireReadableBrowser(); + var rStates = response.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 + }; + var IncomingMessage = response.IncomingMessage = function(xhr, response2, mode, resetTimers) { + var self2 = this; + stream2.Readable.call(self2); + self2._mode = mode; + self2.headers = {}; + self2.rawHeaders = []; + self2.trailers = {}; + self2.rawTrailers = []; + self2.on("end", function() { + process.nextTick(function() { + self2.emit("close"); + }); + }); + if (mode === "fetch") { + let read2 = function() { + reader.read().then(function(result) { + if (self2._destroyed) + return; + resetTimers(result.done); + if (result.done) { + self2.push(null); + return; + } + self2.push(Buffer.from(result.value)); + read2(); + }).catch(function(err) { + resetTimers(true); + if (!self2._destroyed) + self2.emit("error", err); + }); + }; + self2._fetchResponse = response2; + self2.url = response2.url; + self2.statusCode = response2.status; + self2.statusMessage = response2.statusText; + response2.headers.forEach(function(header, key2) { + self2.headers[key2.toLowerCase()] = header; + self2.rawHeaders.push(key2, header); + }); + if (capability2.writableStream) { + var writable2 = new WritableStream({ + write: function(chunk) { + resetTimers(false); + return new Promise(function(resolve, reject) { + if (self2._destroyed) { + reject(); + } else if (self2.push(Buffer.from(chunk))) { + resolve(); + } else { + self2._resumeFetch = resolve; + } + }); + }, + close: function() { + resetTimers(true); + if (!self2._destroyed) + self2.push(null); + }, + abort: function(err) { + resetTimers(true); + if (!self2._destroyed) + self2.emit("error", err); + } + }); + try { + response2.body.pipeTo(writable2).catch(function(err) { + resetTimers(true); + if (!self2._destroyed) + self2.emit("error", err); + }); + return; + } catch (e) { + } + } + var reader = response2.body.getReader(); + read2(); + } else { + self2._xhr = xhr; + self2._pos = 0; + self2.url = xhr.responseURL; + self2.statusCode = xhr.status; + self2.statusMessage = xhr.statusText; + var headers = xhr.getAllResponseHeaders().split(/\r?\n/); + headers.forEach(function(header) { + var matches = header.match(/^([^:]+):\s*(.*)/); + if (matches) { + var key2 = matches[1].toLowerCase(); + if (key2 === "set-cookie") { + if (self2.headers[key2] === void 0) { + self2.headers[key2] = []; + } + self2.headers[key2].push(matches[2]); + } else if (self2.headers[key2] !== void 0) { + self2.headers[key2] += ", " + matches[2]; + } else { + self2.headers[key2] = matches[2]; + } + self2.rawHeaders.push(matches[1], matches[2]); + } + }); + self2._charset = "x-user-defined"; + if (!capability2.overrideMimeType) { + var mimeType = self2.rawHeaders["mime-type"]; + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/); + if (charsetMatch) { + self2._charset = charsetMatch[1].toLowerCase(); + } + } + if (!self2._charset) + self2._charset = "utf-8"; + } + } + }; + inherits(IncomingMessage, stream2.Readable); + IncomingMessage.prototype._read = function() { + var self2 = this; + var resolve = self2._resumeFetch; + if (resolve) { + self2._resumeFetch = null; + resolve(); + } + }; + IncomingMessage.prototype._onXHRProgress = function(resetTimers) { + var self2 = this; + var xhr = self2._xhr; + var response2 = null; + switch (self2._mode) { + case "text": + response2 = xhr.responseText; + if (response2.length > self2._pos) { + var newData = response2.substr(self2._pos); + if (self2._charset === "x-user-defined") { + var buffer2 = Buffer.alloc(newData.length); + for (var i = 0; i < newData.length; i++) + buffer2[i] = newData.charCodeAt(i) & 255; + self2.push(buffer2); + } else { + self2.push(newData, self2._charset); + } + self2._pos = response2.length; + } + break; + case "arraybuffer": + if (xhr.readyState !== rStates.DONE || !xhr.response) + break; + response2 = xhr.response; + self2.push(Buffer.from(new Uint8Array(response2))); + break; + case "moz-chunked-arraybuffer": + response2 = xhr.response; + if (xhr.readyState !== rStates.LOADING || !response2) + break; + self2.push(Buffer.from(new Uint8Array(response2))); + break; + case "ms-stream": + response2 = xhr.response; + if (xhr.readyState !== rStates.LOADING) + break; + var reader = new commonjsGlobal.MSStreamReader(); + reader.onprogress = function() { + if (reader.result.byteLength > self2._pos) { + self2.push(Buffer.from(new Uint8Array(reader.result.slice(self2._pos)))); + self2._pos = reader.result.byteLength; + } + }; + reader.onload = function() { + resetTimers(true); + self2.push(null); + }; + reader.readAsArrayBuffer(response2); + break; + } + if (self2._xhr.readyState === rStates.DONE && self2._mode !== "ms-stream") { + resetTimers(true); + self2.push(null); + } + }; + return response; +} +var hasRequiredRequest; +function requireRequest() { + if (hasRequiredRequest) return request.exports; + hasRequiredRequest = 1; + var capability2 = requireCapability(); + var inherits = requireInherits_browser$1(); + var response2 = requireResponse(); + var stream2 = requireReadableBrowser(); + var IncomingMessage = response2.IncomingMessage; + var rStates = response2.readyStates; + function decideMode(preferBinary, useFetch) { + if (capability2.fetch && useFetch) { + return "fetch"; + } else if (capability2.mozchunkedarraybuffer) { + return "moz-chunked-arraybuffer"; + } else if (capability2.msstream) { + return "ms-stream"; + } else if (capability2.arraybuffer && preferBinary) { + return "arraybuffer"; + } else { + return "text"; + } + } + var ClientRequest = request.exports = function(opts) { + var self2 = this; + stream2.Writable.call(self2); + self2._opts = opts; + self2._body = []; + self2._headers = {}; + if (opts.auth) + self2.setHeader("Authorization", "Basic " + Buffer.from(opts.auth).toString("base64")); + Object.keys(opts.headers).forEach(function(name) { + self2.setHeader(name, opts.headers[name]); + }); + var preferBinary; + var useFetch = true; + if (opts.mode === "disable-fetch" || "requestTimeout" in opts && !capability2.abortController) { + useFetch = false; + preferBinary = true; + } else if (opts.mode === "prefer-streaming") { + preferBinary = false; + } else if (opts.mode === "allow-wrong-content-type") { + preferBinary = !capability2.overrideMimeType; + } else if (!opts.mode || opts.mode === "default" || opts.mode === "prefer-fast") { + preferBinary = true; + } else { + throw new Error("Invalid value for opts.mode"); + } + self2._mode = decideMode(preferBinary, useFetch); + self2._fetchTimer = null; + self2._socketTimeout = null; + self2._socketTimer = null; + self2.on("finish", function() { + self2._onFinish(); + }); + }; + inherits(ClientRequest, stream2.Writable); + ClientRequest.prototype.setHeader = function(name, value) { + var self2 = this; + var lowerName = name.toLowerCase(); + if (unsafeHeaders.indexOf(lowerName) !== -1) + return; + self2._headers[lowerName] = { + name, + value + }; + }; + ClientRequest.prototype.getHeader = function(name) { + var header = this._headers[name.toLowerCase()]; + if (header) + return header.value; + return null; + }; + ClientRequest.prototype.removeHeader = function(name) { + var self2 = this; + delete self2._headers[name.toLowerCase()]; + }; + ClientRequest.prototype._onFinish = function() { + var self2 = this; + if (self2._destroyed) + return; + var opts = self2._opts; + if ("timeout" in opts && opts.timeout !== 0) { + self2.setTimeout(opts.timeout); + } + var headersObj = self2._headers; + var body = null; + if (opts.method !== "GET" && opts.method !== "HEAD") { + body = new Blob(self2._body, { + type: (headersObj["content-type"] || {}).value || "" + }); + } + var headersList = []; + Object.keys(headersObj).forEach(function(keyName) { + var name = headersObj[keyName].name; + var value = headersObj[keyName].value; + if (Array.isArray(value)) { + value.forEach(function(v) { + headersList.push([name, v]); + }); + } else { + headersList.push([name, value]); + } + }); + if (self2._mode === "fetch") { + var signal = null; + if (capability2.abortController) { + var controller = new AbortController(); + signal = controller.signal; + self2._fetchAbortController = controller; + if ("requestTimeout" in opts && opts.requestTimeout !== 0) { + self2._fetchTimer = commonjsGlobal.setTimeout(function() { + self2.emit("requestTimeout"); + if (self2._fetchAbortController) + self2._fetchAbortController.abort(); + }, opts.requestTimeout); + } + } + commonjsGlobal.fetch(self2._opts.url, { + method: self2._opts.method, + headers: headersList, + body: body || void 0, + mode: "cors", + credentials: opts.withCredentials ? "include" : "same-origin", + signal + }).then(function(response3) { + self2._fetchResponse = response3; + self2._resetTimers(false); + self2._connect(); + }, function(reason) { + self2._resetTimers(true); + if (!self2._destroyed) + self2.emit("error", reason); + }); + } else { + var xhr = self2._xhr = new commonjsGlobal.XMLHttpRequest(); + try { + xhr.open(self2._opts.method, self2._opts.url, true); + } catch (err) { + process.nextTick(function() { + self2.emit("error", err); + }); + return; + } + if ("responseType" in xhr) + xhr.responseType = self2._mode; + if ("withCredentials" in xhr) + xhr.withCredentials = !!opts.withCredentials; + if (self2._mode === "text" && "overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + if ("requestTimeout" in opts) { + xhr.timeout = opts.requestTimeout; + xhr.ontimeout = function() { + self2.emit("requestTimeout"); + }; + } + headersList.forEach(function(header) { + xhr.setRequestHeader(header[0], header[1]); + }); + self2._response = null; + xhr.onreadystatechange = function() { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self2._onXHRProgress(); + break; + } + }; + if (self2._mode === "moz-chunked-arraybuffer") { + xhr.onprogress = function() { + self2._onXHRProgress(); + }; + } + xhr.onerror = function() { + if (self2._destroyed) + return; + self2._resetTimers(true); + self2.emit("error", new Error("XHR error")); + }; + try { + xhr.send(body); + } catch (err) { + process.nextTick(function() { + self2.emit("error", err); + }); + return; + } + } + }; + function statusValid(xhr) { + try { + var status = xhr.status; + return status !== null && status !== 0; + } catch (e) { + return false; + } + } + ClientRequest.prototype._onXHRProgress = function() { + var self2 = this; + self2._resetTimers(false); + if (!statusValid(self2._xhr) || self2._destroyed) + return; + if (!self2._response) + self2._connect(); + self2._response._onXHRProgress(self2._resetTimers.bind(self2)); + }; + ClientRequest.prototype._connect = function() { + var self2 = this; + if (self2._destroyed) + return; + self2._response = new IncomingMessage(self2._xhr, self2._fetchResponse, self2._mode, self2._resetTimers.bind(self2)); + self2._response.on("error", function(err) { + self2.emit("error", err); + }); + self2.emit("response", self2._response); + }; + ClientRequest.prototype._write = function(chunk, encoding2, cb) { + var self2 = this; + self2._body.push(chunk); + cb(); + }; + ClientRequest.prototype._resetTimers = function(done) { + var self2 = this; + commonjsGlobal.clearTimeout(self2._socketTimer); + self2._socketTimer = null; + if (done) { + commonjsGlobal.clearTimeout(self2._fetchTimer); + self2._fetchTimer = null; + } else if (self2._socketTimeout) { + self2._socketTimer = commonjsGlobal.setTimeout(function() { + self2.emit("timeout"); + }, self2._socketTimeout); + } + }; + ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function(err) { + var self2 = this; + self2._destroyed = true; + self2._resetTimers(true); + if (self2._response) + self2._response._destroyed = true; + if (self2._xhr) + self2._xhr.abort(); + else if (self2._fetchAbortController) + self2._fetchAbortController.abort(); + if (err) + self2.emit("error", err); + }; + ClientRequest.prototype.end = function(data2, encoding2, cb) { + var self2 = this; + if (typeof data2 === "function") { + cb = data2; + data2 = void 0; + } + stream2.Writable.prototype.end.call(self2, data2, encoding2, cb); + }; + ClientRequest.prototype.setTimeout = function(timeout, cb) { + var self2 = this; + if (cb) + self2.once("timeout", cb); + self2._socketTimeout = timeout; + self2._resetTimers(false); + }; + ClientRequest.prototype.flushHeaders = function() { + }; + ClientRequest.prototype.setNoDelay = function() { + }; + ClientRequest.prototype.setSocketKeepAlive = function() { + }; + var unsafeHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "cookie2", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" + ]; + return request.exports; +} +var immutable; +var hasRequiredImmutable; +function requireImmutable() { + if (hasRequiredImmutable) return immutable; + hasRequiredImmutable = 1; + immutable = extend2; + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + function extend2() { + var target = {}; + for (var i = 0; i < arguments.length; i++) { + var source2 = arguments[i]; + for (var key2 in source2) { + if (hasOwnProperty2.call(source2, key2)) { + target[key2] = source2[key2]; + } + } + } + return target; + } + return immutable; +} +var browser$1; +var hasRequiredBrowser$1; +function requireBrowser$1() { + if (hasRequiredBrowser$1) return browser$1; + hasRequiredBrowser$1 = 1; + browser$1 = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" + }; + return browser$1; +} +var hasRequiredStreamHttp; +function requireStreamHttp() { + if (hasRequiredStreamHttp) return streamHttp; + hasRequiredStreamHttp = 1; + (function(exports) { + var ClientRequest = requireRequest(); + var response2 = requireResponse(); + var extend2 = requireImmutable(); + var statusCodes = requireBrowser$1(); + var url2 = require$$1$5; + var http2 = exports; + http2.request = function(opts, cb) { + if (typeof opts === "string") + opts = url2.parse(opts); + else + opts = extend2(opts); + var defaultProtocol = commonjsGlobal.location.protocol.search(/^https?:$/) === -1 ? "http:" : ""; + var protocol = opts.protocol || defaultProtocol; + var host = opts.hostname || opts.host; + var port = opts.port; + var path2 = opts.path || "/"; + if (host && host.indexOf(":") !== -1) + host = "[" + host + "]"; + opts.url = (host ? protocol + "//" + host : "") + (port ? ":" + port : "") + path2; + opts.method = (opts.method || "GET").toUpperCase(); + opts.headers = opts.headers || {}; + var req = new ClientRequest(opts); + if (cb) + req.on("response", cb); + return req; + }; + http2.get = function get2(opts, cb) { + var req = http2.request(opts, cb); + req.end(); + return req; + }; + http2.ClientRequest = ClientRequest; + http2.IncomingMessage = response2.IncomingMessage; + http2.Agent = function() { + }; + http2.Agent.defaultMaxSockets = 4; + http2.globalAgent = new http2.Agent(); + http2.STATUS_CODES = statusCodes; + http2.METHODS = [ + "CHECKOUT", + "CONNECT", + "COPY", + "DELETE", + "GET", + "HEAD", + "LOCK", + "M-SEARCH", + "MERGE", + "MKACTIVITY", + "MKCOL", + "MOVE", + "NOTIFY", + "OPTIONS", + "PATCH", + "POST", + "PROPFIND", + "PROPPATCH", + "PURGE", + "PUT", + "REPORT", + "SEARCH", + "SUBSCRIBE", + "TRACE", + "UNLOCK", + "UNSUBSCRIBE" + ]; + })(streamHttp); + return streamHttp; +} +var streamHttpExports = requireStreamHttp(); +const http = /* @__PURE__ */ getDefaultExportFromCjs(streamHttpExports); +var httpsBrowserify = { exports: {} }; +var hasRequiredHttpsBrowserify; +function requireHttpsBrowserify() { + if (hasRequiredHttpsBrowserify) return httpsBrowserify.exports; + hasRequiredHttpsBrowserify = 1; + (function(module) { + var http2 = requireStreamHttp(); + var url2 = require$$1$5; + var https2 = module.exports; + for (var key2 in http2) { + if (http2.hasOwnProperty(key2)) https2[key2] = http2[key2]; + } + https2.request = function(params, cb) { + params = validateParams(params); + return http2.request.call(this, params, cb); + }; + https2.get = function(params, cb) { + params = validateParams(params); + return http2.get.call(this, params, cb); + }; + function validateParams(params) { + if (typeof params === "string") { + params = url2.parse(params); + } + if (!params.protocol) { + params.protocol = "https:"; + } + if (params.protocol !== "https:") { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"'); + } + return params; + } + })(httpsBrowserify); + return httpsBrowserify.exports; +} +var httpsBrowserifyExports = requireHttpsBrowserify(); +const https = /* @__PURE__ */ getDefaultExportFromCjs(httpsBrowserifyExports); +const connectionAttemptDelayMs = 300; +const kDNSLookupAt = Symbol("kDNSLookupAt"); +const kTCPConnectionAt = Symbol("kTCPConnectionAt"); +class HttpHappyEyeballsAgent extends http.Agent { + createConnection(options2, oncreate) { + if (net.isIP(clientRequestArgsToHostName(options2))) + return net.createConnection(options2); + createConnectionAsync( + options2, + oncreate, + /* useTLS */ + false + ).catch((err) => oncreate == null ? void 0 : oncreate(err)); + } +} +class HttpsHappyEyeballsAgent extends https.Agent { + createConnection(options2, oncreate) { + if (net.isIP(clientRequestArgsToHostName(options2))) + return tls.connect(options2); + createConnectionAsync( + options2, + oncreate, + /* useTLS */ + true + ).catch((err) => oncreate == null ? void 0 : oncreate(err)); + } +} +const httpsHappyEyeballsAgent = new HttpsHappyEyeballsAgent({ keepAlive: true }); +const httpHappyEyeballsAgent = new HttpHappyEyeballsAgent({ keepAlive: true }); +async function createSocket(host, port) { + return new Promise((resolve, reject) => { + if (net.isIP(host)) { + const socket = net.createConnection({ host, port }); + socket.on("connect", () => resolve(socket)); + socket.on("error", (error2) => reject(error2)); + } else { + createConnectionAsync( + { host, port }, + (err, socket) => { + if (err) + reject(err); + if (socket) + resolve(socket); + }, + /* useTLS */ + false + ).catch((err) => reject(err)); + } + }); +} +async function createTLSSocket(options2) { + return new Promise((resolve, reject) => { + assert(options2.host, "host is required"); + if (net.isIP(options2.host)) { + const socket = tls.connect(options2); + socket.on("secureConnect", () => resolve(socket)); + socket.on("error", (error2) => reject(error2)); + } else { + createConnectionAsync(options2, (err, socket) => { + if (err) + reject(err); + if (socket) { + socket.on("secureConnect", () => resolve(socket)); + socket.on("error", (error2) => reject(error2)); + } + }, true).catch((err) => reject(err)); + } + }); +} +async function createConnectionAsync(options2, oncreate, useTLS) { + const lookup = options2.__testHookLookup || lookupAddresses; + const hostname = clientRequestArgsToHostName(options2); + const addresses = await lookup(hostname); + const dnsLookupAt = monotonicTime(); + const sockets = /* @__PURE__ */ new Set(); + let firstError; + let errorCount = 0; + const handleError = (socket, err) => { + if (!sockets.delete(socket)) + return; + ++errorCount; + firstError ?? (firstError = err); + if (errorCount === addresses.length) + oncreate == null ? void 0 : oncreate(firstError); + }; + const connected = new ManualPromise(); + for (const { address } of addresses) { + const socket = useTLS ? tls.connect({ + ...options2, + port: options2.port, + host: address, + servername: hostname + }) : net.createConnection({ + ...options2, + port: options2.port, + host: address + }); + socket[kDNSLookupAt] = dnsLookupAt; + socket.on("connect", () => { + socket[kTCPConnectionAt] = monotonicTime(); + connected.resolve(); + oncreate == null ? void 0 : oncreate(null, socket); + sockets.delete(socket); + for (const s of sockets) + s.destroy(); + sockets.clear(); + }); + socket.on("timeout", () => { + socket.destroy(); + handleError(socket, new Error("Connection timeout")); + }); + socket.on("error", (e) => handleError(socket, e)); + sockets.add(socket); + await Promise.race([ + connected, + new Promise((f) => setTimeout(f, connectionAttemptDelayMs)) + ]); + if (connected.isDone()) + break; + } +} +async function lookupAddresses(hostname) { + const addresses = await promises.promises.lookup(hostname, { all: true, family: 0, verbatim: true }); + let firstFamily = addresses.filter(({ family }) => family === 6); + let secondFamily = addresses.filter(({ family }) => family === 4); + if (firstFamily.length && firstFamily[0] !== addresses[0]) { + const tmp = firstFamily; + firstFamily = secondFamily; + secondFamily = tmp; + } + const result = []; + for (let i = 0; i < Math.max(firstFamily.length, secondFamily.length); i++) { + if (firstFamily[i]) + result.push(firstFamily[i]); + if (secondFamily[i]) + result.push(secondFamily[i]); + } + return result; +} +function clientRequestArgsToHostName(options2) { + if (options2.hostname) + return options2.hostname; + if (options2.host) + return options2.host; + throw new Error("Either options.hostname or options.host must be provided"); +} +function timingForSocket(socket) { + return { + dnsLookupAt: socket[kDNSLookupAt], + tcpConnectionAt: socket[kTCPConnectionAt] + }; +} +const NET_DEFAULT_TIMEOUT = 3e4; +function httpRequest(params, onResponse, onError) { + const parsedUrl = url.parse(params.url); + let options2 = { + ...parsedUrl, + agent: parsedUrl.protocol === "https:" ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent, + method: params.method || "GET", + headers: params.headers + }; + if (params.rejectUnauthorized !== void 0) + options2.rejectUnauthorized = params.rejectUnauthorized; + const timeout = params.timeout ?? NET_DEFAULT_TIMEOUT; + const proxyURL = getProxyForUrl(params.url); + if (proxyURL) { + const parsedProxyURL = url.parse(proxyURL); + if (params.url.startsWith("http:")) { + options2 = { + path: parsedUrl.href, + host: parsedProxyURL.hostname, + port: parsedProxyURL.port, + headers: options2.headers, + method: options2.method + }; + } else { + parsedProxyURL.secureProxy = parsedProxyURL.protocol === "https:"; + options2.agent = new HttpsProxyAgent(parsedProxyURL); + options2.rejectUnauthorized = false; + } + } + const requestCallback = (res) => { + const statusCode = res.statusCode || 0; + if (statusCode >= 300 && statusCode < 400 && res.headers.location) { + request2.destroy(); + httpRequest({ ...params, url: new URL(res.headers.location, params.url).toString() }, onResponse, onError); + } else { + onResponse(res); + } + }; + const request2 = options2.protocol === "https:" ? https.request(options2, requestCallback) : http.request(options2, requestCallback); + request2.on("error", onError); + if (timeout !== void 0) { + const rejectOnTimeout = () => { + onError(new Error(`Request to ${params.url} timed out after ${timeout}ms`)); + request2.abort(); + }; + if (timeout <= 0) { + rejectOnTimeout(); + return; + } + request2.setTimeout(timeout, rejectOnTimeout); + } + request2.end(params.data); +} +function fetchData(params, onError) { + return new Promise((resolve, reject) => { + httpRequest(params, async (response2) => { + if (response2.statusCode !== 200) { + const error2 = onError ? await onError(params, response2) : new Error(`fetch failed: server returned code ${response2.statusCode}. URL: ${params.url}`); + reject(error2); + return; + } + let body = ""; + response2.on("data", (chunk) => body += chunk); + response2.on("error", (error2) => reject(error2)); + response2.on("end", () => resolve(body)); + }, reject); + }); +} +function shouldBypassProxy(url2, bypass) { + if (!bypass) + return false; + const domains = bypass.split(",").map((s) => { + s = s.trim(); + if (!s.startsWith(".")) + s = "." + s; + return s; + }); + const domain = "." + url2.hostname; + return domains.some((d) => domain.endsWith(d)); +} +function createProxyAgent(proxy, forUrl) { + var _a2; + if (!proxy) + return; + if (forUrl && proxy.bypass && shouldBypassProxy(forUrl, proxy.bypass)) + return; + let proxyServer = proxy.server.trim(); + if (!/^\w+:\/\//.test(proxyServer)) + proxyServer = "http://" + proxyServer; + const proxyOpts = url.parse(proxyServer); + if ((_a2 = proxyOpts.protocol) == null ? void 0 : _a2.startsWith("socks")) { + return new SocksProxyAgent({ + host: proxyOpts.hostname, + port: proxyOpts.port || void 0 + }); + } + if (proxy.username) + proxyOpts.auth = `${proxy.username}:${proxy.password || ""}`; + if (forUrl && ["ws:", "wss:"].includes(forUrl.protocol)) { + return new HttpsProxyAgent(proxyOpts); + } + return new HttpsProxyAgent(proxyOpts); +} +var browser; +var hasRequiredBrowser; +function requireBrowser() { + if (hasRequiredBrowser) return browser; + hasRequiredBrowser = 1; + var global2 = /* @__PURE__ */ function() { + return this; + }(); + var WebSocket2 = global2.WebSocket || global2.MozWebSocket; + browser = WebSocket2 ? ws2 : null; + function ws2(uri2, protocols, opts) { + var instance; + if (protocols) { + instance = new WebSocket2(uri2, protocols); + } else { + instance = new WebSocket2(uri2); + } + return instance; + } + if (WebSocket2) ws2.prototype = WebSocket2.prototype; + return browser; +} +var endpoint; +var hasRequiredEndpoint; +function requireEndpoint() { + if (hasRequiredEndpoint) return endpoint; + hasRequiredEndpoint = 1; + var Writable = requireBrowser$h().Writable; + var inherits = requireInherits_browser$1(); + function Endpoint(options2, callback) { + if (!(this instanceof Endpoint)) return new Endpoint(options2, callback); + if (typeof options2 === "function") { + callback = options2; + options2 = {}; + } + Writable.call(this, options2); + var self2 = this; + this._objectMode = !!options2.objectMode; + this._buffers = []; + var sources = []; + function cleanup() { + self2.removeListener("pipe", onpipe); + self2.removeListener("error", error2); + self2.removeListener("finish", finish); + for (var i = 0, l = sources.length; i < l; i++) { + sources[i].removeListener("error", error2); + } + } + function finish() { + cleanup(); + callback(null, self2.buffer); + } + function error2(err) { + cleanup(); + callback(err, self2.buffer); + } + function onpipe(source2) { + sources.push(source2); + source2.once("error", error2); + } + function onunpipe(source2) { + var index2 = sources.indexOf(source2); + if (index2 !== -1) { + sources.splice(index2, 1); + source2.removeListener("error", error2); + } + } + this.once("finish", finish); + this.once("error", error2); + this.on("pipe", onpipe); + this.on("unpipe", onunpipe); + } + endpoint = Endpoint; + inherits(Endpoint, Writable); + Endpoint.prototype._write = function(data2, encodeing, callback) { + this._buffers.push(data2); + return callback(null); + }; + Object.defineProperty(Endpoint.prototype, "buffer", { + get: function() { + if (this._objectMode) { + return this._buffers; + } else { + var total = Buffer.concat(this._buffers); + this._buffers = [total]; + return total; + } + }, + enumerable: true, + configurable: true + }); + return endpoint; +} +var inspector; +var hasRequiredInspector; +function requireInspector() { + if (hasRequiredInspector) return inspector; + hasRequiredInspector = 1; + var fs2 = require$$2$1; + var path2 = requirePath(); + var util2 = requireUtil$5(); + var http2 = requireStreamHttp(); + var events2 = requireEvents(); + var WebSocket2 = requireBrowser(); + var endpoint2 = requireEndpoint(); + var library = {}; + fs2.readdirSync(path2.resolve(__dirname, "lib")).filter(function(filename) { + return filename[0] !== "."; + }).forEach(function(filename) { + var filepath = path2.resolve(__dirname, "lib", filename); + library[path2.basename(filename, ".js")] = commonjsRequire(filepath); + }); + function WebKitInspector(port, host, href, callback) { + if (!(this instanceof WebKitInspector)) { + return new WebKitInspector(port, host, href, callback); + } + this.closed = false; + this._callbacks = {}; + this._id = 0; + this.debug = false; + var domains = Object.keys(library); + for (var i = 0, l = domains.length; i < l; i++) { + this[domains[i]] = new library[domains[i]](this); + } + if (typeof port !== "number") { + throw new Error("A port number must be speficed"); + } + if (typeof host !== "string") { + throw new Error("A host name must be speficed"); + } + if (typeof href !== "string") { + throw new Error("A page url must be speficed"); + } + if (callback) this.once("connect", callback); + this._tryConnect(port, host, href, 0, 2e3); + } + util2.inherits(WebKitInspector, events2.EventEmitter); + inspector = WebKitInspector; + WebKitInspector.prototype._tryConnect = function(port, host, href, use, timeout) { + var self2 = this; + var time = Date.now(); + var req = http2.get("http://" + host + ":" + port + "/json", function(res) { + res.pipe(endpoint2(function(err, buffer2) { + if (err) return self2.emit("error", err); + if (self2.closed) return; + var wsUrl = null; + var pages = JSON.parse(buffer2.toString()); + for (var i = 0, l = pages.length; i < l; i++) { + if (pages[i].url === href) { + wsUrl = pages[i].webSocketDebuggerUrl || false; + break; + } + } + if (wsUrl === null) { + return self2.emit("error", new Error("No page with the given url was found")); + } + if (wsUrl === false) { + return self2.emit("error", new Error("Another inspector is already listning")); + } + self2._ws = new WebSocket2(wsUrl); + self2._ws.on("message", self2._respond.bind(self2)); + self2._ws.on("error", self2.emit.bind(self2, "error")); + self2._ws.once("open", self2.emit.bind(self2, "connect")); + self2._ws.once("close", self2.close.bind(self2)); + })); + }); + req.on("error", function(err) { + var timeUse = time - Date.now() + use; + if (err.code === "ECONNREFUSED" && timeUse + 100 < timeout && self2.closed === false) { + setTimeout(function() { + self2._tryConnect(port, host, href, timeUse, timeout); + }, 100); + return; + } + self2.emit("error", err); + }); + }; + WebKitInspector.prototype._splitArgs = function(argsList) { + var args = [], callback; + if (args.length === 1) { + callback = argsList[0]; + } else { + for (var i = 0, l = argsList.length; i < l; i++) { + args.push(argsList[i]); + } + callback = args.pop(); + } + if (typeof callback !== "function") { + throw new Error("missing callback"); + } + return { args, callback }; + }; + WebKitInspector.prototype._request = function(method, params, callback) { + var self2 = this; + var newId = ++this._id; + var request2 = { + "id": newId, + "method": method, + "params": params + }; + this._callbacks[newId] = callback; + if (this.debug) { + console.log("=== Send request #" + newId + " ==="); + console.log(util2.inspect(request2, false, Infinity, true)); + console.log("=== message end ==="); + } + this._ws.send(JSON.stringify(request2), function(err) { + if (err) { + delete self2._callbacks[newId]; + callback(err, null); + } + }); + }; + WebKitInspector.prototype._respond = function(message) { + message = JSON.parse(message); + if (message.id) { + if (this.debug) { + console.log("=== Got response #" + message.id + " ==="); + console.log(util2.inspect(message, false, Infinity, true)); + console.log("=== message end ==="); + } + var callback = this._callbacks[message.id]; + if (callback === void 0) { + this.emit("error", new Error("atempt to fire a missing callback")); + return; + } + delete this._callbacks[message.id]; + if (message.error) { + var err = new Error(message.error.message); + err.code = message.error.code; + callback.call(null, err, null); + } else { + callback.call(null, null, message.result); + } + } else { + if (this.debug) { + console.log("=== Got event ::" + message.method + " ==="); + console.log(util2.inspect(message, false, Infinity, true)); + console.log("=== message end ==="); + } + var method = message.method.split("."); + this[method[0]].emit(method[1], message.params); + } + }; + WebKitInspector.prototype.close = function(callback) { + var self2 = this; + if (this.closed) return; + this.closed = true; + if (typeof callback === "function") this.once("close", callback); + if (this._ws && this._ws.readyState !== WebSocket2.CLOSED) { + this._ws.once("close", function() { + self2.emit("close"); + }); + this._ws.close(); + } else { + this.emit("close"); + } + }; + return inspector; +} +var browserExports = requireBrowser$h(); +const stream = /* @__PURE__ */ getDefaultExportFromCjs(browserExports); +var eventsExports = requireEvents(); +const EventEmitter$1 = /* @__PURE__ */ getDefaultExportFromCjs(eventsExports); +class AsyncLocalStorage { + constructor() { + __publicField(this, "lastZoneId", 0); + __publicField(this, "_zones", /* @__PURE__ */ new Map()); + __publicField(this, "_current"); + } + getStore() { + return this._current; + } + run(store, func) { + let id; + if (store) { + id = this.lastZoneId++; + this._zones.set(id, store); + this._current = store; + Object.defineProperty(func, "name", { value: `__PWZONE__[${id}]-${store.type}` }); + } + return runWithFinally(() => func(), () => { + if (id) + this._zones.delete(id); + if (store) + this._current = store.previous; + }); + } +} +function runWithFinally(func, finallyFunc) { + try { + const result = func(); + if (result instanceof Promise) { + return result.then((r) => { + finallyFunc(); + return r; + }).catch((e) => { + finallyFunc(); + throw e; + }); + } + finallyFunc(); + return result; + } catch (e) { + finallyFunc(); + throw e; + } +} +const asyncLocalStorage = new AsyncLocalStorage(); +class Zone { + constructor(asyncLocalStorage2, store) { + this._asyncLocalStorage = asyncLocalStorage2; + this._data = store; + } + with(type2, data2) { + return new Zone(this._asyncLocalStorage, new Map(this._data).set(type2, data2)); + } + without(type2) { + const data2 = type2 ? new Map(this._data) : /* @__PURE__ */ new Map(); + data2.delete(type2); + return new Zone(this._asyncLocalStorage, data2); + } + run(func) { + return this._asyncLocalStorage.run(this, func); + } + data(type2) { + return this._data.get(type2); + } +} +const emptyZone = new Zone(asyncLocalStorage, /* @__PURE__ */ new Map()); +function currentZone() { + return asyncLocalStorage.getStore() ?? emptyZone; +} +const pipelineAsync = utilExports.promisify(browserExports.pipeline); +class NodeZone { + constructor(zone) { + this._zone = zone; + } + push(data2) { + return new NodeZone(this._zone.with("apiZone", data2)); + } + pop() { + return new NodeZone(this._zone.without("apiZone")); + } + run(func) { + return this._zone.run(func); + } + data() { + return this._zone.data("apiZone"); + } +} +let boxedStackPrefixes = []; +const coreDir = path.dirname(Boolean("../../../package.json")); +const nodePlatform = { + name: "node", + boxedStackPrefixes: () => { + if (define_process_env_default.PWDEBUGIMPL) + return []; + return [coreDir, ...boxedStackPrefixes]; + }, + calculateSha1: (text) => { + const sha12 = crypto.createHash("sha1"); + sha12.update(text); + return Promise.resolve(sha12.digest("hex")); + }, + colors, + coreDir, + createGuid: () => crypto.randomBytes(16).toString("hex"), + defaultMaxListeners: () => eventsExports.EventEmitter.defaultMaxListeners, + fs: () => fs, + env: define_process_env_default, + inspectCustom: utilExports.inspect.custom, + isDebugMode: () => !!debugMode(), + isJSDebuggerAttached: () => !!requireInspector().url(), + isLogEnabled(name) { + return debugLogger.isEnabled(name); + }, + isUnderTest: () => isUnderTest(), + log(name, message) { + debugLogger.log(name, message); + }, + path: () => path, + pathSeparator: path.sep, + showInternalStackFrames: () => !!define_process_env_default.PWDEBUGIMPL, + async streamFile(path2, stream2) { + await pipelineAsync(fs.createReadStream(path2), stream2); + }, + streamReadable: (channel) => { + return new ReadableStreamImpl(channel); + }, + streamWritable: (channel) => { + return new WritableStreamImpl(channel); + }, + zones: { + current: () => new NodeZone(currentZone()), + empty: new NodeZone(emptyZone) + } +}; +class ReadableStreamImpl extends browserExports.Readable { + constructor(channel) { + super(); + this._channel = channel; + } + async _read() { + const result = await this._channel.read({ size: 1024 * 1024 }); + if (result.binary.byteLength) + this.push(result.binary); + else + this.push(null); + } + _destroy(error2, callback) { + this._channel.close().catch((e) => null); + super._destroy(error2, callback); + } +} +class WritableStreamImpl extends browserExports.Writable { + constructor(channel) { + super(); + this._channel = channel; + } + async _write(chunk, encoding2, callback) { + const error2 = await this._channel.write({ binary: typeof chunk === "string" ? Buffer.from(chunk) : chunk }).catch((e) => e); + callback(error2 || null); + } + async _final(callback) { + const error2 = await this._channel.close().catch((e) => e); + callback(error2 || null); + } +} +function noop() { +} +const createInterface = noop; +const gracefullyCloseSet = /* @__PURE__ */ new Set(); +const killSet = /* @__PURE__ */ new Set(); +async function gracefullyCloseAll() { + await Promise.all(Array.from(gracefullyCloseSet).map((gracefullyClose) => gracefullyClose().catch((e) => { + }))); +} +function gracefullyProcessExitDoNotHang(code) { + setTimeout(() => process.exit(code), 3e4); + gracefullyCloseAll().then(() => { + process.exit(code); + }); +} +function exitHandler() { + for (const kill of killSet) + kill(); +} +let sigintHandlerCalled = false; +function sigintHandler() { + const exitWithCode130 = () => { + if (isUnderTest()) { + setTimeout(() => process.exit(130), 1e3); + } else { + process.exit(130); + } + }; + if (sigintHandlerCalled) { + process.off("SIGINT", sigintHandler); + for (const kill of killSet) + kill(); + exitWithCode130(); + } else { + sigintHandlerCalled = true; + gracefullyCloseAll().then(() => exitWithCode130()); + } +} +function sigtermHandler() { + gracefullyCloseAll(); +} +function sighupHandler() { + gracefullyCloseAll(); +} +const installedHandlers = /* @__PURE__ */ new Set(); +const processHandlers = { + exit: exitHandler, + SIGINT: sigintHandler, + SIGTERM: sigtermHandler, + SIGHUP: sighupHandler +}; +function addProcessHandlerIfNeeded(name) { + if (!installedHandlers.has(name)) { + installedHandlers.add(name); + process.on(name, processHandlers[name]); + } +} +function removeProcessHandlersIfNeeded() { + if (killSet.size) + return; + for (const handler of installedHandlers) + process.off(handler, processHandlers[handler]); + installedHandlers.clear(); +} +async function launchProcess(options2) { + options2.stdio === "pipe" ? ["ignore", "pipe", "pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe"]; + options2.log(` ${options2.command} ${options2.args ? options2.args.join(" ") : ""}`); + ({ + // On non-windows platforms, `detached: true` makes child process a leader of a new + // process group, making it possible to kill child process tree with `.kill(-pid)` command. + // @see https://nodejs.org/api/child_process.html#child_process_options_detached + detached: process.platform !== "win32", + env: options2.env, + cwd: options2.cwd, + shell: options2.shell + }); + const spawnedProcess = spawn(options2.command, options2.args || []); + const cleanup = async () => { + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + const errors2 = await removeFolders(options2.tempDirectories); + for (let i = 0; i < options2.tempDirectories.length; ++i) { + if (errors2[i]) + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${options2.tempDirectories[i]}: ${errors2[i]}`); + } + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`); + }; + spawnedProcess.on("error", () => { + }); + if (!spawnedProcess.pid) { + let failed; + const failedPromise = new Promise((f, r) => failed = f); + spawnedProcess.once("error", (error2) => { + failed(new Error("Failed to launch: " + error2)); + }); + return cleanup().then(() => failedPromise).then((e) => Promise.reject(e)); + } + options2.log(` pid=${spawnedProcess.pid}`); + const stdout = createInterface({ input: spawnedProcess.stdout }); + stdout.on("line", (data2) => { + options2.log(`[pid=${spawnedProcess.pid}][out] ` + data2); + }); + const stderr = createInterface({ input: spawnedProcess.stderr }); + stderr.on("line", (data2) => { + options2.log(`[pid=${spawnedProcess.pid}][err] ` + data2); + }); + let processClosed = false; + let fulfillCleanup = () => { + }; + const waitForCleanup = new Promise((f) => fulfillCleanup = f); + spawnedProcess.once("close", (exitCode, signal) => { + options2.log(`[pid=${spawnedProcess.pid}] `); + processClosed = true; + gracefullyCloseSet.delete(gracefullyClose); + killSet.delete(killProcessAndCleanup); + removeProcessHandlersIfNeeded(); + options2.onExit(exitCode, signal); + cleanup().then(fulfillCleanup); + }); + addProcessHandlerIfNeeded("exit"); + if (options2.handleSIGINT) + addProcessHandlerIfNeeded("SIGINT"); + if (options2.handleSIGTERM) + addProcessHandlerIfNeeded("SIGTERM"); + if (options2.handleSIGHUP) + addProcessHandlerIfNeeded("SIGHUP"); + gracefullyCloseSet.add(gracefullyClose); + killSet.add(killProcessAndCleanup); + let gracefullyClosing = false; + async function gracefullyClose() { + if (gracefullyClosing) { + options2.log(`[pid=${spawnedProcess.pid}] `); + killProcess(); + await waitForCleanup; + return; + } + gracefullyClosing = true; + options2.log(`[pid=${spawnedProcess.pid}] `); + await options2.attemptToGracefullyClose().catch(() => killProcess()); + await waitForCleanup; + options2.log(`[pid=${spawnedProcess.pid}] `); + } + function killProcess() { + gracefullyCloseSet.delete(gracefullyClose); + killSet.delete(killProcessAndCleanup); + removeProcessHandlersIfNeeded(); + options2.log(`[pid=${spawnedProcess.pid}] `); + if (spawnedProcess.pid && !spawnedProcess.killed && !processClosed) { + options2.log(`[pid=${spawnedProcess.pid}] `); + try { + if (process.platform === "win32") { + const taskkillProcess = spawnSync(`taskkill /pid ${spawnedProcess.pid} /T /F`, { shell: true }); + const [stdout2, stderr2] = [taskkillProcess.stdout.toString(), taskkillProcess.stderr.toString()]; + if (stdout2) + options2.log(`[pid=${spawnedProcess.pid}] taskkill stdout: ${stdout2}`); + if (stderr2) + options2.log(`[pid=${spawnedProcess.pid}] taskkill stderr: ${stderr2}`); + } else { + process.kill(-spawnedProcess.pid, "SIGKILL"); + } + } catch (e) { + options2.log(`[pid=${spawnedProcess.pid}] exception while trying to kill process: ${e}`); + } + } else { + options2.log(`[pid=${spawnedProcess.pid}] `); + } + } + function killProcessAndCleanup() { + killProcess(); + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + for (const dir of options2.tempDirectories) { + try { + fs.rmSync(dir, { force: true, recursive: true, maxRetries: 5 }); + } catch (e) { + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${dir}: ${e}`); + } + } + options2.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`); + } + function killAndWait() { + killProcess(); + return waitForCleanup; + } + return { launchedProcess: spawnedProcess, gracefullyClose, kill: killAndWait }; +} +function envArrayToObject(env) { + const result = {}; + for (const { name, value } of env) + result[name] = value; + return result; +} +define_process_env_default.PWTEST_PROFILE_DIR || ""; +class SocksConnection { + constructor(uid, socket, client) { + this._buffer = Buffer.from([]); + this._offset = 0; + this._fence = 0; + this._uid = uid; + this._socket = socket; + this._client = client; + this._boundOnData = this._onData.bind(this); + socket.on("data", this._boundOnData); + socket.on("close", () => this._onClose()); + socket.on("end", () => this._onClose()); + socket.on("error", () => this._onClose()); + this._run().catch(() => this._socket.end()); + } + async _run() { + assert(await this._authenticate()); + const { command: command2, host, port } = await this._parseRequest(); + if (command2 !== 1) { + this._writeBytes(Buffer.from([ + 5, + 7, + 0, + // RSV + 1, + // IPv4 + 0, + 0, + 0, + 0, + // Address + 0, + 0 + // Port + ])); + return; + } + this._socket.off("data", this._boundOnData); + this._client.onSocketRequested({ uid: this._uid, host, port }); + } + async _authenticate() { + const version2 = await this._readByte(); + assert(version2 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version2); + const nMethods = await this._readByte(); + assert(nMethods, "No authentication methods specified"); + const methods = await this._readBytes(nMethods); + for (const method of methods) { + if (method === 0) { + this._writeBytes(Buffer.from([version2, method])); + return true; + } + } + this._writeBytes(Buffer.from([ + version2, + 255 + /* NO_ACCEPTABLE_METHODS */ + ])); + return false; + } + async _parseRequest() { + const version2 = await this._readByte(); + assert(version2 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version2); + const command2 = await this._readByte(); + await this._readByte(); + const addressType = await this._readByte(); + let host = ""; + switch (addressType) { + case 1: + host = (await this._readBytes(4)).join("."); + break; + case 3: + const length = await this._readByte(); + host = (await this._readBytes(length)).toString(); + break; + case 4: + const bytes = await this._readBytes(16); + const tokens = []; + for (let i = 0; i < 8; ++i) + tokens.push(bytes.readUInt16BE(i * 2).toString(16)); + host = tokens.join(":"); + break; + } + const port = (await this._readBytes(2)).readUInt16BE(0); + this._buffer = Buffer.from([]); + this._offset = 0; + this._fence = 0; + return { + command: command2, + host, + port + }; + } + async _readByte() { + const buffer2 = await this._readBytes(1); + return buffer2[0]; + } + async _readBytes(length) { + this._fence = this._offset + length; + if (!this._buffer || this._buffer.length < this._fence) + await new Promise((f) => this._fenceCallback = f); + this._offset += length; + return this._buffer.slice(this._offset - length, this._offset); + } + _writeBytes(buffer2) { + if (this._socket.writable) + this._socket.write(buffer2); + } + _onClose() { + this._client.onSocketClosed({ uid: this._uid }); + } + _onData(buffer2) { + this._buffer = Buffer.concat([this._buffer, buffer2]); + if (this._fenceCallback && this._buffer.length >= this._fence) { + const callback = this._fenceCallback; + this._fenceCallback = void 0; + callback(); + } + } + socketConnected(host, port) { + this._writeBytes(Buffer.from([ + 5, + 0, + 0, + // RSV + ...ipToSocksAddress(host), + // ATYP, Address + port >> 8, + port & 255 + // Port + ])); + this._socket.on("data", (data2) => this._client.onSocketData({ uid: this._uid, data: data2 })); + } + socketFailed(errorCode) { + const buffer2 = Buffer.from([ + 5, + 0, + 0, + // RSV + ...ipToSocksAddress("0.0.0.0"), + // ATYP, Address + 0, + 0 + // Port + ]); + switch (errorCode) { + case "ENOENT": + case "ENOTFOUND": + case "ETIMEDOUT": + case "EHOSTUNREACH": + buffer2[1] = 4; + break; + case "ENETUNREACH": + buffer2[1] = 3; + break; + case "ECONNREFUSED": + buffer2[1] = 5; + break; + case "ERULESET": + buffer2[1] = 2; + break; + } + this._writeBytes(buffer2); + this._socket.end(); + } + sendData(data2) { + this._socket.write(data2); + } + end() { + this._socket.end(); + } + error(error2) { + this._socket.destroy(new Error(error2)); + } +} +function hexToNumber(hex) { + return [...hex].reduce((value, digit2) => { + const code = digit2.charCodeAt(0); + if (code >= 48 && code <= 57) + return value + code; + if (code >= 97 && code <= 102) + return value + (code - 97) + 10; + if (code >= 65 && code <= 70) + return value + (code - 65) + 10; + throw new Error("Invalid IPv6 token " + hex); + }, 0); +} +function ipToSocksAddress(address) { + if (net.isIPv4(address)) { + return [ + 1, + // IPv4 + ...address.split(".", 4).map((t) => +t & 255) + // Address + ]; + } + if (net.isIPv6(address)) { + const result = [4]; + const tokens = address.split(":", 8); + while (tokens.length < 8) + tokens.unshift(""); + for (const token of tokens) { + const value = hexToNumber(token); + result.push(value >> 8 & 255, value & 255); + } + return result; + } + throw new Error("Only IPv4 and IPv6 addresses are supported"); +} +function starMatchToRegex(pattern) { + const source2 = pattern.split("*").map((s) => { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + }).join(".*"); + return new RegExp("^" + source2 + "$"); +} +function parsePattern(pattern) { + if (!pattern) + return () => false; + const matchers = pattern.split(",").map((token) => { + const match = token.match(/^(.*?)(?::(\d+))?$/); + if (!match) + throw new Error(`Unsupported token "${token}" in pattern "${pattern}"`); + const tokenPort = match[2] ? +match[2] : void 0; + const portMatches = (port) => tokenPort === void 0 || tokenPort === port; + let tokenHost = match[1]; + if (tokenHost === "") { + return (host, port) => { + if (!portMatches(port)) + return false; + return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]"; + }; + } + if (tokenHost === "*") + return (host, port) => portMatches(port); + if (net.isIPv4(tokenHost) || net.isIPv6(tokenHost)) + return (host, port) => host === tokenHost && portMatches(port); + if (tokenHost[0] === ".") + tokenHost = "*" + tokenHost; + const tokenRegex = starMatchToRegex(tokenHost); + return (host, port) => { + if (!portMatches(port)) + return false; + if (net.isIPv4(host) || net.isIPv6(host)) + return false; + return !!host.match(tokenRegex); + }; + }); + return (host, port) => matchers.some((matcher) => matcher(host, port)); +} +const _SocksProxy = class _SocksProxy2 extends EventEmitter$1 { + constructor() { + super(); + this._connections = /* @__PURE__ */ new Map(); + this._sockets = /* @__PURE__ */ new Set(); + this._closed = false; + this._patternMatcher = () => false; + this._directSockets = /* @__PURE__ */ new Map(); + this._server = new net.Server((socket) => { + const uid = createGuid(); + const connection = new SocksConnection(uid, socket, this); + this._connections.set(uid, connection); + }); + this._server.on("connection", (socket) => { + if (this._closed) { + socket.destroy(); + return; + } + this._sockets.add(socket); + socket.once("close", () => this._sockets.delete(socket)); + }); + } + setPattern(pattern) { + try { + this._patternMatcher = parsePattern(pattern); + } catch (e) { + this._patternMatcher = () => false; + } + } + async _handleDirect(request2) { + var _a2, _b2; + try { + const socket = await createSocket(request2.host, request2.port); + socket.on("data", (data2) => { + var _a3; + return (_a3 = this._connections.get(request2.uid)) == null ? void 0 : _a3.sendData(data2); + }); + socket.on("error", (error2) => { + var _a3; + (_a3 = this._connections.get(request2.uid)) == null ? void 0 : _a3.error(error2.message); + this._directSockets.delete(request2.uid); + }); + socket.on("end", () => { + var _a3; + (_a3 = this._connections.get(request2.uid)) == null ? void 0 : _a3.end(); + this._directSockets.delete(request2.uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._directSockets.set(request2.uid, socket); + (_a2 = this._connections.get(request2.uid)) == null ? void 0 : _a2.socketConnected(localAddress, localPort); + } catch (error2) { + (_b2 = this._connections.get(request2.uid)) == null ? void 0 : _b2.socketFailed(error2.code); + } + } + port() { + return this._port; + } + async listen(port, hostname) { + return new Promise((f) => { + this._server.listen(port, hostname, () => { + const port2 = this._server.address().port; + this._port = port2; + f(port2); + }); + }); + } + async close() { + if (this._closed) + return; + this._closed = true; + for (const socket of this._sockets) + socket.destroy(); + this._sockets.clear(); + await new Promise((f) => this._server.close(f)); + } + onSocketRequested(payload) { + if (!this._patternMatcher(payload.host, payload.port)) { + this._handleDirect(payload); + return; + } + this.emit(_SocksProxy2.Events.SocksRequested, payload); + } + onSocketData(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.write(payload.data); + return; + } + this.emit(_SocksProxy2.Events.SocksData, payload); + } + onSocketClosed(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.destroy(); + this._directSockets.delete(payload.uid); + return; + } + this.emit(_SocksProxy2.Events.SocksClosed, payload); + } + socketConnected({ uid, host, port }) { + var _a2; + (_a2 = this._connections.get(uid)) == null ? void 0 : _a2.socketConnected(host, port); + } + socketFailed({ uid, errorCode }) { + var _a2; + (_a2 = this._connections.get(uid)) == null ? void 0 : _a2.socketFailed(errorCode); + } + sendSocketData({ uid, data: data2 }) { + var _a2; + (_a2 = this._connections.get(uid)) == null ? void 0 : _a2.sendData(data2); + } + sendSocketEnd({ uid }) { + var _a2; + (_a2 = this._connections.get(uid)) == null ? void 0 : _a2.end(); + } + sendSocketError({ uid, error: error2 }) { + var _a2; + (_a2 = this._connections.get(uid)) == null ? void 0 : _a2.error(error2); + } +}; +_SocksProxy.Events = { + SocksRequested: "socksRequested", + SocksData: "socksData", + SocksClosed: "socksClosed" +}; +let SocksProxy = _SocksProxy; +const _SocksProxyHandler = class _SocksProxyHandler2 extends EventEmitter$1 { + constructor(pattern, redirectPortForTest) { + super(); + this._sockets = /* @__PURE__ */ new Map(); + this._patternMatcher = () => false; + this._patternMatcher = parsePattern(pattern); + this._redirectPortForTest = redirectPortForTest; + } + cleanup() { + for (const uid of this._sockets.keys()) + this.socketClosed({ uid }); + } + async socketRequested({ uid, host, port }) { + debugLogger.log("socks", `[${uid}] => request ${host}:${port}`); + if (!this._patternMatcher(host, port)) { + const payload = { uid, errorCode: "ERULESET" }; + debugLogger.log("socks", `[${uid}] <= pattern error ${payload.errorCode}`); + this.emit(_SocksProxyHandler2.Events.SocksFailed, payload); + return; + } + if (host === "local.playwright") + host = "localhost"; + try { + if (this._redirectPortForTest) + port = this._redirectPortForTest; + const socket = await createSocket(host, port); + socket.on("data", (data2) => { + const payload2 = { uid, data: data2 }; + this.emit(_SocksProxyHandler2.Events.SocksData, payload2); + }); + socket.on("error", (error2) => { + const payload2 = { uid, error: error2.message }; + debugLogger.log("socks", `[${uid}] <= network socket error ${payload2.error}`); + this.emit(_SocksProxyHandler2.Events.SocksError, payload2); + this._sockets.delete(uid); + }); + socket.on("end", () => { + const payload2 = { uid }; + debugLogger.log("socks", `[${uid}] <= network socket closed`); + this.emit(_SocksProxyHandler2.Events.SocksEnd, payload2); + this._sockets.delete(uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._sockets.set(uid, socket); + const payload = { uid, host: localAddress, port: localPort }; + debugLogger.log("socks", `[${uid}] <= connected to network ${payload.host}:${payload.port}`); + this.emit(_SocksProxyHandler2.Events.SocksConnected, payload); + } catch (error2) { + const payload = { uid, errorCode: error2.code }; + debugLogger.log("socks", `[${uid}] <= connect error ${payload.errorCode}`); + this.emit(_SocksProxyHandler2.Events.SocksFailed, payload); + } + } + sendSocketData({ uid, data: data2 }) { + var _a2; + (_a2 = this._sockets.get(uid)) == null ? void 0 : _a2.write(data2); + } + socketClosed({ uid }) { + var _a2; + debugLogger.log("socks", `[${uid}] <= browser socket closed`); + (_a2 = this._sockets.get(uid)) == null ? void 0 : _a2.destroy(); + this._sockets.delete(uid); + } +}; +_SocksProxyHandler.Events = { + SocksConnected: "socksConnected", + SocksData: "socksData", + SocksError: "socksError", + SocksFailed: "socksFailed", + SocksEnd: "socksEnd" +}; +let SocksProxyHandler = _SocksProxyHandler; +function makeWaitForNextTask() { + if (process.versions.electron) + return (callback) => setTimeout(callback, 0); + if (parseInt(process.versions.node, 10) >= 11) + return setImmediate; + let spinning = false; + const callbacks = []; + const loop = () => { + const callback = callbacks.shift(); + if (!callback) { + spinning = false; + return; + } + setImmediate(loop); + callback(); + }; + return (callback) => { + callbacks.push(callback); + if (!spinning) { + spinning = true; + setImmediate(loop); + } + }; +} +class ZipFile { + constructor(fileName) { + this._entries = /* @__PURE__ */ new Map(); + this._fileName = fileName; + this._openedPromise = this._open(); + } + async _open() { + await new Promise((fulfill, reject) => { + yauzl.open(this._fileName, { autoClose: false }, (e, z) => { + if (e) { + reject(e); + return; + } + this._zipFile = z; + this._zipFile.on("entry", (entry) => { + this._entries.set(entry.fileName, entry); + }); + this._zipFile.on("end", fulfill); + }); + }); + } + async entries() { + await this._openedPromise; + return [...this._entries.keys()]; + } + async read(entryPath) { + await this._openedPromise; + const entry = this._entries.get(entryPath); + if (!entry) + throw new Error(`${entryPath} not found in file ${this._fileName}`); + return new Promise((resolve, reject) => { + this._zipFile.openReadStream(entry, (error2, readStream) => { + if (error2 || !readStream) { + reject(error2 || "Entry not found"); + return; + } + const buffers = []; + readStream.on("data", (data2) => buffers.push(data2)); + readStream.on("end", () => resolve(Buffer.concat(buffers))); + }); + }); + } + close() { + var _a2; + (_a2 = this._zipFile) == null ? void 0 : _a2.close(); + } +} +const PACKAGE_PATH = path.join("playwright/packages/playwright-core/src/server/registry", "..", "..", ".."); +const BIN_PATH = path.join("playwright/packages/playwright-core/src/server/registry", "..", "..", "..", "bin"); +const PLAYWRIGHT_CDN_MIRRORS = [ + "https://cdn.playwright.dev/dbazure/download/playwright", + // ESRP CDN + "https://playwright.download.prss.microsoft.com/dbazure/download/playwright", + // Directly hit ESRP CDN + "https://cdn.playwright.dev" + // Hit the Storage Bucket directly +]; +if (define_process_env_default.PW_TEST_CDN_THAT_SHOULD_WORK) { + for (let i = 0; i < PLAYWRIGHT_CDN_MIRRORS.length; i++) { + const cdn = PLAYWRIGHT_CDN_MIRRORS[i]; + if (cdn !== define_process_env_default.PW_TEST_CDN_THAT_SHOULD_WORK) { + const parsedCDN = new URL(cdn); + parsedCDN.hostname = parsedCDN.hostname + ".does-not-resolve.playwright.dev"; + PLAYWRIGHT_CDN_MIRRORS[i] = parsedCDN.toString(); + } + } +} +const EXECUTABLE_PATHS = { + "chromium": { + "linux": ["chrome-linux", "chrome"], + "mac": ["chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium"], + "win": ["chrome-win", "chrome.exe"] + }, + "chromium-headless-shell": { + "linux": ["chrome-linux", "headless_shell"], + "mac": ["chrome-mac", "headless_shell"], + "win": ["chrome-win", "headless_shell.exe"] + }, + "firefox": { + "linux": ["firefox", "firefox"], + "mac": ["firefox", "Nightly.app", "Contents", "MacOS", "firefox"], + "win": ["firefox", "firefox.exe"] + }, + "webkit": { + "linux": ["pw_run.sh"], + "mac": ["pw_run.sh"], + "win": ["Playwright.exe"] + }, + "ffmpeg": { + "linux": ["ffmpeg-linux"], + "mac": ["ffmpeg-mac"], + "win": ["ffmpeg-win64.exe"] + }, + "winldd": { + "linux": void 0, + "mac": void 0, + "win": ["PrintDeps.exe"] + } +}; +const DOWNLOAD_PATHS = { + "chromium": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/chromium/%s/chromium-linux.zip", + "ubuntu22.04-x64": "builds/chromium/%s/chromium-linux.zip", + "ubuntu24.04-x64": "builds/chromium/%s/chromium-linux.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "ubuntu22.04-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "ubuntu24.04-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "debian11-x64": "builds/chromium/%s/chromium-linux.zip", + "debian11-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "debian12-x64": "builds/chromium/%s/chromium-linux.zip", + "debian12-arm64": "builds/chromium/%s/chromium-linux-arm64.zip", + "mac10.13": "builds/chromium/%s/chromium-mac.zip", + "mac10.14": "builds/chromium/%s/chromium-mac.zip", + "mac10.15": "builds/chromium/%s/chromium-mac.zip", + "mac11": "builds/chromium/%s/chromium-mac.zip", + "mac11-arm64": "builds/chromium/%s/chromium-mac-arm64.zip", + "mac12": "builds/chromium/%s/chromium-mac.zip", + "mac12-arm64": "builds/chromium/%s/chromium-mac-arm64.zip", + "mac13": "builds/chromium/%s/chromium-mac.zip", + "mac13-arm64": "builds/chromium/%s/chromium-mac-arm64.zip", + "mac14": "builds/chromium/%s/chromium-mac.zip", + "mac14-arm64": "builds/chromium/%s/chromium-mac-arm64.zip", + "mac15": "builds/chromium/%s/chromium-mac.zip", + "mac15-arm64": "builds/chromium/%s/chromium-mac-arm64.zip", + "win64": "builds/chromium/%s/chromium-win64.zip" + }, + "chromium-headless-shell": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/chromium/%s/chromium-headless-shell-linux.zip", + "ubuntu22.04-x64": "builds/chromium/%s/chromium-headless-shell-linux.zip", + "ubuntu24.04-x64": "builds/chromium/%s/chromium-headless-shell-linux.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "ubuntu22.04-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "ubuntu24.04-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "debian11-x64": "builds/chromium/%s/chromium-headless-shell-linux.zip", + "debian11-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "debian12-x64": "builds/chromium/%s/chromium-headless-shell-linux.zip", + "debian12-arm64": "builds/chromium/%s/chromium-headless-shell-linux-arm64.zip", + "mac10.13": void 0, + "mac10.14": void 0, + "mac10.15": void 0, + "mac11": "builds/chromium/%s/chromium-headless-shell-mac.zip", + "mac11-arm64": "builds/chromium/%s/chromium-headless-shell-mac-arm64.zip", + "mac12": "builds/chromium/%s/chromium-headless-shell-mac.zip", + "mac12-arm64": "builds/chromium/%s/chromium-headless-shell-mac-arm64.zip", + "mac13": "builds/chromium/%s/chromium-headless-shell-mac.zip", + "mac13-arm64": "builds/chromium/%s/chromium-headless-shell-mac-arm64.zip", + "mac14": "builds/chromium/%s/chromium-headless-shell-mac.zip", + "mac14-arm64": "builds/chromium/%s/chromium-headless-shell-mac-arm64.zip", + "mac15": "builds/chromium/%s/chromium-headless-shell-mac.zip", + "mac15-arm64": "builds/chromium/%s/chromium-headless-shell-mac-arm64.zip", + "win64": "builds/chromium/%s/chromium-headless-shell-win64.zip" + }, + "chromium-tip-of-tree": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux.zip", + "ubuntu22.04-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux.zip", + "ubuntu24.04-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "ubuntu22.04-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "ubuntu24.04-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "debian11-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux.zip", + "debian11-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "debian12-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux.zip", + "debian12-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-linux-arm64.zip", + "mac10.13": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac10.14": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac10.15": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac11": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac11-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac-arm64.zip", + "mac12": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac12-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac-arm64.zip", + "mac13": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac13-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac-arm64.zip", + "mac14": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac14-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac-arm64.zip", + "mac15": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac.zip", + "mac15-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-mac-arm64.zip", + "win64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-win64.zip" + }, + "chromium-tip-of-tree-headless-shell": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux.zip", + "ubuntu22.04-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux.zip", + "ubuntu24.04-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "ubuntu22.04-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "ubuntu24.04-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "debian11-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux.zip", + "debian11-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "debian12-x64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux.zip", + "debian12-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-linux-arm64.zip", + "mac10.13": void 0, + "mac10.14": void 0, + "mac10.15": void 0, + "mac11": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac.zip", + "mac11-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac-arm64.zip", + "mac12": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac.zip", + "mac12-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac-arm64.zip", + "mac13": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac.zip", + "mac13-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac-arm64.zip", + "mac14": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac.zip", + "mac14-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac-arm64.zip", + "mac15": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac.zip", + "mac15-arm64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-mac-arm64.zip", + "win64": "builds/chromium-tip-of-tree/%s/chromium-tip-of-tree-headless-shell-win64.zip" + }, + "firefox": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/firefox/%s/firefox-ubuntu-20.04.zip", + "ubuntu22.04-x64": "builds/firefox/%s/firefox-ubuntu-22.04.zip", + "ubuntu24.04-x64": "builds/firefox/%s/firefox-ubuntu-24.04.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/firefox/%s/firefox-ubuntu-20.04-arm64.zip", + "ubuntu22.04-arm64": "builds/firefox/%s/firefox-ubuntu-22.04-arm64.zip", + "ubuntu24.04-arm64": "builds/firefox/%s/firefox-ubuntu-24.04-arm64.zip", + "debian11-x64": "builds/firefox/%s/firefox-debian-11.zip", + "debian11-arm64": "builds/firefox/%s/firefox-debian-11-arm64.zip", + "debian12-x64": "builds/firefox/%s/firefox-debian-12.zip", + "debian12-arm64": "builds/firefox/%s/firefox-debian-12-arm64.zip", + "mac10.13": "builds/firefox/%s/firefox-mac.zip", + "mac10.14": "builds/firefox/%s/firefox-mac.zip", + "mac10.15": "builds/firefox/%s/firefox-mac.zip", + "mac11": "builds/firefox/%s/firefox-mac.zip", + "mac11-arm64": "builds/firefox/%s/firefox-mac-arm64.zip", + "mac12": "builds/firefox/%s/firefox-mac.zip", + "mac12-arm64": "builds/firefox/%s/firefox-mac-arm64.zip", + "mac13": "builds/firefox/%s/firefox-mac.zip", + "mac13-arm64": "builds/firefox/%s/firefox-mac-arm64.zip", + "mac14": "builds/firefox/%s/firefox-mac.zip", + "mac14-arm64": "builds/firefox/%s/firefox-mac-arm64.zip", + "mac15": "builds/firefox/%s/firefox-mac.zip", + "mac15-arm64": "builds/firefox/%s/firefox-mac-arm64.zip", + "win64": "builds/firefox/%s/firefox-win64.zip" + }, + "firefox-beta": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/firefox-beta/%s/firefox-beta-ubuntu-20.04.zip", + "ubuntu22.04-x64": "builds/firefox-beta/%s/firefox-beta-ubuntu-22.04.zip", + "ubuntu24.04-x64": "builds/firefox-beta/%s/firefox-beta-ubuntu-24.04.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": void 0, + "ubuntu22.04-arm64": "builds/firefox-beta/%s/firefox-beta-ubuntu-22.04-arm64.zip", + "ubuntu24.04-arm64": "builds/firefox-beta/%s/firefox-beta-ubuntu-24.04-arm64.zip", + "debian11-x64": "builds/firefox-beta/%s/firefox-beta-debian-11.zip", + "debian11-arm64": "builds/firefox-beta/%s/firefox-beta-debian-11-arm64.zip", + "debian12-x64": "builds/firefox-beta/%s/firefox-beta-debian-12.zip", + "debian12-arm64": "builds/firefox-beta/%s/firefox-beta-debian-12-arm64.zip", + "mac10.13": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac10.14": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac10.15": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac11": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac11-arm64": "builds/firefox-beta/%s/firefox-beta-mac-arm64.zip", + "mac12": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac12-arm64": "builds/firefox-beta/%s/firefox-beta-mac-arm64.zip", + "mac13": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac13-arm64": "builds/firefox-beta/%s/firefox-beta-mac-arm64.zip", + "mac14": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac14-arm64": "builds/firefox-beta/%s/firefox-beta-mac-arm64.zip", + "mac15": "builds/firefox-beta/%s/firefox-beta-mac.zip", + "mac15-arm64": "builds/firefox-beta/%s/firefox-beta-mac-arm64.zip", + "win64": "builds/firefox-beta/%s/firefox-beta-win64.zip" + }, + "webkit": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/webkit/%s/webkit-ubuntu-20.04.zip", + "ubuntu22.04-x64": "builds/webkit/%s/webkit-ubuntu-22.04.zip", + "ubuntu24.04-x64": "builds/webkit/%s/webkit-ubuntu-24.04.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/webkit/%s/webkit-ubuntu-20.04-arm64.zip", + "ubuntu22.04-arm64": "builds/webkit/%s/webkit-ubuntu-22.04-arm64.zip", + "ubuntu24.04-arm64": "builds/webkit/%s/webkit-ubuntu-24.04-arm64.zip", + "debian11-x64": "builds/webkit/%s/webkit-debian-11.zip", + "debian11-arm64": "builds/webkit/%s/webkit-debian-11-arm64.zip", + "debian12-x64": "builds/webkit/%s/webkit-debian-12.zip", + "debian12-arm64": "builds/webkit/%s/webkit-debian-12-arm64.zip", + "mac10.13": void 0, + "mac10.14": "builds/deprecated-webkit-mac-10.14/%s/deprecated-webkit-mac-10.14.zip", + "mac10.15": "builds/deprecated-webkit-mac-10.15/%s/deprecated-webkit-mac-10.15.zip", + "mac11": "builds/webkit/%s/webkit-mac-11.zip", + "mac11-arm64": "builds/webkit/%s/webkit-mac-11-arm64.zip", + "mac12": "builds/webkit/%s/webkit-mac-12.zip", + "mac12-arm64": "builds/webkit/%s/webkit-mac-12-arm64.zip", + "mac13": "builds/webkit/%s/webkit-mac-13.zip", + "mac13-arm64": "builds/webkit/%s/webkit-mac-13-arm64.zip", + "mac14": "builds/webkit/%s/webkit-mac-14.zip", + "mac14-arm64": "builds/webkit/%s/webkit-mac-14-arm64.zip", + "mac15": "builds/webkit/%s/webkit-mac-15.zip", + "mac15-arm64": "builds/webkit/%s/webkit-mac-15-arm64.zip", + "win64": "builds/webkit/%s/webkit-win64.zip" + }, + "ffmpeg": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/ffmpeg/%s/ffmpeg-linux.zip", + "ubuntu22.04-x64": "builds/ffmpeg/%s/ffmpeg-linux.zip", + "ubuntu24.04-x64": "builds/ffmpeg/%s/ffmpeg-linux.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/ffmpeg/%s/ffmpeg-linux-arm64.zip", + "ubuntu22.04-arm64": "builds/ffmpeg/%s/ffmpeg-linux-arm64.zip", + "ubuntu24.04-arm64": "builds/ffmpeg/%s/ffmpeg-linux-arm64.zip", + "debian11-x64": "builds/ffmpeg/%s/ffmpeg-linux.zip", + "debian11-arm64": "builds/ffmpeg/%s/ffmpeg-linux-arm64.zip", + "debian12-x64": "builds/ffmpeg/%s/ffmpeg-linux.zip", + "debian12-arm64": "builds/ffmpeg/%s/ffmpeg-linux-arm64.zip", + "mac10.13": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac10.14": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac10.15": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac11": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac11-arm64": "builds/ffmpeg/%s/ffmpeg-mac-arm64.zip", + "mac12": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac12-arm64": "builds/ffmpeg/%s/ffmpeg-mac-arm64.zip", + "mac13": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac13-arm64": "builds/ffmpeg/%s/ffmpeg-mac-arm64.zip", + "mac14": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac14-arm64": "builds/ffmpeg/%s/ffmpeg-mac-arm64.zip", + "mac15": "builds/ffmpeg/%s/ffmpeg-mac.zip", + "mac15-arm64": "builds/ffmpeg/%s/ffmpeg-mac-arm64.zip", + "win64": "builds/ffmpeg/%s/ffmpeg-win64.zip" + }, + "winldd": { + "": void 0, + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": void 0, + "ubuntu22.04-x64": void 0, + "ubuntu24.04-x64": void 0, + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": void 0, + "ubuntu22.04-arm64": void 0, + "ubuntu24.04-arm64": void 0, + "debian11-x64": void 0, + "debian11-arm64": void 0, + "debian12-x64": void 0, + "debian12-arm64": void 0, + "mac10.13": void 0, + "mac10.14": void 0, + "mac10.15": void 0, + "mac11": void 0, + "mac11-arm64": void 0, + "mac12": void 0, + "mac12-arm64": void 0, + "mac13": void 0, + "mac13-arm64": void 0, + "mac14": void 0, + "mac14-arm64": void 0, + "mac15": void 0, + "mac15-arm64": void 0, + "win64": "builds/winldd/%s/winldd-win64.zip" + }, + "android": { + "": "builds/android/%s/android.zip", + "ubuntu18.04-x64": void 0, + "ubuntu20.04-x64": "builds/android/%s/android.zip", + "ubuntu22.04-x64": "builds/android/%s/android.zip", + "ubuntu24.04-x64": "builds/android/%s/android.zip", + "ubuntu18.04-arm64": void 0, + "ubuntu20.04-arm64": "builds/android/%s/android.zip", + "ubuntu22.04-arm64": "builds/android/%s/android.zip", + "ubuntu24.04-arm64": "builds/android/%s/android.zip", + "debian11-x64": "builds/android/%s/android.zip", + "debian11-arm64": "builds/android/%s/android.zip", + "debian12-x64": "builds/android/%s/android.zip", + "debian12-arm64": "builds/android/%s/android.zip", + "mac10.13": "builds/android/%s/android.zip", + "mac10.14": "builds/android/%s/android.zip", + "mac10.15": "builds/android/%s/android.zip", + "mac11": "builds/android/%s/android.zip", + "mac11-arm64": "builds/android/%s/android.zip", + "mac12": "builds/android/%s/android.zip", + "mac12-arm64": "builds/android/%s/android.zip", + "mac13": "builds/android/%s/android.zip", + "mac13-arm64": "builds/android/%s/android.zip", + "mac14": "builds/android/%s/android.zip", + "mac14-arm64": "builds/android/%s/android.zip", + "mac15": "builds/android/%s/android.zip", + "mac15-arm64": "builds/android/%s/android.zip", + "win64": "builds/android/%s/android.zip" + }, + // TODO(bidi): implement downloads. + "bidi": {} +}; +const registryDirectory = (() => { + let result; + const envDefined = getFromENV("PLAYWRIGHT_BROWSERS_PATH"); + if (envDefined === "0") { + result = path.join("playwright/packages/playwright-core/src/server/registry", "..", "..", "..", ".local-browsers"); + } else if (envDefined) { + result = envDefined; + } else { + let cacheDirectory; + if (process.platform === "linux") + cacheDirectory = define_process_env_default.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"); + else if (process.platform === "darwin") + cacheDirectory = path.join(os.homedir(), "Library", "Caches"); + else if (process.platform === "win32") + cacheDirectory = define_process_env_default.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"); + else + throw new Error("Unsupported platform: " + process.platform); + result = path.join(cacheDirectory, "ms-playwright"); + } + if (!path.isAbsolute(result)) { + result = path.resolve(getFromENV("INIT_CWD") || process.cwd(), result); + } + return result; +})(); +function isBrowserDirectory(browserDirectory) { + const baseName = path.basename(browserDirectory); + for (const browserName of allDownloadable) { + if (baseName.startsWith(browserName.replace(/-/g, "_") + "-")) + return true; + } + return false; +} +function readDescriptors(browsersJSON) { + return browsersJSON["browsers"].map((obj) => { + const name = obj.name; + const revisionOverride = (obj.revisionOverrides || {})[hostPlatform]; + const revision = revisionOverride || obj.revision; + const browserDirectoryPrefix = revisionOverride ? `${name}_${hostPlatform}_special` : `${name}`; + const descriptor = { + name, + revision, + hasRevisionOverride: !!revisionOverride, + // We only put browser version for the supported operating systems. + browserVersion: revisionOverride ? void 0 : obj.browserVersion, + installByDefault: !!obj.installByDefault, + // Method `isBrowserDirectory` determines directory to be browser iff + // it starts with some browser name followed by '-'. Some browser names + // are prefixes of others, e.g. 'webkit' is a prefix of `webkit-technology-preview`. + // To avoid older registries erroneously removing 'webkit-technology-preview', we have to + // ensure that browser folders to never include dashes inside. + dir: path.join(registryDirectory, browserDirectoryPrefix.replace(/-/g, "_") + "-" + revision) + }; + return descriptor; + }); +} +const allDownloadable = ["android", "chromium", "firefox", "webkit", "ffmpeg", "firefox-beta", "chromium-tip-of-tree", "chromium-headless-shell", "chromium-tip-of-tree-headless-shell"]; +class Registry { + constructor(browsersJSON) { + const descriptors = readDescriptors(browsersJSON); + const findExecutablePath = (dir, name) => { + let tokens = void 0; + if (process.platform === "linux") + tokens = EXECUTABLE_PATHS[name]["linux"]; + else if (process.platform === "darwin") + tokens = EXECUTABLE_PATHS[name]["mac"]; + else if (process.platform === "win32") + tokens = EXECUTABLE_PATHS[name]["win"]; + return tokens ? path.join(dir, ...tokens) : void 0; + }; + const executablePathOrDie = (name, e, installByDefault, sdkLanguage) => { + if (!e) + throw new Error(`${name} is not supported on ${hostPlatform}`); + const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install${installByDefault ? "" : " " + name}`); + if (!canAccessFile(e)) { + const currentDockerVersion = readDockerVersionSync(); + const preferredDockerVersion = currentDockerVersion ? dockerVersion(currentDockerVersion.dockerImageNameTemplate) : null; + const isOutdatedDockerImage = currentDockerVersion && preferredDockerVersion && currentDockerVersion.dockerImageName !== preferredDockerVersion.dockerImageName; + const prettyMessage = isOutdatedDockerImage ? [ + `Looks like ${sdkLanguage === "javascript" ? "Playwright Test or " : ""}Playwright was just updated to ${preferredDockerVersion.driverVersion}.`, + `Please update docker image as well.`, + `- current: ${currentDockerVersion.dockerImageName}`, + `- required: ${preferredDockerVersion.dockerImageName}`, + ``, + `<3 Playwright Team` + ].join("\n") : [ + `Looks like ${sdkLanguage === "javascript" ? "Playwright Test or " : ""}Playwright was just installed or updated.`, + `Please run the following command to download new browser${installByDefault ? "s" : ""}:`, + ``, + ` ${installCommand}`, + ``, + `<3 Playwright Team` + ].join("\n"); + throw new Error(`Executable doesn't exist at ${e} +${wrapInASCIIBox(prettyMessage, 1)}`); + } + return e; + }; + this._executables = []; + const chromium = descriptors.find((d) => d.name === "chromium"); + const chromiumExecutable = findExecutablePath(chromium.dir, "chromium"); + this._executables.push({ + type: "browser", + name: "chromium", + browserName: "chromium", + directory: chromium.dir, + executablePath: () => chromiumExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("chromium", chromiumExecutable, chromium.installByDefault, sdkLanguage), + installType: chromium.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, chromium.dir, ["chrome-linux"], [], ["chrome-win"]), + downloadURLs: this._downloadURLs(chromium), + browserVersion: chromium.browserVersion, + _install: () => this._downloadExecutable(chromium, chromiumExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + const chromiumHeadlessShell = descriptors.find((d) => d.name === "chromium-headless-shell"); + const chromiumHeadlessShellExecutable = findExecutablePath(chromiumHeadlessShell.dir, "chromium-headless-shell"); + this._executables.push({ + type: "channel", + name: "chromium-headless-shell", + browserName: "chromium", + directory: chromiumHeadlessShell.dir, + executablePath: () => chromiumHeadlessShellExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("chromium", chromiumHeadlessShellExecutable, chromiumHeadlessShell.installByDefault, sdkLanguage), + installType: chromiumHeadlessShell.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, chromiumHeadlessShell.dir, ["chrome-linux"], [], ["chrome-win"]), + downloadURLs: this._downloadURLs(chromiumHeadlessShell), + browserVersion: chromium.browserVersion, + _install: () => this._downloadExecutable(chromiumHeadlessShell, chromiumHeadlessShellExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + const chromiumTipOfTreeHeadlessShell = descriptors.find((d) => d.name === "chromium-tip-of-tree-headless-shell"); + const chromiumTipOfTreeHeadlessShellExecutable = findExecutablePath(chromiumTipOfTreeHeadlessShell.dir, "chromium-headless-shell"); + this._executables.push({ + type: "channel", + name: "chromium-tip-of-tree-headless-shell", + browserName: "chromium", + directory: chromiumTipOfTreeHeadlessShell.dir, + executablePath: () => chromiumTipOfTreeHeadlessShellExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("chromium", chromiumTipOfTreeHeadlessShellExecutable, chromiumTipOfTreeHeadlessShell.installByDefault, sdkLanguage), + installType: chromiumTipOfTreeHeadlessShell.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, chromiumTipOfTreeHeadlessShell.dir, ["chrome-linux"], [], ["chrome-win"]), + downloadURLs: this._downloadURLs(chromiumTipOfTreeHeadlessShell), + browserVersion: chromium.browserVersion, + _install: () => this._downloadExecutable(chromiumTipOfTreeHeadlessShell, chromiumTipOfTreeHeadlessShellExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + const chromiumTipOfTree = descriptors.find((d) => d.name === "chromium-tip-of-tree"); + const chromiumTipOfTreeExecutable = findExecutablePath(chromiumTipOfTree.dir, "chromium"); + this._executables.push({ + type: "tool", + name: "chromium-tip-of-tree", + browserName: "chromium", + directory: chromiumTipOfTree.dir, + executablePath: () => chromiumTipOfTreeExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("chromium-tip-of-tree", chromiumTipOfTreeExecutable, chromiumTipOfTree.installByDefault, sdkLanguage), + installType: chromiumTipOfTree.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, chromiumTipOfTree.dir, ["chrome-linux"], [], ["chrome-win"]), + downloadURLs: this._downloadURLs(chromiumTipOfTree), + browserVersion: chromiumTipOfTree.browserVersion, + _install: () => this._downloadExecutable(chromiumTipOfTree, chromiumTipOfTreeExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + this._executables.push(this._createChromiumChannel("chrome", { + "linux": "/opt/google/chrome/chrome", + "darwin": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "win32": `\\Google\\Chrome\\Application\\chrome.exe` + }, () => this._installChromiumChannel("chrome", { + "linux": "reinstall_chrome_stable_linux.sh", + "darwin": "reinstall_chrome_stable_mac.sh", + "win32": "reinstall_chrome_stable_win.ps1" + }))); + this._executables.push(this._createChromiumChannel("chrome-beta", { + "linux": "/opt/google/chrome-beta/chrome", + "darwin": "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta", + "win32": `\\Google\\Chrome Beta\\Application\\chrome.exe` + }, () => this._installChromiumChannel("chrome-beta", { + "linux": "reinstall_chrome_beta_linux.sh", + "darwin": "reinstall_chrome_beta_mac.sh", + "win32": "reinstall_chrome_beta_win.ps1" + }))); + this._executables.push(this._createChromiumChannel("chrome-dev", { + "linux": "/opt/google/chrome-unstable/chrome", + "darwin": "/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev", + "win32": `\\Google\\Chrome Dev\\Application\\chrome.exe` + })); + this._executables.push(this._createChromiumChannel("chrome-canary", { + "linux": "", + "darwin": "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", + "win32": `\\Google\\Chrome SxS\\Application\\chrome.exe` + })); + this._executables.push(this._createChromiumChannel("msedge", { + "linux": "/opt/microsoft/msedge/msedge", + "darwin": "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + "win32": `\\Microsoft\\Edge\\Application\\msedge.exe` + }, () => this._installMSEdgeChannel("msedge", { + "linux": "reinstall_msedge_stable_linux.sh", + "darwin": "reinstall_msedge_stable_mac.sh", + "win32": "reinstall_msedge_stable_win.ps1" + }))); + this._executables.push(this._createChromiumChannel("msedge-beta", { + "linux": "/opt/microsoft/msedge-beta/msedge", + "darwin": "/Applications/Microsoft Edge Beta.app/Contents/MacOS/Microsoft Edge Beta", + "win32": `\\Microsoft\\Edge Beta\\Application\\msedge.exe` + }, () => this._installMSEdgeChannel("msedge-beta", { + "darwin": "reinstall_msedge_beta_mac.sh", + "linux": "reinstall_msedge_beta_linux.sh", + "win32": "reinstall_msedge_beta_win.ps1" + }))); + this._executables.push(this._createChromiumChannel("msedge-dev", { + "linux": "/opt/microsoft/msedge-dev/msedge", + "darwin": "/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev", + "win32": `\\Microsoft\\Edge Dev\\Application\\msedge.exe` + }, () => this._installMSEdgeChannel("msedge-dev", { + "darwin": "reinstall_msedge_dev_mac.sh", + "linux": "reinstall_msedge_dev_linux.sh", + "win32": "reinstall_msedge_dev_win.ps1" + }))); + this._executables.push(this._createChromiumChannel("msedge-canary", { + "linux": "", + "darwin": "/Applications/Microsoft Edge Canary.app/Contents/MacOS/Microsoft Edge Canary", + "win32": `\\Microsoft\\Edge SxS\\Application\\msedge.exe` + })); + this._executables.push(this._createBidiFirefoxChannel("moz-firefox", { + "linux": "/snap/bin/firefox", + "darwin": "/Applications/Firefox.app/Contents/MacOS/firefox", + "win32": "\\Mozilla Firefox\\firefox.exe" + })); + this._executables.push(this._createBidiFirefoxChannel("moz-firefox-beta", { + "linux": "/opt/firefox-beta/firefox", + "darwin": "/Applications/Firefox.app/Contents/MacOS/firefox", + "win32": "\\Mozilla Firefox\\firefox.exe" + })); + this._executables.push(this._createBidiFirefoxChannel("moz-firefox-nightly", { + "linux": "/opt/firefox-nightly/firefox", + "darwin": "/Applications/Firefox Nightly.app/Contents/MacOS/firefox", + "win32": "\\Mozilla Firefox\\firefox.exe" + })); + this._executables.push(this._createBidiChromiumChannel("bidi-chrome-stable", { + "linux": "/opt/google/chrome/chrome", + "darwin": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "win32": `\\Google\\Chrome\\Application\\chrome.exe` + })); + this._executables.push(this._createBidiChromiumChannel("bidi-chrome-canary", { + "linux": "", + "darwin": "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", + "win32": `\\Google\\Chrome SxS\\Application\\chrome.exe` + })); + this._executables.push({ + type: "browser", + name: "bidi-chromium", + browserName: "bidi", + directory: chromium.dir, + executablePath: () => chromiumExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("chromium", chromiumExecutable, chromium.installByDefault, sdkLanguage), + installType: "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, chromium.dir, ["chrome-linux"], [], ["chrome-win"]), + downloadURLs: this._downloadURLs(chromium), + browserVersion: chromium.browserVersion, + _install: () => this._downloadExecutable(chromium, chromiumExecutable), + _dependencyGroup: "chromium", + _isHermeticInstallation: true + }); + const firefox = descriptors.find((d) => d.name === "firefox"); + const firefoxExecutable = findExecutablePath(firefox.dir, "firefox"); + this._executables.push({ + type: "browser", + name: "firefox", + browserName: "firefox", + directory: firefox.dir, + executablePath: () => firefoxExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("firefox", firefoxExecutable, firefox.installByDefault, sdkLanguage), + installType: firefox.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, firefox.dir, ["firefox"], [], ["firefox"]), + downloadURLs: this._downloadURLs(firefox), + browserVersion: firefox.browserVersion, + _install: () => this._downloadExecutable(firefox, firefoxExecutable), + _dependencyGroup: "firefox", + _isHermeticInstallation: true + }); + const firefoxBeta = descriptors.find((d) => d.name === "firefox-beta"); + const firefoxBetaExecutable = findExecutablePath(firefoxBeta.dir, "firefox"); + this._executables.push({ + type: "tool", + name: "firefox-beta", + browserName: "firefox", + directory: firefoxBeta.dir, + executablePath: () => firefoxBetaExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("firefox-beta", firefoxBetaExecutable, firefoxBeta.installByDefault, sdkLanguage), + installType: firefoxBeta.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, firefoxBeta.dir, ["firefox"], [], ["firefox"]), + downloadURLs: this._downloadURLs(firefoxBeta), + browserVersion: firefoxBeta.browserVersion, + _install: () => this._downloadExecutable(firefoxBeta, firefoxBetaExecutable), + _dependencyGroup: "firefox", + _isHermeticInstallation: true + }); + const webkit = descriptors.find((d) => d.name === "webkit"); + const webkitExecutable = findExecutablePath(webkit.dir, "webkit"); + const webkitLinuxLddDirectories = [ + path.join("minibrowser-gtk"), + path.join("minibrowser-gtk", "bin"), + path.join("minibrowser-gtk", "lib"), + path.join("minibrowser-gtk", "sys", "lib"), + path.join("minibrowser-wpe"), + path.join("minibrowser-wpe", "bin"), + path.join("minibrowser-wpe", "lib"), + path.join("minibrowser-wpe", "sys", "lib") + ]; + this._executables.push({ + type: "browser", + name: "webkit", + browserName: "webkit", + directory: webkit.dir, + executablePath: () => webkitExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("webkit", webkitExecutable, webkit.installByDefault, sdkLanguage), + installType: webkit.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: (sdkLanguage) => this._validateHostRequirements(sdkLanguage, webkit.dir, webkitLinuxLddDirectories, ["libGLESv2.so.2", "libx264.so"], [""]), + downloadURLs: this._downloadURLs(webkit), + browserVersion: webkit.browserVersion, + _install: () => this._downloadExecutable(webkit, webkitExecutable), + _dependencyGroup: "webkit", + _isHermeticInstallation: true + }); + const ffmpeg = descriptors.find((d) => d.name === "ffmpeg"); + const ffmpegExecutable = findExecutablePath(ffmpeg.dir, "ffmpeg"); + this._executables.push({ + type: "tool", + name: "ffmpeg", + browserName: void 0, + directory: ffmpeg.dir, + executablePath: () => ffmpegExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("ffmpeg", ffmpegExecutable, ffmpeg.installByDefault, sdkLanguage), + installType: ffmpeg.installByDefault ? "download-by-default" : "download-on-demand", + _validateHostRequirements: () => Promise.resolve(), + downloadURLs: this._downloadURLs(ffmpeg), + _install: () => this._downloadExecutable(ffmpeg, ffmpegExecutable), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + const winldd = descriptors.find((d) => d.name === "winldd"); + const winlddExecutable = findExecutablePath(winldd.dir, "winldd"); + this._executables.push({ + type: "tool", + name: "winldd", + browserName: void 0, + directory: winldd.dir, + executablePath: () => winlddExecutable, + executablePathOrDie: (sdkLanguage) => executablePathOrDie("winldd", winlddExecutable, winldd.installByDefault, sdkLanguage), + installType: process.platform === "win32" ? "download-by-default" : "none", + _validateHostRequirements: () => Promise.resolve(), + downloadURLs: this._downloadURLs(winldd), + _install: () => this._downloadExecutable(winldd, winlddExecutable), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + const android = descriptors.find((d) => d.name === "android"); + this._executables.push({ + type: "tool", + name: "android", + browserName: void 0, + directory: android.dir, + executablePath: () => void 0, + executablePathOrDie: () => "", + installType: "download-on-demand", + _validateHostRequirements: () => Promise.resolve(), + downloadURLs: this._downloadURLs(android), + _install: () => this._downloadExecutable(android), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + this._executables.push({ + type: "browser", + name: "bidi", + browserName: "bidi", + directory: void 0, + executablePath: () => void 0, + executablePathOrDie: () => "", + installType: "none", + _validateHostRequirements: () => Promise.resolve(), + downloadURLs: [], + _install: () => Promise.resolve(), + _dependencyGroup: "tools", + _isHermeticInstallation: true + }); + } + _createChromiumChannel(name, lookAt, install) { + const executablePath = (sdkLanguage, shouldThrow) => { + const suffix = lookAt[process.platform]; + if (!suffix) { + if (shouldThrow) + throw new Error(`Chromium distribution '${name}' is not supported on ${process.platform}`); + return void 0; + } + const prefixes = process.platform === "win32" ? [ + define_process_env_default.LOCALAPPDATA, + define_process_env_default.PROGRAMFILES, + define_process_env_default["PROGRAMFILES(X86)"], + // In some cases there is no PROGRAMFILES/(86) env var set but HOMEDRIVE is set. + define_process_env_default.HOMEDRIVE + "\\Program Files", + define_process_env_default.HOMEDRIVE + "\\Program Files (x86)" + ].filter(Boolean) : [""]; + for (const prefix of prefixes) { + const executablePath2 = path.join(prefix, suffix); + if (canAccessFile(executablePath2)) + return executablePath2; + } + if (!shouldThrow) + return void 0; + const location2 = prefixes.length ? ` at ${path.join(prefixes[0], suffix)}` : ``; + const installation = install ? ` +Run "${buildPlaywrightCLICommand(sdkLanguage, "install " + name)}"` : ""; + throw new Error(`Chromium distribution '${name}' is not found${location2}${installation}`); + }; + return { + type: "channel", + name, + browserName: "chromium", + directory: void 0, + executablePath: (sdkLanguage) => executablePath(sdkLanguage, false), + executablePathOrDie: (sdkLanguage) => executablePath(sdkLanguage, true), + installType: install ? "install-script" : "none", + _validateHostRequirements: () => Promise.resolve(), + _isHermeticInstallation: false, + _install: install + }; + } + _createBidiFirefoxChannel(name, lookAt, install) { + const executablePath = (sdkLanguage, shouldThrow) => { + const suffix = lookAt[process.platform]; + if (!suffix) { + if (shouldThrow) + throw new Error(`Firefox distribution '${name}' is not supported on ${process.platform}`); + return void 0; + } + const prefixes = process.platform === "win32" ? [ + define_process_env_default.LOCALAPPDATA, + define_process_env_default.PROGRAMFILES, + define_process_env_default["PROGRAMFILES(X86)"], + // In some cases there is no PROGRAMFILES/(86) env var set but HOMEDRIVE is set. + define_process_env_default.HOMEDRIVE + "\\Program Files", + define_process_env_default.HOMEDRIVE + "\\Program Files (x86)" + ].filter(Boolean) : [""]; + for (const prefix of prefixes) { + const executablePath2 = path.join(prefix, suffix); + if (canAccessFile(executablePath2)) + return executablePath2; + } + if (shouldThrow) + throw new Error(`Cannot find Firefox installation for channel '${name}' at the standard system paths.`); + return void 0; + }; + return { + type: "channel", + name, + browserName: "bidi", + directory: void 0, + executablePath: (sdkLanguage) => executablePath(sdkLanguage, false), + executablePathOrDie: (sdkLanguage) => executablePath(sdkLanguage, true), + installType: "none", + _validateHostRequirements: () => Promise.resolve(), + _isHermeticInstallation: true, + _install: install + }; + } + _createBidiChromiumChannel(name, lookAt, install) { + const executablePath = (sdkLanguage, shouldThrow) => { + const suffix = lookAt[process.platform]; + if (!suffix) { + if (shouldThrow) + throw new Error(`Firefox distribution '${name}' is not supported on ${process.platform}`); + return void 0; + } + const prefixes = process.platform === "win32" ? [ + define_process_env_default.LOCALAPPDATA, + define_process_env_default.PROGRAMFILES, + define_process_env_default["PROGRAMFILES(X86)"], + // In some cases there is no PROGRAMFILES/(86) env var set but HOMEDRIVE is set. + define_process_env_default.HOMEDRIVE + "\\Program Files", + define_process_env_default.HOMEDRIVE + "\\Program Files (x86)" + ].filter(Boolean) : [""]; + for (const prefix of prefixes) { + const executablePath2 = path.join(prefix, suffix); + if (canAccessFile(executablePath2)) + return executablePath2; + } + if (!shouldThrow) + return void 0; + const location2 = prefixes.length ? ` at ${path.join(prefixes[0], suffix)}` : ``; + const installation = install ? ` +Run "${buildPlaywrightCLICommand(sdkLanguage, "install " + name)}"` : ""; + throw new Error(`Chromium distribution '${name}' is not found${location2}${installation}`); + }; + return { + type: "channel", + name, + browserName: "bidi", + directory: void 0, + executablePath: (sdkLanguage) => executablePath(sdkLanguage, false), + executablePathOrDie: (sdkLanguage) => executablePath(sdkLanguage, true), + installType: install ? "install-script" : "none", + _validateHostRequirements: () => Promise.resolve(), + _isHermeticInstallation: false, + _install: install + }; + } + executables() { + return this._executables; + } + findExecutable(name) { + return this._executables.find((b) => b.name === name); + } + defaultExecutables() { + return this._executables.filter((e) => e.installType === "download-by-default"); + } + _dedupe(executables) { + return Array.from(new Set(executables)); + } + async _validateHostRequirements(sdkLanguage, browserDirectory, linuxLddDirectories, dlOpenLibraries, windowsExeAndDllDirectories) { + if (os.platform() === "linux") + return await validateDependenciesLinux(sdkLanguage, linuxLddDirectories.map((d) => path.join(browserDirectory, d)), dlOpenLibraries); + if (os.platform() === "win32" && os.arch() === "x64") + return await validateDependenciesWindows(sdkLanguage, windowsExeAndDllDirectories.map((d) => path.join(browserDirectory, d))); + } + async installDeps(executablesToInstallDeps, dryRun) { + const executables = this._dedupe(executablesToInstallDeps); + const targets = /* @__PURE__ */ new Set(); + for (const executable of executables) { + if (executable._dependencyGroup) + targets.add(executable._dependencyGroup); + } + targets.add("tools"); + if (os.platform() === "win32") + return await installDependenciesWindows(targets, dryRun); + if (os.platform() === "linux") + return await installDependenciesLinux(targets, dryRun); + } + async install(executablesToInstall, forceReinstall) { + const executables = this._dedupe(executablesToInstall); + await fs.promises.mkdir(registryDirectory, { recursive: true }); + const lockfilePath = path.join(registryDirectory, "__dirlock"); + const linksDir = path.join(registryDirectory, ".links"); + let releaseLock; + try { + releaseLock = await lockfile.lock(registryDirectory, { + retries: { + // Retry 20 times during 10 minutes with + // exponential back-off. + // See documentation at: https://www.npmjs.com/package/retry#retrytimeoutsoptions + retries: 20, + factor: 1.27579 + }, + onCompromised: (err) => { + throw new Error(`${err.message} Path: ${lockfilePath}`); + }, + lockfilePath + }); + await fs.promises.mkdir(linksDir, { recursive: true }); + await fs.promises.writeFile(path.join(linksDir, calculateSha1(PACKAGE_PATH)), PACKAGE_PATH); + if (!getAsBooleanFromENV("PLAYWRIGHT_SKIP_BROWSER_GC")) + await this._validateInstallationCache(linksDir); + for (const executable of executables) { + if (!executable._install) + throw new Error(`ERROR: Playwright does not support installing ${executable.name}`); + const { embedderName } = getEmbedderName(); + if (!getAsBooleanFromENV("CI") && !executable._isHermeticInstallation && !forceReinstall && executable.executablePath(embedderName)) { + const command2 = buildPlaywrightCLICommand(embedderName, "install --force " + executable.name); + process.stderr.write("\n" + wrapInASCIIBox([ + `ATTENTION: "${executable.name}" is already installed on the system!`, + ``, + `"${executable.name}" installation is not hermetic; installing newer version`, + `requires *removal* of a current installation first.`, + ``, + `To *uninstall* current version and re-install latest "${executable.name}":`, + ``, + `- Close all running instances of "${executable.name}", if any`, + `- Use "--force" to install browser:`, + ``, + ` ${command2}`, + ``, + `<3 Playwright Team` + ].join("\n"), 1) + "\n\n"); + return; + } + await executable._install(); + } + } catch (e) { + if (e.code === "ELOCKED") { + const rmCommand = process.platform === "win32" ? "rm -R" : "rm -rf"; + throw new Error("\n" + wrapInASCIIBox([ + `An active lockfile is found at:`, + ``, + ` ${lockfilePath}`, + ``, + `Either:`, + `- wait a few minutes if other Playwright is installing browsers in parallel`, + `- remove lock manually with:`, + ``, + ` ${rmCommand} ${lockfilePath}`, + ``, + `<3 Playwright Team` + ].join("\n"), 1)); + } else { + throw e; + } + } finally { + if (releaseLock) + await releaseLock(); + } + } + async uninstall(all) { + const linksDir = path.join(registryDirectory, ".links"); + if (all) { + const links = await fs.promises.readdir(linksDir).catch(() => []); + for (const link2 of links) + await fs.promises.unlink(path.join(linksDir, link2)); + } else { + await fs.promises.unlink(path.join(linksDir, calculateSha1(PACKAGE_PATH))).catch(() => { + }); + } + await this._validateInstallationCache(linksDir); + return { + numberOfBrowsersLeft: (await fs.promises.readdir(registryDirectory).catch(() => [])).filter((browserDirectory) => isBrowserDirectory(browserDirectory)).length + }; + } + async validateHostRequirementsForExecutablesIfNeeded(executables, sdkLanguage) { + if (getAsBooleanFromENV("PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS")) { + process.stderr.write("Skipping host requirements validation logic because `PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS` env variable is set.\n"); + return; + } + for (const executable of executables) + await this._validateHostRequirementsForExecutableIfNeeded(executable, sdkLanguage); + } + async _validateHostRequirementsForExecutableIfNeeded(executable, sdkLanguage) { + const kMaximumReValidationPeriod = 30 * 24 * 60 * 60 * 1e3; + if (!executable.directory) + return; + const markerFile = path.join(executable.directory, "DEPENDENCIES_VALIDATED"); + if (await fs.promises.stat(markerFile).then((stat2) => Date.now() - stat2.mtime.getTime() < kMaximumReValidationPeriod).catch(() => false)) + return; + debugLogger.log("install", `validating host requirements for "${executable.name}"`); + try { + await executable._validateHostRequirements(sdkLanguage); + debugLogger.log("install", `validation passed for ${executable.name}`); + } catch (error2) { + debugLogger.log("install", `validation failed for ${executable.name}`); + throw error2; + } + await fs.promises.writeFile(markerFile, "").catch(() => { + }); + } + _downloadURLs(descriptor) { + const paths = DOWNLOAD_PATHS[descriptor.name]; + const downloadPathTemplate = paths[hostPlatform] || paths[""]; + if (!downloadPathTemplate) + return []; + const downloadPath = utilExports.format(downloadPathTemplate, descriptor.revision); + let downloadURLs = PLAYWRIGHT_CDN_MIRRORS.map((mirror) => `${mirror}/${downloadPath}`); + let downloadHostEnv; + if (descriptor.name.startsWith("chromium")) + downloadHostEnv = "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST"; + else if (descriptor.name.startsWith("firefox")) + downloadHostEnv = "PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST"; + else if (descriptor.name.startsWith("webkit")) + downloadHostEnv = "PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST"; + const customHostOverride = downloadHostEnv && getFromENV(downloadHostEnv) || getFromENV("PLAYWRIGHT_DOWNLOAD_HOST"); + if (customHostOverride) + downloadURLs = [`${customHostOverride}/${downloadPath}`]; + return downloadURLs; + } + async _downloadExecutable(descriptor, executablePath) { + const downloadURLs = this._downloadURLs(descriptor); + if (!downloadURLs.length) + throw new Error(`ERROR: Playwright does not support ${descriptor.name} on ${hostPlatform}`); + if (!isOfficiallySupportedPlatform) + logPolitely(`BEWARE: your OS is not officially supported by Playwright; downloading fallback build for ${hostPlatform}.`); + if (descriptor.hasRevisionOverride) { + const message = `You are using a frozen ${descriptor.name} browser which does not receive updates anymore on ${hostPlatform}. Please update to the latest version of your operating system to test up-to-date browsers.`; + if (define_process_env_default.GITHUB_ACTIONS) + console.log(`::warning title=Playwright::${message}`); + else + logPolitely(message); + } + const displayName = descriptor.name.split("-").map((word) => { + return word === "ffmpeg" ? "FFMPEG" : word.charAt(0).toUpperCase() + word.slice(1); + }).join(" "); + const title = descriptor.browserVersion ? `${displayName} ${descriptor.browserVersion} (playwright build v${descriptor.revision})` : `${displayName} playwright build v${descriptor.revision}`; + const downloadFileName = `playwright-download-${descriptor.name}-${hostPlatform}-${descriptor.revision}.zip`; + const downloadSocketTimeoutEnv = getFromENV("PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT"); + const downloadSocketTimeout = +(downloadSocketTimeoutEnv || "0") || NET_DEFAULT_TIMEOUT; + await downloadBrowserWithProgressBar(title, descriptor.dir, executablePath, downloadURLs, downloadFileName, downloadSocketTimeout).catch((e) => { + throw new Error(`Failed to download ${title}, caused by +${e.stack}`); + }); + } + async _installMSEdgeChannel(channel, scripts) { + const scriptArgs = []; + if (process.platform !== "linux") { + const products = lowercaseAllKeys(JSON.parse(await fetchData({ url: "https://edgeupdates.microsoft.com/api/products" }))); + const productName = { + "msedge": "Stable", + "msedge-beta": "Beta", + "msedge-dev": "Dev" + }[channel]; + const product = products.find((product2) => product2.product === productName); + const searchConfig = { + darwin: { platform: "MacOS", arch: "universal", artifact: "pkg" }, + win32: { platform: "Windows", arch: "x64", artifact: "msi" } + }[process.platform]; + const release = searchConfig ? product.releases.find((release2) => release2.platform === searchConfig.platform && release2.architecture === searchConfig.arch && release2.artifacts.length > 0) : null; + const artifact = release ? release.artifacts.find((artifact2) => artifact2.artifactname === searchConfig.artifact) : null; + if (artifact) + scriptArgs.push( + artifact.location + /* url */ + ); + else + throw new Error(`Cannot install ${channel} on ${process.platform}`); + } + await this._installChromiumChannel(channel, scripts, scriptArgs); + } + async _installChromiumChannel(channel, scripts, scriptArgs = []) { + const scriptName = scripts[process.platform]; + if (!scriptName) + throw new Error(`Cannot install ${channel} on ${process.platform}`); + const cwd = BIN_PATH; + const isPowerShell = scriptName.endsWith(".ps1"); + if (isPowerShell) { + const args = [ + "-ExecutionPolicy", + "Bypass", + "-File", + path.join(BIN_PATH, scriptName), + ...scriptArgs + ]; + const { code } = await spawnAsync("powershell.exe", args, { cwd, stdio: "inherit" }); + if (code !== 0) + throw new Error(`Failed to install ${channel}`); + } else { + const { command: command2, args, elevatedPermissions } = await transformCommandsForRoot([`bash "${path.join(BIN_PATH, scriptName)}" ${scriptArgs.join("")}`]); + if (elevatedPermissions) + console.log("Switching to root user to install dependencies..."); + const { code } = await spawnAsync(command2, args, { cwd, stdio: "inherit" }); + if (code !== 0) + throw new Error(`Failed to install ${channel}`); + } + } + async listInstalledBrowsers() { + const linksDir = path.join(registryDirectory, ".links"); + const { browsers: browsers2 } = await this._traverseBrowserInstallations(linksDir); + return browsers2.filter((browser2) => fs.existsSync(browser2.browserPath)); + } + async _validateInstallationCache(linksDir) { + const { browsers: browsers2, brokenLinks } = await this._traverseBrowserInstallations(linksDir); + await this._deleteStaleBrowsers(browsers2); + await this._deleteBrokenInstallations(brokenLinks); + } + async _traverseBrowserInstallations(linksDir) { + const browserList = []; + const brokenLinks = []; + for (const fileName of await fs.promises.readdir(linksDir)) { + const linkPath = path.join(linksDir, fileName); + let linkTarget = ""; + try { + linkTarget = (await fs.promises.readFile(linkPath)).toString(); + const browsersJSON = commonjsRequire(path.join(linkTarget, "browsers.json")); + const descriptors = readDescriptors(browsersJSON); + for (const browserName of allDownloadable) { + const descriptor = descriptors.find((d) => d.name === browserName); + if (!descriptor) + continue; + const browserPath = descriptor.dir; + const browserVersion = parseInt(descriptor.revision, 10); + browserList.push({ + browserName, + browserVersion, + browserPath, + referenceDir: linkTarget + }); + } + } catch (e) { + brokenLinks.push(linkPath); + } + } + return { browsers: browserList, brokenLinks }; + } + async _deleteStaleBrowsers(browserList) { + const usedBrowserPaths = /* @__PURE__ */ new Set(); + for (const browser2 of browserList) { + const { browserName, browserVersion, browserPath } = browser2; + const shouldHaveMarkerFile = browserName === "chromium" && (browserVersion >= 786218 || browserVersion < 3e5) || browserName === "firefox" && browserVersion >= 1128 || browserName === "webkit" && browserVersion >= 1307 || // All new applications have a marker file right away. + browserName !== "firefox" && browserName !== "chromium" && browserName !== "webkit"; + if (!shouldHaveMarkerFile || await existsAsync(browserDirectoryToMarkerFilePath(browserPath))) + usedBrowserPaths.add(browserPath); + } + let downloadedBrowsers = (await fs.promises.readdir(registryDirectory)).map((file) => path.join(registryDirectory, file)); + downloadedBrowsers = downloadedBrowsers.filter((file) => isBrowserDirectory(file)); + const directories = new Set(downloadedBrowsers); + for (const browserDirectory of usedBrowserPaths) + directories.delete(browserDirectory); + for (const directory of directories) + logPolitely("Removing unused browser at " + directory); + await removeFolders([...directories]); + } + async _deleteBrokenInstallations(brokenLinks) { + for (const linkPath of brokenLinks) + await fs.promises.unlink(linkPath).catch((e) => { + }); + } +} +function browserDirectoryToMarkerFilePath(browserDirectory) { + return path.join(browserDirectory, "INSTALLATION_COMPLETE"); +} +function buildPlaywrightCLICommand(sdkLanguage, parameters) { + switch (sdkLanguage) { + case "python": + return `playwright ${parameters}`; + case "java": + return `mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="${parameters}"`; + case "csharp": + return `pwsh bin/Debug/netX/playwright.ps1 ${parameters}`; + default: { + const packageManagerCommand = getPackageManagerExecCommand(); + return `${packageManagerCommand} playwright ${parameters}`; + } + } +} +function findChromiumChannel(sdkLanguage) { + let channel = null; + for (const name of ["chromium", "chrome", "msedge"]) { + try { + registry.findExecutable(name).executablePathOrDie(sdkLanguage); + channel = name === "chromium" ? void 0 : name; + break; + } catch (e) { + } + } + if (channel === null) { + const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install chromium`); + const prettyMessage = [ + `No chromium-based browser found on the system.`, + `Please run the following command to download one:`, + ``, + ` ${installCommand}`, + ``, + `<3 Playwright Team` + ].join("\n"); + throw new Error("\n" + wrapInASCIIBox(prettyMessage, 1)); + } + return channel; +} +function lowercaseAllKeys(json) { + if (typeof json !== "object" || !json) + return json; + if (Array.isArray(json)) + return json.map(lowercaseAllKeys); + const result = {}; + for (const [key2, value] of Object.entries(json)) + result[key2.toLowerCase()] = lowercaseAllKeys(value); + return result; +} +const registry = new Registry(require$$0$5); +function parseSerializedValue(value, handles) { + return innerParseSerializedValue(value, handles, /* @__PURE__ */ new Map(), []); +} +function innerParseSerializedValue(value, handles, refs, accessChain) { + if (value.ref !== void 0) + return refs.get(value.ref); + if (value.n !== void 0) + return value.n; + if (value.s !== void 0) + return value.s; + if (value.b !== void 0) + return value.b; + if (value.v !== void 0) { + if (value.v === "undefined") + return void 0; + if (value.v === "null") + return null; + if (value.v === "NaN") + return NaN; + if (value.v === "Infinity") + return Infinity; + if (value.v === "-Infinity") + return -Infinity; + if (value.v === "-0") + return -0; + } + if (value.d !== void 0) + return new Date(value.d); + if (value.u !== void 0) + return new URL(value.u); + if (value.bi !== void 0) + return BigInt(value.bi); + if (value.e !== void 0) { + const error2 = new Error(value.e.m); + error2.name = value.e.n; + error2.stack = value.e.s; + return error2; + } + if (value.r !== void 0) + return new RegExp(value.r.p, value.r.f); + if (value.ta !== void 0) { + const ctor = typedArrayKindToConstructor[value.ta.k]; + return new ctor(value.ta.b.buffer, value.ta.b.byteOffset, value.ta.b.length / ctor.BYTES_PER_ELEMENT); + } + if (value.a !== void 0) { + const result = []; + refs.set(value.id, result); + for (let i = 0; i < value.a.length; i++) + result.push(innerParseSerializedValue(value.a[i], handles, refs, [...accessChain, i])); + return result; + } + if (value.o !== void 0) { + const result = {}; + refs.set(value.id, result); + for (const { k, v } of value.o) + result[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]); + return result; + } + if (value.h !== void 0) { + if (handles === void 0) + throw new Error("Unexpected handle"); + return handles[value.h]; + } + throw new Error(`Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value}`); +} +function serializeValue(value, handleSerializer) { + return innerSerializeValue(value, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []); +} +function innerSerializeValue(value, handleSerializer, visitorInfo, accessChain) { + const handle = handleSerializer(value); + if ("fallThrough" in handle) + value = handle.fallThrough; + else + return handle; + if (typeof value === "symbol") + return { v: "undefined" }; + if (Object.is(value, void 0)) + return { v: "undefined" }; + if (Object.is(value, null)) + return { v: "null" }; + if (Object.is(value, NaN)) + return { v: "NaN" }; + if (Object.is(value, Infinity)) + return { v: "Infinity" }; + if (Object.is(value, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value, -0)) + return { v: "-0" }; + if (typeof value === "boolean") + return { b: value }; + if (typeof value === "number") + return { n: value }; + if (typeof value === "string") + return { s: value }; + if (typeof value === "bigint") + return { bi: value.toString() }; + if (isError$1(value)) + return { e: { n: value.name, m: value.message, s: value.stack || "" } }; + if (isDate$2(value)) + return { d: value.toJSON() }; + if (isURL$1(value)) + return { u: value.toJSON() }; + if (isRegExp$2(value)) + return { r: { p: value.source, f: value.flags } }; + const typedArrayKind = constructorToTypedArrayKind.get(value.constructor); + if (typedArrayKind) + return { ta: { b: Buffer.from(value.buffer, value.byteOffset, value.byteLength), k: typedArrayKind } }; + const id = visitorInfo.visited.get(value); + if (id) + return { ref: id }; + if (Array.isArray(value)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value, id2); + for (let i = 0; i < value.length; ++i) + a.push(innerSerializeValue(value[i], handleSerializer, visitorInfo, [...accessChain, i])); + return { a, id: id2 }; + } + if (typeof value === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value, id2); + for (const name of Object.keys(value)) + o.push({ k: name, v: innerSerializeValue(value[name], handleSerializer, visitorInfo, [...accessChain, name]) }); + return { o, id: id2 }; + } + throw new Error(`Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value}`); +} +function accessChainToDisplayString(accessChain) { + const chainString = accessChain.map((accessor, i) => { + if (typeof accessor === "string") + return i ? `.${accessor}` : accessor; + return `[${accessor}]`; + }).join(""); + return chainString.length > 0 ? ` at position "${chainString}"` : ""; +} +function isRegExp$2(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function isDate$2(obj) { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; +} +function isURL$1(obj) { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; +} +function isError$1(obj) { + const proto = obj ? Object.getPrototypeOf(obj) : null; + return obj instanceof Error || (proto == null ? void 0 : proto.name) === "Error" || proto && isError$1(proto); +} +const typedArrayKindToConstructor = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array +}; +const constructorToTypedArrayKind = new Map(Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k])); +class CustomError extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + } +} +let TimeoutError$1 = class TimeoutError extends CustomError { +}; +let TargetClosedError$1 = class TargetClosedError extends CustomError { + constructor(cause, logs) { + super((cause || "Target page, context or browser has been closed") + (logs || "")); + } +}; +function isTargetClosedError$1(error2) { + return error2 instanceof TargetClosedError$1 || error2.name === "TargetClosedError"; +} +function serializeError$1(e) { + if (isError$2(e)) + return { error: { message: e.message, stack: e.stack, name: e.name } }; + return { value: serializeValue(e, (value) => ({ fallThrough: value })) }; +} +function parseError$1(error2) { + if (!error2.error) { + if (error2.value === void 0) + throw new Error("Serialized error must have either an error or a value"); + return parseSerializedValue(error2.value, void 0); + } + const e = new Error(error2.error.message); + e.stack = error2.error.stack || ""; + e.name = error2.error.name; + return e; +} +class SdkObject extends eventsExports.EventEmitter { + constructor(parent, guidPrefix, guid) { + super(); + this.guid = guid || `${guidPrefix || ""}@${createGuid()}`; + this.setMaxListeners(0); + this.attribution = { ...parent.attribution }; + this.instrumentation = parent.instrumentation; + } +} +function createInstrumentation$1() { + const listeners = /* @__PURE__ */ new Map(); + return new Proxy({}, { + get: (obj, prop) => { + if (typeof prop !== "string") + return obj[prop]; + if (prop === "addListener") + return (listener, context) => listeners.set(listener, context); + if (prop === "removeListener") + return (listener) => listeners.delete(listener); + if (!prop.startsWith("on")) + return obj[prop]; + return async (sdkObject, ...params) => { + var _a2; + for (const [listener, context] of listeners) { + if (!context || sdkObject.attribution.context === context) + await ((_a2 = listener[prop]) == null ? void 0 : _a2.call(listener, sdkObject, ...params)); + } + }; + } + }); +} +function serverSideCallMetadata() { + return { + id: "", + startTime: 0, + endTime: 0, + type: "Internal", + method: "", + params: {}, + log: [], + isServerSide: true + }; +} +class ProtocolError extends Error { + constructor(type2, method, logs) { + super(); + this.type = type2; + this.method = method; + this.logs = logs; + } + setMessage(message) { + rewriteErrorMessage(this, `Protocol error (${this.method}): ${message}`); + } + browserLogMessage() { + return this.logs ? "\nBrowser logs:\n" + this.logs : ""; + } +} +function isProtocolError(e) { + return e instanceof ProtocolError; +} +function isSessionClosedError(e) { + return e instanceof ProtocolError && (e.type === "closed" || e.type === "crashed"); +} +function compressCallLog(log) { + const lines = []; + for (const block of findRepeatedSubsequences(log)) { + for (let i = 0; i < block.sequence.length; i++) { + const line = block.sequence[i]; + const leadingWhitespace = line.match(/^\s*/); + const whitespacePrefix = " " + (leadingWhitespace == null ? void 0 : leadingWhitespace[0]) || ""; + const countPrefix = `${block.count} × `; + if (block.count > 1 && i === 0) + lines.push(whitespacePrefix + countPrefix + line.trim()); + else if (block.count > 1) + lines.push(whitespacePrefix + " ".repeat(countPrefix.length - 2) + "- " + line.trim()); + else + lines.push(whitespacePrefix + "- " + line.trim()); + } + } + return lines; +} +function findRepeatedSubsequences(s) { + const n = s.length; + const result = []; + let i = 0; + const arraysEqual = (a1, a2) => { + if (a1.length !== a2.length) + return false; + for (let j = 0; j < a1.length; j++) { + if (a1[j] !== a2[j]) + return false; + } + return true; + }; + while (i < n) { + let maxRepeatCount = 1; + let maxRepeatSubstr = [s[i]]; + let maxRepeatLength = 1; + for (let p = 1; p <= n - i; p++) { + const substr = s.slice(i, i + p); + let k = 1; + while (i + p * k <= n && arraysEqual(s.slice(i + p * (k - 1), i + p * k), substr)) + k += 1; + k -= 1; + if (k > 1 && k * p > maxRepeatCount * maxRepeatLength) { + maxRepeatCount = k; + maxRepeatSubstr = substr; + maxRepeatLength = p; + } + } + result.push({ sequence: maxRepeatSubstr, count: maxRepeatCount }); + i += maxRepeatLength * maxRepeatCount; + } + return result; +} +const metadataValidator = createMetadataValidator(); +function maxDispatchersForBucket(gcBucket) { + return { + "JSHandle": 1e5, + "ElementHandle": 1e5 + }[gcBucket] ?? 1e4; +} +class Dispatcher extends eventsExports.EventEmitter { + constructor(parent, object, type2, initializer, gcBucket) { + super(); + this._dispatchers = /* @__PURE__ */ new Map(); + this._disposed = false; + this._eventListeners = []; + this._openScope = new LongStandingScope(); + this.connection = parent instanceof DispatcherConnection ? parent : parent.connection; + this._parent = parent instanceof DispatcherConnection ? void 0 : parent; + const guid = object.guid; + this._guid = guid; + this._type = type2; + this._object = object; + this._gcBucket = gcBucket ?? type2; + this.connection.registerDispatcher(this); + if (this._parent) { + assert(!this._parent._dispatchers.has(guid)); + this._parent._dispatchers.set(guid, this); + } + if (this._parent) + this.connection.sendCreate(this._parent, type2, guid, initializer); + this.connection.maybeDisposeStaleDispatchers(this._gcBucket); + } + parentScope() { + return this._parent; + } + addObjectListener(eventName, handler) { + this._eventListeners.push(eventsHelper.addEventListener(this._object, eventName, handler)); + } + adopt(child) { + if (child._parent === this) + return; + const oldParent = child._parent; + oldParent._dispatchers.delete(child._guid); + this._dispatchers.set(child._guid, child); + child._parent = this; + this.connection.sendAdopt(this, child); + } + async _handleCommand(callMetadata, method, validParams) { + const commandPromise = this[method](validParams, callMetadata); + try { + return await this._openScope.race(commandPromise); + } catch (e) { + if (callMetadata.potentiallyClosesScope && isTargetClosedError$1(e)) + return await commandPromise; + throw e; + } + } + _dispatchEvent(method, params) { + if (this._disposed) { + if (isUnderTest()) + throw new Error(`${this._guid} is sending "${String(method)}" event after being disposed`); + return; + } + this.connection.sendEvent(this, method, params); + } + _dispose(reason) { + this._disposeRecursively(new TargetClosedError$1()); + this.connection.sendDispose(this, reason); + } + _onDispose() { + } + _disposeRecursively(error2) { + var _a2; + assert(!this._disposed, `${this._guid} is disposed more than once`); + this._onDispose(); + this._disposed = true; + eventsHelper.removeEventListeners(this._eventListeners); + (_a2 = this._parent) == null ? void 0 : _a2._dispatchers.delete(this._guid); + const list = this.connection._dispatchersByBucket.get(this._gcBucket); + list == null ? void 0 : list.delete(this._guid); + this.connection._dispatcherByGuid.delete(this._guid); + this.connection._dispatcherByObject.delete(this._object); + for (const dispatcher of [...this._dispatchers.values()]) + dispatcher._disposeRecursively(error2); + this._dispatchers.clear(); + this._openScope.close(error2); + } + _debugScopeState() { + return { + _guid: this._guid, + objects: Array.from(this._dispatchers.values()).map((o) => o._debugScopeState()) + }; + } + async waitForEventInfo() { + } +} +class RootDispatcher extends Dispatcher { + constructor(connection, createPlaywright) { + super(connection, { guid: "" }, "Root", {}); + this.createPlaywright = createPlaywright; + this._initialized = false; + } + async initialize(params) { + assert(this.createPlaywright); + assert(!this._initialized); + this._initialized = true; + return { + playwright: await this.createPlaywright(this, params) + }; + } +} +class DispatcherConnection { + constructor(isLocal) { + this._dispatcherByGuid = /* @__PURE__ */ new Map(); + this._dispatcherByObject = /* @__PURE__ */ new Map(); + this._dispatchersByBucket = /* @__PURE__ */ new Map(); + this.onmessage = (message) => { + }; + this._waitOperations = /* @__PURE__ */ new Map(); + this._isLocal = !!isLocal; + } + sendEvent(dispatcher, event, params) { + const validator = findValidator(dispatcher._type, event, "Event"); + params = validator(params, "", this._validatorToWireContext()); + this.onmessage({ guid: dispatcher._guid, method: event, params }); + } + sendCreate(parent, type2, guid, initializer) { + const validator = findValidator(type2, "", "Initializer"); + initializer = validator(initializer, "", this._validatorToWireContext()); + this.onmessage({ guid: parent._guid, method: "__create__", params: { type: type2, initializer, guid } }); + } + sendAdopt(parent, dispatcher) { + this.onmessage({ guid: parent._guid, method: "__adopt__", params: { guid: dispatcher._guid } }); + } + sendDispose(dispatcher, reason) { + this.onmessage({ guid: dispatcher._guid, method: "__dispose__", params: { reason } }); + } + _validatorToWireContext() { + return { + tChannelImpl: this._tChannelImplToWire.bind(this), + binary: this._isLocal ? "buffer" : "toBase64", + isUnderTest + }; + } + _validatorFromWireContext() { + return { + tChannelImpl: this._tChannelImplFromWire.bind(this), + binary: this._isLocal ? "buffer" : "fromBase64", + isUnderTest + }; + } + _tChannelImplFromWire(names, arg, path2, context) { + if (arg && typeof arg === "object" && typeof arg.guid === "string") { + const guid = arg.guid; + const dispatcher = this._dispatcherByGuid.get(guid); + if (!dispatcher) + throw new ValidationError(`${path2}: no object with guid ${guid}`); + if (names !== "*" && !names.includes(dispatcher._type)) + throw new ValidationError(`${path2}: object with guid ${guid} has type ${dispatcher._type}, expected ${names.toString()}`); + return dispatcher; + } + throw new ValidationError(`${path2}: expected guid for ${names.toString()}`); + } + _tChannelImplToWire(names, arg, path2, context) { + if (arg instanceof Dispatcher) { + if (names !== "*" && !names.includes(arg._type)) + throw new ValidationError(`${path2}: dispatcher with guid ${arg._guid} has type ${arg._type}, expected ${names.toString()}`); + return { guid: arg._guid }; + } + throw new ValidationError(`${path2}: expected dispatcher ${names.toString()}`); + } + existingDispatcher(object) { + return this._dispatcherByObject.get(object); + } + registerDispatcher(dispatcher) { + assert(!this._dispatcherByGuid.has(dispatcher._guid)); + this._dispatcherByGuid.set(dispatcher._guid, dispatcher); + this._dispatcherByObject.set(dispatcher._object, dispatcher); + let list = this._dispatchersByBucket.get(dispatcher._gcBucket); + if (!list) { + list = /* @__PURE__ */ new Set(); + this._dispatchersByBucket.set(dispatcher._gcBucket, list); + } + list.add(dispatcher._guid); + } + maybeDisposeStaleDispatchers(gcBucket) { + const maxDispatchers = maxDispatchersForBucket(gcBucket); + const list = this._dispatchersByBucket.get(gcBucket); + if (!list || list.size <= maxDispatchers) + return; + const dispatchersArray = [...list]; + const disposeCount = maxDispatchers / 10 | 0; + this._dispatchersByBucket.set(gcBucket, new Set(dispatchersArray.slice(disposeCount))); + for (let i = 0; i < disposeCount; ++i) { + const d = this._dispatcherByGuid.get(dispatchersArray[i]); + if (!d) + continue; + d._dispose("gc"); + } + } + async dispatch(message) { + var _a2, _b2, _c2, _d2, _e2, _f2; + const { id, guid, method, params, metadata } = message; + const dispatcher = this._dispatcherByGuid.get(guid); + if (!dispatcher) { + this.onmessage({ id, error: serializeError$1(new TargetClosedError$1()) }); + return; + } + let validParams; + let validMetadata; + try { + const validator = findValidator(dispatcher._type, method, "Params"); + const validatorContext = this._validatorFromWireContext(); + validParams = validator(params, "", validatorContext); + validMetadata = metadataValidator(metadata, "", validatorContext); + if (typeof dispatcher[method] !== "function") + throw new Error(`Mismatching dispatcher: "${dispatcher._type}" does not implement "${method}"`); + } catch (e) { + this.onmessage({ id, error: serializeError$1(e) }); + return; + } + if ((_a2 = methodMetainfo.get(dispatcher._type + "." + method)) == null ? void 0 : _a2.internal) { + validMetadata.internal = true; + } + const sdkObject = dispatcher._object instanceof SdkObject ? dispatcher._object : void 0; + const callMetadata = { + id: `call@${id}`, + location: validMetadata.location, + title: validMetadata.title, + internal: validMetadata.internal, + stepId: validMetadata.stepId, + objectId: sdkObject == null ? void 0 : sdkObject.guid, + pageId: (_c2 = (_b2 = sdkObject == null ? void 0 : sdkObject.attribution) == null ? void 0 : _b2.page) == null ? void 0 : _c2.guid, + frameId: (_e2 = (_d2 = sdkObject == null ? void 0 : sdkObject.attribution) == null ? void 0 : _d2.frame) == null ? void 0 : _e2.guid, + startTime: monotonicTime(), + endTime: 0, + type: dispatcher._type, + method, + params: params || {}, + log: [] + }; + if (sdkObject && ((_f2 = params == null ? void 0 : params.info) == null ? void 0 : _f2.waitId)) { + const info = params.info; + switch (info.phase) { + case "before": { + this._waitOperations.set(info.waitId, callMetadata); + await sdkObject.instrumentation.onBeforeCall(sdkObject, callMetadata); + this.onmessage({ id }); + return; + } + case "log": { + const originalMetadata = this._waitOperations.get(info.waitId); + originalMetadata.log.push(info.message); + sdkObject.instrumentation.onCallLog(sdkObject, originalMetadata, "api", info.message); + this.onmessage({ id }); + return; + } + case "after": { + const originalMetadata = this._waitOperations.get(info.waitId); + originalMetadata.endTime = monotonicTime(); + originalMetadata.error = info.error ? { error: { name: "Error", message: info.error } } : void 0; + this._waitOperations.delete(info.waitId); + await sdkObject.instrumentation.onAfterCall(sdkObject, originalMetadata); + this.onmessage({ id }); + return; + } + } + } + await (sdkObject == null ? void 0 : sdkObject.instrumentation.onBeforeCall(sdkObject, callMetadata)); + const response2 = { id }; + try { + const result = await dispatcher._handleCommand(callMetadata, method, validParams); + const validator = findValidator(dispatcher._type, method, "Result"); + response2.result = validator(result, "", this._validatorToWireContext()); + callMetadata.result = result; + } catch (e) { + if (isTargetClosedError$1(e) && sdkObject) { + const reason = closeReason(sdkObject); + if (reason) + rewriteErrorMessage(e, reason); + } else if (isProtocolError(e)) { + if (e.type === "closed") { + const reason = sdkObject ? closeReason(sdkObject) : void 0; + e = new TargetClosedError$1(reason, e.browserLogMessage()); + } else if (e.type === "crashed") { + rewriteErrorMessage(e, "Target crashed " + e.browserLogMessage()); + } + } + response2.error = serializeError$1(e); + callMetadata.error = response2.error; + } finally { + callMetadata.endTime = monotonicTime(); + await (sdkObject == null ? void 0 : sdkObject.instrumentation.onAfterCall(sdkObject, callMetadata)); + } + if (response2.error) + response2.log = compressCallLog(callMetadata.log); + this.onmessage(response2); + } +} +function closeReason(sdkObject) { + var _a2, _b2, _c2; + return ((_a2 = sdkObject.attribution.page) == null ? void 0 : _a2.closeReason) || ((_b2 = sdkObject.attribution.context) == null ? void 0 : _b2._closeReason) || ((_c2 = sdkObject.attribution.browser) == null ? void 0 : _c2._closeReason); +} +var libExports = requireLib(); +const source$6 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/clock.ts\nvar clock_exports = {};\n__export(clock_exports, {\n ClockController: () => ClockController,\n createClock: () => createClock,\n inject: () => inject,\n install: () => install\n});\nmodule.exports = __toCommonJS(clock_exports);\nvar ClockController = class {\n constructor(embedder) {\n this._duringTick = false;\n this._uniqueTimerId = idCounterStart;\n this.disposables = [];\n this._log = [];\n this._timers = /* @__PURE__ */ new Map();\n this._now = { time: asWallTime(0), isFixedTime: false, ticks: 0, origin: asWallTime(-1) };\n this._embedder = embedder;\n }\n uninstall() {\n this.disposables.forEach((dispose) => dispose());\n this.disposables.length = 0;\n }\n now() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.time;\n }\n install(time) {\n this._replayLogOnce();\n this._innerSetTime(asWallTime(time));\n }\n setSystemTime(time) {\n this._replayLogOnce();\n this._innerSetTime(asWallTime(time));\n }\n setFixedTime(time) {\n this._replayLogOnce();\n this._innerSetFixedTime(asWallTime(time));\n }\n performanceNow() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.ticks;\n }\n _syncRealTime() {\n if (!this._realTime)\n return;\n const now = this._embedder.performanceNow();\n const sinceLastSync = now - this._realTime.lastSyncTicks;\n if (sinceLastSync > 0) {\n this._advanceNow(shiftTicks(this._now.ticks, sinceLastSync));\n this._realTime.lastSyncTicks = now;\n }\n }\n _innerSetTime(time) {\n this._now.time = time;\n this._now.isFixedTime = false;\n if (this._now.origin < 0)\n this._now.origin = this._now.time;\n }\n _innerSetFixedTime(time) {\n this._innerSetTime(time);\n this._now.isFixedTime = true;\n }\n _advanceNow(to) {\n if (!this._now.isFixedTime)\n this._now.time = asWallTime(this._now.time + to - this._now.ticks);\n this._now.ticks = to;\n }\n async log(type, time, param) {\n this._log.push({ type, time, param });\n }\n async runFor(ticks) {\n this._replayLogOnce();\n if (ticks < 0)\n throw new TypeError("Negative ticks are not supported");\n await this._runTo(shiftTicks(this._now.ticks, ticks));\n }\n async _runTo(to) {\n to = Math.ceil(to);\n if (this._now.ticks > to)\n return;\n let firstException;\n while (true) {\n const result = await this._callFirstTimer(to);\n if (!result.timerFound)\n break;\n firstException = firstException || result.error;\n }\n this._advanceNow(to);\n if (firstException)\n throw firstException;\n }\n async pauseAt(time) {\n this._replayLogOnce();\n this._innerPause();\n const toConsume = time - this._now.time;\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, toConsume));\n return toConsume;\n }\n _innerPause() {\n this._realTime = void 0;\n this._updateRealTimeTimer();\n }\n resume() {\n this._replayLogOnce();\n this._innerResume();\n }\n _innerResume() {\n const now = this._embedder.performanceNow();\n this._realTime = { startTicks: now, lastSyncTicks: now };\n this._updateRealTimeTimer();\n }\n _updateRealTimeTimer() {\n var _a;\n if (!this._realTime) {\n (_a = this._currentRealTimeTimer) == null ? void 0 : _a.dispose();\n this._currentRealTimeTimer = void 0;\n return;\n }\n const firstTimer = this._firstTimer();\n const callAt = Math.min(firstTimer ? firstTimer.callAt : this._now.ticks + maxTimeout, this._now.ticks + 100);\n if (this._currentRealTimeTimer && this._currentRealTimeTimer.callAt < callAt)\n return;\n if (this._currentRealTimeTimer) {\n this._currentRealTimeTimer.dispose();\n this._currentRealTimeTimer = void 0;\n }\n this._currentRealTimeTimer = {\n callAt,\n dispose: this._embedder.setTimeout(() => {\n this._currentRealTimeTimer = void 0;\n this._syncRealTime();\n void this._runTo(this._now.ticks).catch((e) => console.error(e)).then(() => this._updateRealTimeTimer());\n }, callAt - this._now.ticks)\n };\n }\n async fastForward(ticks) {\n this._replayLogOnce();\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, ticks | 0));\n }\n async _innerFastForwardTo(to) {\n if (to < this._now.ticks)\n throw new Error("Cannot fast-forward to the past");\n for (const timer of this._timers.values()) {\n if (to > timer.callAt)\n timer.callAt = to;\n }\n await this._runTo(to);\n }\n addTimer(options) {\n this._replayLogOnce();\n if (options.type === "AnimationFrame" /* AnimationFrame */ && !options.func)\n throw new Error("Callback must be provided to requestAnimationFrame calls");\n if (options.type === "IdleCallback" /* IdleCallback */ && !options.func)\n throw new Error("Callback must be provided to requestIdleCallback calls");\n if (["Timeout" /* Timeout */, "Interval" /* Interval */].includes(options.type) && !options.func && options.delay === void 0)\n throw new Error("Callback must be provided to timer calls");\n let delay = options.delay ? +options.delay : 0;\n if (!Number.isFinite(delay))\n delay = 0;\n delay = delay > maxTimeout ? 1 : delay;\n delay = Math.max(0, delay);\n const timer = {\n type: options.type,\n func: options.func,\n args: options.args || [],\n delay,\n callAt: shiftTicks(this._now.ticks, delay || (this._duringTick ? 1 : 0)),\n createdAt: this._now.ticks,\n id: this._uniqueTimerId++,\n error: new Error()\n };\n this._timers.set(timer.id, timer);\n if (this._realTime)\n this._updateRealTimeTimer();\n return timer.id;\n }\n countTimers() {\n return this._timers.size;\n }\n _firstTimer(beforeTick) {\n let firstTimer = null;\n for (const timer of this._timers.values()) {\n const isInRange = beforeTick === void 0 || timer.callAt <= beforeTick;\n if (isInRange && (!firstTimer || compareTimers(firstTimer, timer) === 1))\n firstTimer = timer;\n }\n return firstTimer;\n }\n _takeFirstTimer(beforeTick) {\n const timer = this._firstTimer(beforeTick);\n if (!timer)\n return null;\n this._advanceNow(timer.callAt);\n if (timer.type === "Interval" /* Interval */)\n timer.callAt = shiftTicks(timer.callAt, timer.delay);\n else\n this._timers.delete(timer.id);\n return timer;\n }\n async _callFirstTimer(beforeTick) {\n const timer = this._takeFirstTimer(beforeTick);\n if (!timer)\n return { timerFound: false };\n this._duringTick = true;\n try {\n if (typeof timer.func !== "function") {\n let error2;\n try {\n (() => {\n globalThis.eval(timer.func);\n })();\n } catch (e) {\n error2 = e;\n }\n await new Promise((f) => this._embedder.setTimeout(f));\n return { timerFound: true, error: error2 };\n }\n let args = timer.args;\n if (timer.type === "AnimationFrame" /* AnimationFrame */)\n args = [this._now.ticks];\n else if (timer.type === "IdleCallback" /* IdleCallback */)\n args = [{ didTimeout: false, timeRemaining: () => 0 }];\n let error;\n try {\n timer.func.apply(null, args);\n } catch (e) {\n error = e;\n }\n await new Promise((f) => this._embedder.setTimeout(f));\n return { timerFound: true, error };\n } finally {\n this._duringTick = false;\n }\n }\n getTimeToNextFrame() {\n return 16 - this._now.ticks % 16;\n }\n clearTimer(timerId, type) {\n this._replayLogOnce();\n if (!timerId) {\n return;\n }\n const id = Number(timerId);\n if (Number.isNaN(id) || id < idCounterStart) {\n const handlerName = getClearHandler(type);\n new Error(`Clock: ${handlerName} was invoked to clear a native timer instead of one created by the clock library.`);\n }\n const timer = this._timers.get(id);\n if (timer) {\n if (timer.type === type || timer.type === "Timeout" && type === "Interval" || timer.type === "Interval" && type === "Timeout") {\n this._timers.delete(id);\n } else {\n const clear = getClearHandler(type);\n const schedule = getScheduleHandler(timer.type);\n throw new Error(\n `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`\n );\n }\n }\n }\n _replayLogOnce() {\n if (!this._log.length)\n return;\n let lastLogTime = -1;\n let isPaused = false;\n for (const { type, time, param } of this._log) {\n if (!isPaused && lastLogTime !== -1)\n this._advanceNow(shiftTicks(this._now.ticks, time - lastLogTime));\n lastLogTime = time;\n if (type === "install") {\n this._innerSetTime(asWallTime(param));\n } else if (type === "fastForward" || type === "runFor") {\n this._advanceNow(shiftTicks(this._now.ticks, param));\n } else if (type === "pauseAt") {\n isPaused = true;\n this._innerPause();\n this._innerSetTime(asWallTime(param));\n } else if (type === "resume") {\n this._innerResume();\n isPaused = false;\n } else if (type === "setFixedTime") {\n this._innerSetFixedTime(asWallTime(param));\n } else if (type === "setSystemTime") {\n this._innerSetTime(asWallTime(param));\n }\n }\n if (!isPaused && lastLogTime > 0)\n this._advanceNow(shiftTicks(this._now.ticks, this._embedder.dateNow() - lastLogTime));\n this._log.length = 0;\n }\n};\nfunction mirrorDateProperties(target, source) {\n for (const prop in source) {\n if (source.hasOwnProperty(prop))\n target[prop] = source[prop];\n }\n target.toString = () => source.toString();\n target.prototype = source.prototype;\n target.parse = source.parse;\n target.UTC = source.UTC;\n target.prototype.toUTCString = source.prototype.toUTCString;\n target.isFake = true;\n return target;\n}\nfunction createDate(clock, NativeDate) {\n function ClockDate(year, month, date, hour, minute, second, ms) {\n if (!(this instanceof ClockDate))\n return new NativeDate(clock.now()).toString();\n switch (arguments.length) {\n case 0:\n return new NativeDate(clock.now());\n case 1:\n return new NativeDate(year);\n case 2:\n return new NativeDate(year, month);\n case 3:\n return new NativeDate(year, month, date);\n case 4:\n return new NativeDate(year, month, date, hour);\n case 5:\n return new NativeDate(year, month, date, hour, minute);\n case 6:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second\n );\n default:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second,\n ms\n );\n }\n }\n ClockDate.now = () => clock.now();\n return mirrorDateProperties(ClockDate, NativeDate);\n}\nfunction createIntl(clock, NativeIntl) {\n const ClockIntl = {};\n for (const key of Object.getOwnPropertyNames(NativeIntl))\n ClockIntl[key] = NativeIntl[key];\n ClockIntl.DateTimeFormat = function(...args) {\n const realFormatter = new NativeIntl.DateTimeFormat(...args);\n const formatter = {\n formatRange: realFormatter.formatRange.bind(realFormatter),\n formatRangeToParts: realFormatter.formatRangeToParts.bind(realFormatter),\n resolvedOptions: realFormatter.resolvedOptions.bind(realFormatter),\n format: (date) => realFormatter.format(date || clock.now()),\n formatToParts: (date) => realFormatter.formatToParts(date || clock.now())\n };\n return formatter;\n };\n ClockIntl.DateTimeFormat.prototype = Object.create(\n NativeIntl.DateTimeFormat.prototype\n );\n ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;\n return ClockIntl;\n}\nfunction compareTimers(a, b) {\n if (a.callAt < b.callAt)\n return -1;\n if (a.callAt > b.callAt)\n return 1;\n if (a.type === "Immediate" /* Immediate */ && b.type !== "Immediate" /* Immediate */)\n return -1;\n if (a.type !== "Immediate" /* Immediate */ && b.type === "Immediate" /* Immediate */)\n return 1;\n if (a.createdAt < b.createdAt)\n return -1;\n if (a.createdAt > b.createdAt)\n return 1;\n if (a.id < b.id)\n return -1;\n if (a.id > b.id)\n return 1;\n}\nvar maxTimeout = Math.pow(2, 31) - 1;\nvar idCounterStart = 1e12;\nfunction platformOriginals(globalObject) {\n const raw = {\n setTimeout: globalObject.setTimeout,\n clearTimeout: globalObject.clearTimeout,\n setInterval: globalObject.setInterval,\n clearInterval: globalObject.clearInterval,\n requestAnimationFrame: globalObject.requestAnimationFrame ? globalObject.requestAnimationFrame : void 0,\n cancelAnimationFrame: globalObject.cancelAnimationFrame ? globalObject.cancelAnimationFrame : void 0,\n requestIdleCallback: globalObject.requestIdleCallback ? globalObject.requestIdleCallback : void 0,\n cancelIdleCallback: globalObject.cancelIdleCallback ? globalObject.cancelIdleCallback : void 0,\n Date: globalObject.Date,\n performance: globalObject.performance,\n Intl: globalObject.Intl\n };\n const bound = { ...raw };\n for (const key of Object.keys(bound)) {\n if (key !== "Date" && typeof bound[key] === "function")\n bound[key] = bound[key].bind(globalObject);\n }\n return { raw, bound };\n}\nfunction getScheduleHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `request${type}`;\n return `set${type}`;\n}\nfunction createApi(clock, originals) {\n return {\n setTimeout: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Timeout" /* Timeout */,\n func,\n args,\n delay\n });\n },\n clearTimeout: (timerId) => {\n if (timerId)\n clock.clearTimer(timerId, "Timeout" /* Timeout */);\n },\n setInterval: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Interval" /* Interval */,\n func,\n args,\n delay\n });\n },\n clearInterval: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "Interval" /* Interval */);\n },\n requestAnimationFrame: (callback) => {\n return clock.addTimer({\n type: "AnimationFrame" /* AnimationFrame */,\n func: callback,\n delay: clock.getTimeToNextFrame()\n });\n },\n cancelAnimationFrame: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "AnimationFrame" /* AnimationFrame */);\n },\n requestIdleCallback: (callback, options) => {\n let timeToNextIdlePeriod = 0;\n if (clock.countTimers() > 0)\n timeToNextIdlePeriod = 50;\n return clock.addTimer({\n type: "IdleCallback" /* IdleCallback */,\n func: callback,\n delay: (options == null ? void 0 : options.timeout) ? Math.min(options == null ? void 0 : options.timeout, timeToNextIdlePeriod) : timeToNextIdlePeriod\n });\n },\n cancelIdleCallback: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "IdleCallback" /* IdleCallback */);\n },\n Intl: originals.Intl ? createIntl(clock, originals.Intl) : void 0,\n Date: createDate(clock, originals.Date),\n performance: originals.performance ? fakePerformance(clock, originals.performance) : void 0\n };\n}\nfunction getClearHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `cancel${type}`;\n return `clear${type}`;\n}\nfunction fakePerformance(clock, performance) {\n const result = {\n now: () => clock.performanceNow()\n };\n result.__defineGetter__("timeOrigin", () => clock._now.origin || 0);\n for (const key of Object.keys(performance.__proto__)) {\n if (key === "now" || key === "timeOrigin")\n continue;\n if (key === "getEntries" || key === "getEntriesByName" || key === "getEntriesByType")\n result[key] = () => [];\n else\n result[key] = () => {\n };\n }\n return result;\n}\nfunction createClock(globalObject) {\n const originals = platformOriginals(globalObject);\n const embedder = {\n dateNow: () => originals.raw.Date.now(),\n performanceNow: () => Math.ceil(originals.raw.performance.now()),\n setTimeout: (task, timeout) => {\n const timerId = originals.bound.setTimeout(task, timeout);\n return () => originals.bound.clearTimeout(timerId);\n },\n setInterval: (task, delay) => {\n const intervalId = originals.bound.setInterval(task, delay);\n return () => originals.bound.clearInterval(intervalId);\n }\n };\n const clock = new ClockController(embedder);\n const api = createApi(clock, originals.bound);\n return { clock, api, originals: originals.raw };\n}\nfunction install(globalObject, config = {}) {\n var _a, _b;\n if ((_a = globalObject.Date) == null ? void 0 : _a.isFake) {\n throw new TypeError(`Can\'t install fake timers twice on the same global object.`);\n }\n const { clock, api, originals } = createClock(globalObject);\n const toFake = ((_b = config.toFake) == null ? void 0 : _b.length) ? config.toFake : Object.keys(originals);\n for (const method of toFake) {\n if (method === "Date") {\n globalObject.Date = mirrorDateProperties(api.Date, globalObject.Date);\n } else if (method === "Intl") {\n globalObject.Intl = api[method];\n } else if (method === "performance") {\n globalObject.performance = api[method];\n const kEventTimeStamp = Symbol("playwrightEventTimeStamp");\n Object.defineProperty(Event.prototype, "timeStamp", {\n get() {\n var _a2;\n if (!this[kEventTimeStamp])\n this[kEventTimeStamp] = (_a2 = api.performance) == null ? void 0 : _a2.now();\n return this[kEventTimeStamp];\n }\n });\n } else {\n globalObject[method] = (...args) => {\n return api[method].apply(api, args);\n };\n }\n clock.disposables.push(() => {\n globalObject[method] = originals[method];\n });\n }\n return { clock, api, originals };\n}\nfunction inject(globalObject) {\n const builtins = platformOriginals(globalObject).bound;\n const { clock: controller } = install(globalObject);\n controller.resume();\n return {\n controller,\n builtins\n };\n}\nfunction asWallTime(n) {\n return n;\n}\nfunction shiftTicks(ticks, ms) {\n return ticks + ms;\n}\n'; +let Clock$1 = class Clock { + constructor(browserContext) { + this._initScripts = []; + this._browserContext = browserContext; + } + async resetForReuse() { + await this._browserContext.removeInitScripts(this._initScripts); + this._initScripts = []; + } + async fastForward(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks$1(ticks); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('fastForward', ${Date.now()}, ${ticksMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.fastForward(${ticksMillis})`); + } + async install(time) { + await this._installIfNeeded(); + const timeMillis = time !== void 0 ? parseTime$1(time) : Date.now(); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('install', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.install(${timeMillis})`); + } + async pauseAt(ticks) { + await this._installIfNeeded(); + const timeMillis = parseTime$1(ticks); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.pauseAt(${timeMillis})`); + } + async resume() { + await this._installIfNeeded(); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`); + } + async setFixedTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime$1(time); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('setFixedTime', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.setFixedTime(${timeMillis})`); + } + async setSystemTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime$1(time); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('setSystemTime', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.setSystemTime(${timeMillis})`); + } + async runFor(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks$1(ticks); + this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('runFor', ${Date.now()}, ${ticksMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.runFor(${ticksMillis})`); + } + async _installIfNeeded() { + if (this._initScripts.length) + return; + const script = `(() => { + const module = {}; + ${source$6} + globalThis.__pwClock = (module.exports.inject())(globalThis); + })();`; + this._initScripts.push(await this._browserContext.addInitScript(script)); + await this._evaluateInFrames(script); + } + async _evaluateInFrames(script) { + await this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: true }); + } +}; +function parseTicks$1(value) { + if (typeof value === "number") + return value; + if (!value) + return 0; + const str = value; + const strings = str.split(":"); + const l = strings.length; + let i = l; + let ms2 = 0; + let parsed; + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error( + `Clock only understands numbers, 'mm:ss' and 'hh:mm:ss'` + ); + } + while (i--) { + parsed = parseInt(strings[i], 10); + if (parsed >= 60) + throw new Error(`Invalid time ${str}`); + ms2 += parsed * Math.pow(60, l - i - 1); + } + return ms2 * 1e3; +} +function parseTime$1(epoch) { + if (!epoch) + return 0; + if (typeof epoch === "number") + return epoch; + const parsed = new Date(epoch); + if (!isFinite(parsed.getTime())) + throw new Error(`Invalid date: ${epoch}`); + return parsed.getTime(); +} +const symbol = Symbol("Debugger"); +const _Debugger = class _Debugger2 extends eventsExports.EventEmitter { + constructor(context) { + super(); + this._pauseOnNextStatement = false; + this._pausedCallsMetadata = /* @__PURE__ */ new Map(); + this._muted = false; + this._context = context; + this._context[symbol] = this; + this._enabled = debugMode() === "inspector"; + if (this._enabled) + this.pauseOnNextStatement(); + context.instrumentation.addListener(this, context); + this._context.once(BrowserContext$1.Events.Close, () => { + this._context.instrumentation.removeListener(this); + }); + this._slowMo = this._context._browser.options.slowMo; + } + async setMuted(muted) { + this._muted = muted; + if (muted) this.resume(false); + } + async onBeforeCall(sdkObject, metadata) { + if (this._muted) + return; + if (shouldPauseOnCall(sdkObject, metadata) || this._pauseOnNextStatement && shouldPauseBeforeStep(metadata)) + await this.pause(sdkObject, metadata); + } + async _doSlowMo() { + await new Promise((f) => setTimeout(f, this._slowMo)); + } + async onAfterCall(sdkObject, metadata) { + if (this._slowMo && shouldSlowMo(metadata)) + await this._doSlowMo(); + } + async onBeforeInputAction(sdkObject, metadata) { + if (this._muted) + return; + if (metadata.playing) + return; + if (this._enabled && this._pauseOnNextStatement) + await this.pause(sdkObject, metadata); + } + async pause(sdkObject, metadata) { + if (this._muted) + return; + this._enabled = true; + metadata.pauseStartTime = monotonicTime(); + const result = new Promise((resolve) => { + this._pausedCallsMetadata.set(metadata, { resolve, sdkObject }); + }); + this.emit(_Debugger2.Events.PausedStateChanged); + return result; + } + resume(step) { + if (!this.isPaused()) + return; + this._pauseOnNextStatement = step; + const endTime = monotonicTime(); + for (const [metadata, { resolve }] of this._pausedCallsMetadata) { + metadata.pauseEndTime = endTime; + resolve(); + } + this._pausedCallsMetadata.clear(); + this.emit(_Debugger2.Events.PausedStateChanged); + } + pauseOnNextStatement() { + this._pauseOnNextStatement = true; + } + isPaused(metadata) { + if (metadata) + return this._pausedCallsMetadata.has(metadata); + return !!this._pausedCallsMetadata.size; + } + pausedDetails() { + const result = []; + for (const [metadata, { sdkObject }] of this._pausedCallsMetadata) + result.push({ metadata, sdkObject }); + return result; + } +}; +_Debugger.Events = { + PausedStateChanged: "pausedstatechanged" +}; +let Debugger = _Debugger; +function shouldPauseOnCall(sdkObject, metadata) { + var _a2; + if (sdkObject.attribution.playwright.options.isServer) + return false; + if (!((_a2 = sdkObject.attribution.browser) == null ? void 0 : _a2.options.headful) && !isUnderTest()) + return false; + return metadata.method === "pause"; +} +function shouldPauseBeforeStep(metadata) { + if (metadata.playing) + return true; + if (metadata.internal) + return false; + if (metadata.method === "close") + return true; + if (metadata.method === "waitForSelector" || metadata.method === "waitForEventInfo" || metadata.method === "querySelector" || metadata.method === "querySelectorAll") + return false; + const step = metadata.type + "." + metadata.method; + const metainfo = methodMetainfo.get(step); + if (metainfo == null ? void 0 : metainfo.internal) + return false; + return !!(metainfo == null ? void 0 : metainfo.snapshot) && !metainfo.pausesBeforeInput; +} +function shouldSlowMo(metadata) { + const metainfo = methodMetainfo.get(metadata.type + "." + metadata.method); + return !!(metainfo == null ? void 0 : metainfo.slowMo); +} +let Dialog$1 = class Dialog extends SdkObject { + constructor(page, type2, message, onHandle, defaultValue) { + super(page, "dialog"); + this._handled = false; + this._page = page; + this._type = type2; + this._message = message; + this._onHandle = onHandle; + this._defaultValue = defaultValue || ""; + } + page() { + return this._page; + } + type() { + return this._type; + } + message() { + return this._message; + } + defaultValue() { + return this._defaultValue; + } + async accept(promptText) { + assert(!this._handled, "Cannot accept dialog which is already handled!"); + this._handled = true; + this._page.browserContext.dialogManager.dialogWillClose(this); + await this._onHandle(true, promptText); + } + async dismiss() { + assert(!this._handled, "Cannot dismiss dialog which is already handled!"); + this._handled = true; + this._page.browserContext.dialogManager.dialogWillClose(this); + await this._onHandle(false); + } + async close() { + if (this._type === "beforeunload") + await this.accept(); + else + await this.dismiss(); + } +}; +class DialogManager { + constructor(instrumentation) { + this._dialogHandlers = /* @__PURE__ */ new Set(); + this._openedDialogs = /* @__PURE__ */ new Set(); + this._instrumentation = instrumentation; + } + dialogDidOpen(dialog) { + for (const frame of dialog.page().frameManager.frames()) + frame._invalidateNonStallingEvaluations("JavaScript dialog interrupted evaluation"); + this._openedDialogs.add(dialog); + this._instrumentation.onDialog(dialog); + let hasHandlers = false; + for (const handler of this._dialogHandlers) { + if (handler(dialog)) + hasHandlers = true; + } + if (!hasHandlers) + dialog.close().then(() => { + }); + } + dialogWillClose(dialog) { + this._openedDialogs.delete(dialog); + } + addDialogHandler(handler) { + this._dialogHandlers.add(handler); + } + removeDialogHandler(handler) { + this._dialogHandlers.delete(handler); + if (!this._dialogHandlers.size) { + for (const dialog of this._openedDialogs) + dialog.close().catch(() => { + }); + } + } + hasOpenDialogsForPage(page) { + return [...this._openedDialogs].some((dialog) => dialog.page() === page); + } + async closeBeforeUnloadDialogs() { + await Promise.all([...this._openedDialogs].map(async (dialog) => { + if (dialog.type() === "beforeunload") + await dialog.dismiss(); + })); + } +} +let Artifact$1 = class Artifact extends SdkObject { + constructor(parent, localPath, unaccessibleErrorMessage, cancelCallback) { + super(parent, "artifact"); + this._finishedPromise = new ManualPromise(); + this._saveCallbacks = []; + this._finished = false; + this._deleted = false; + this._localPath = localPath; + this._unaccessibleErrorMessage = unaccessibleErrorMessage; + this._cancelCallback = cancelCallback; + } + finishedPromise() { + return this._finishedPromise; + } + localPath() { + return this._localPath; + } + async localPathAfterFinished() { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + await this._finishedPromise; + if (this._failureError) + throw this._failureError; + return this._localPath; + } + saveAs(saveCallback) { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + if (this._deleted) + throw new Error(`File already deleted. Save before deleting.`); + if (this._failureError) + throw this._failureError; + if (this._finished) { + saveCallback(this._localPath).catch(() => { + }); + return; + } + this._saveCallbacks.push(saveCallback); + } + async failureError() { + var _a2; + if (this._unaccessibleErrorMessage) + return this._unaccessibleErrorMessage; + await this._finishedPromise; + return ((_a2 = this._failureError) == null ? void 0 : _a2.message) || null; + } + async cancel() { + assert(this._cancelCallback !== void 0); + return this._cancelCallback(); + } + async delete() { + if (this._unaccessibleErrorMessage) + return; + const fileName = await this.localPathAfterFinished(); + if (this._deleted) + return; + this._deleted = true; + if (fileName) + await fs.promises.unlink(fileName).catch((e) => { + }); + } + async deleteOnContextClose() { + if (this._deleted) + return; + this._deleted = true; + if (!this._unaccessibleErrorMessage) + await fs.promises.unlink(this._localPath).catch((e) => { + }); + await this.reportFinished(new TargetClosedError$1()); + } + async reportFinished(error2) { + if (this._finished) + return; + this._finished = true; + this._failureError = error2; + if (error2) { + for (const callback of this._saveCallbacks) + await callback("", error2); + } else { + for (const callback of this._saveCallbacks) + await callback(this._localPath); + } + this._saveCallbacks = []; + this._finishedPromise.resolve(); + } +}; +const source$5 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/utilityScript.ts\nvar utilityScript_exports = {};\n__export(utilityScript_exports, {\n UtilityScript: () => UtilityScript\n});\nmodule.exports = __toCommonJS(utilityScript_exports);\n\n// packages/playwright-core/src/utils/isomorphic/utilityScriptSerializers.ts\nfunction isRegExp(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n // eslint-disable-next-line no-restricted-globals\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n return returnByValue ? this._promiseAwareJsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _promiseAwareJsonValueNoThrow(value) {\n const safeJson = (value2) => {\n try {\n return this.jsonValue(true, value2);\n } catch (e) {\n return void 0;\n }\n };\n if (value && typeof value === "object" && typeof value.then === "function") {\n return (async () => {\n const promiseValue = await value;\n return safeJson(promiseValue);\n })();\n }\n return safeJson(value);\n }\n};\n'; +function isRegExp$1(obj) { + try { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; + } catch (error2) { + return false; + } +} +function isDate$1(obj) { + try { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; + } catch (error2) { + return false; + } +} +function isURL(obj) { + try { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; + } catch (error2) { + return false; + } +} +function isError(obj) { + var _a2; + try { + return obj instanceof Error || obj && ((_a2 = Object.getPrototypeOf(obj)) == null ? void 0 : _a2.name) === "Error"; + } catch (error2) { + return false; + } +} +function isTypedArray(obj, constructor) { + try { + return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`; + } catch (error2) { + return false; + } +} +const typedArrayConstructors = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + // TODO: add Float16Array once it's in baseline + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array +}; +function typedArrayToBase64(array) { + if ("toBase64" in array) + return array.toBase64(); + const binary2 = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join(""); + return btoa(binary2); +} +function base64ToTypedArray(base64, TypedArrayConstructor) { + const binary2 = atob(base64); + const bytes = new Uint8Array(binary2.length); + for (let i = 0; i < binary2.length; i++) + bytes[i] = binary2.charCodeAt(i); + return new TypedArrayConstructor(bytes.buffer); +} +function parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) { + if (Object.is(value, void 0)) + return void 0; + if (typeof value === "object" && value) { + if ("ref" in value) + return refs.get(value.ref); + if ("v" in value) { + if (value.v === "undefined") + return void 0; + if (value.v === "null") + return null; + if (value.v === "NaN") + return NaN; + if (value.v === "Infinity") + return Infinity; + if (value.v === "-Infinity") + return -Infinity; + if (value.v === "-0") + return -0; + return void 0; + } + if ("d" in value) { + return new Date(value.d); + } + if ("u" in value) + return new URL(value.u); + if ("bi" in value) + return BigInt(value.bi); + if ("e" in value) { + const error2 = new Error(value.e.m); + error2.name = value.e.n; + error2.stack = value.e.s; + return error2; + } + if ("r" in value) + return new RegExp(value.r.p, value.r.f); + if ("a" in value) { + const result = []; + refs.set(value.id, result); + for (const a of value.a) + result.push(parseEvaluationResultValue(a, handles, refs)); + return result; + } + if ("o" in value) { + const result = {}; + refs.set(value.id, result); + for (const { k, v } of value.o) { + if (k === "__proto__") + continue; + result[k] = parseEvaluationResultValue(v, handles, refs); + } + return result; + } + if ("h" in value) + return handles[value.h]; + if ("ta" in value) + return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]); + } + return value; +} +function serializeAsCallArgument(value, handleSerializer) { + return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 }); +} +function serialize(value, handleSerializer, visitorInfo) { + if (value && typeof value === "object") { + if (typeof globalThis.Window === "function" && value instanceof globalThis.Window) + return "ref: "; + if (typeof globalThis.Document === "function" && value instanceof globalThis.Document) + return "ref: "; + if (typeof globalThis.Node === "function" && value instanceof globalThis.Node) + return "ref: "; + } + return innerSerialize(value, handleSerializer, visitorInfo); +} +function innerSerialize(value, handleSerializer, visitorInfo) { + var _a2; + const result = handleSerializer(value); + if ("fallThrough" in result) + value = result.fallThrough; + else + return result; + if (typeof value === "symbol") + return { v: "undefined" }; + if (Object.is(value, void 0)) + return { v: "undefined" }; + if (Object.is(value, null)) + return { v: "null" }; + if (Object.is(value, NaN)) + return { v: "NaN" }; + if (Object.is(value, Infinity)) + return { v: "Infinity" }; + if (Object.is(value, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value, -0)) + return { v: "-0" }; + if (typeof value === "boolean") + return value; + if (typeof value === "number") + return value; + if (typeof value === "string") + return value; + if (typeof value === "bigint") + return { bi: value.toString() }; + if (isError(value)) { + let stack; + if ((_a2 = value.stack) == null ? void 0 : _a2.startsWith(value.name + ": " + value.message)) { + stack = value.stack; + } else { + stack = `${value.name}: ${value.message} +${value.stack}`; + } + return { e: { n: value.name, m: value.message, s: stack } }; + } + if (isDate$1(value)) + return { d: value.toJSON() }; + if (isURL(value)) + return { u: value.toJSON() }; + if (isRegExp$1(value)) + return { r: { p: value.source, f: value.flags } }; + for (const [k, ctor] of Object.entries(typedArrayConstructors)) { + if (isTypedArray(value, ctor)) + return { ta: { b: typedArrayToBase64(value), k } }; + } + const id = visitorInfo.visited.get(value); + if (id) + return { ref: id }; + if (Array.isArray(value)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value, id2); + for (let i = 0; i < value.length; ++i) + a.push(serialize(value[i], handleSerializer, visitorInfo)); + return { a, id: id2 }; + } + if (typeof value === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value, id2); + for (const name of Object.keys(value)) { + let item; + try { + item = value[name]; + } catch (e) { + continue; + } + if (name === "toJSON" && typeof item === "function") + o.push({ k: name, v: { o: [], id: 0 } }); + else + o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) }); + } + let jsonWrapper; + try { + if (o.length === 0 && value.toJSON && typeof value.toJSON === "function") + jsonWrapper = { value: value.toJSON() }; + } catch (e) { + } + if (jsonWrapper) + return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo); + return { o, id: id2 }; + } +} +class ExecutionContext extends SdkObject { + constructor(parent, delegate, worldNameForTest) { + super(parent, "execution-context"); + this._contextDestroyedScope = new LongStandingScope(); + this.worldNameForTest = worldNameForTest; + this.delegate = delegate; + } + contextDestroyed(reason) { + this._contextDestroyedScope.close(new Error(reason)); + } + async _raceAgainstContextDestroyed(promise) { + return this._contextDestroyedScope.race(promise); + } + rawEvaluateJSON(expression) { + return this._raceAgainstContextDestroyed(this.delegate.rawEvaluateJSON(expression)); + } + rawEvaluateHandle(expression) { + return this._raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression)); + } + async evaluateWithArguments(expression, returnByValue, values, handles) { + const utilityScript = await this.utilityScript(); + return this._raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression, returnByValue, utilityScript, values, handles)); + } + getProperties(object) { + return this._raceAgainstContextDestroyed(this.delegate.getProperties(object)); + } + releaseHandle(handle) { + return this.delegate.releaseHandle(handle); + } + adoptIfNeeded(handle) { + return null; + } + utilityScript() { + if (!this._utilityScriptPromise) { + const source2 = ` + (() => { + const module = {}; + ${source$5} + return new (module.exports.UtilityScript())(globalThis, ${isUnderTest()}); + })();`; + this._utilityScriptPromise = this._raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, source2)).then((handle) => { + handle._setPreview("UtilityScript"); + return handle; + }); + } + return this._utilityScriptPromise; + } + async doSlowMo() { + } +} +let JSHandle$1 = class JSHandle extends SdkObject { + constructor(context, type2, preview, objectId, value) { + super(context, "handle"); + this.__jshandle = true; + this._disposed = false; + this._context = context; + this._objectId = objectId; + this._value = value; + this._objectType = type2; + this._preview = this._objectId ? preview || `JSHandle@${this._objectType}` : String(value); + if (this._objectId && globalThis.leakedJSHandles) + globalThis.leakedJSHandles.set(this, new Error("Leaked JSHandle")); + } + async evaluate(pageFunction, arg) { + return evaluate(this._context, true, pageFunction, this, arg); + } + async evaluateHandle(pageFunction, arg) { + return evaluate(this._context, false, pageFunction, this, arg); + } + async evaluateExpression(expression, options2, arg) { + const value = await evaluateExpression(this._context, expression, { ...options2, returnByValue: true }, this, arg); + await this._context.doSlowMo(); + return value; + } + async evaluateExpressionHandle(expression, options2, arg) { + const value = await evaluateExpression(this._context, expression, { ...options2, returnByValue: false }, this, arg); + await this._context.doSlowMo(); + return value; + } + async getProperty(propertyName) { + const objectHandle = await this.evaluateHandle((object, propertyName2) => { + const result2 = { __proto__: null }; + result2[propertyName2] = object[propertyName2]; + return result2; + }, propertyName); + const properties = await objectHandle.getProperties(); + const result = properties.get(propertyName); + objectHandle.dispose(); + return result; + } + async getProperties() { + if (!this._objectId) + return /* @__PURE__ */ new Map(); + return this._context.getProperties(this); + } + rawValue() { + return this._value; + } + async jsonValue() { + if (!this._objectId) + return this._value; + const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`; + return this._context.evaluateWithArguments(script, true, [true], [this]); + } + asElement() { + return null; + } + dispose() { + if (this._disposed) + return; + this._disposed = true; + if (this._objectId) { + this._context.releaseHandle(this).catch((e) => { + }); + if (globalThis.leakedJSHandles) + globalThis.leakedJSHandles.delete(this); + } + } + toString() { + return this._preview; + } + _setPreviewCallback(callback) { + this._previewCallback = callback; + } + preview() { + return this._preview; + } + worldNameForTest() { + return this._context.worldNameForTest; + } + _setPreview(preview) { + this._preview = preview; + if (this._previewCallback) + this._previewCallback(preview); + } +}; +async function evaluate(context, returnByValue, pageFunction, ...args) { + return evaluateExpression(context, String(pageFunction), { returnByValue, isFunction: typeof pageFunction === "function" }, ...args); +} +async function evaluateExpression(context, expression, options2, ...args) { + expression = normalizeEvaluationExpression(expression, options2.isFunction); + const handles = []; + const toDispose = []; + const pushHandle = (handle) => { + handles.push(handle); + return handles.length - 1; + }; + args = args.map((arg) => serializeAsCallArgument(arg, (handle) => { + if (handle instanceof JSHandle$1) { + if (!handle._objectId) + return { fallThrough: handle._value }; + if (handle._disposed) + throw new JavaScriptErrorInEvaluate("JSHandle is disposed!"); + const adopted = context.adoptIfNeeded(handle); + if (adopted === null) + return { h: pushHandle(Promise.resolve(handle)) }; + toDispose.push(adopted); + return { h: pushHandle(adopted) }; + } + return { fallThrough: handle }; + })); + const utilityScriptObjects = []; + for (const handle of await Promise.all(handles)) { + if (handle._context !== context) + throw new JavaScriptErrorInEvaluate("JSHandles can be evaluated only in the context they were created!"); + utilityScriptObjects.push(handle); + } + const utilityScriptValues = [options2.isFunction, options2.returnByValue, expression, args.length, ...args]; + const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`; + try { + return await context.evaluateWithArguments(script, options2.returnByValue || false, utilityScriptValues, utilityScriptObjects); + } finally { + toDispose.map((handlePromise) => handlePromise.then((handle) => handle.dispose())); + } +} +function parseUnserializableValue(unserializableValue) { + if (unserializableValue === "NaN") + return NaN; + if (unserializableValue === "Infinity") + return Infinity; + if (unserializableValue === "-Infinity") + return -Infinity; + if (unserializableValue === "-0") + return -0; +} +function normalizeEvaluationExpression(expression, isFunction) { + expression = expression.trim(); + if (isFunction) { + try { + new Function("(" + expression + ")"); + } catch (e1) { + if (!(e1 instanceof EvalError) || !e1.message.includes("unsafe-eval")) { + if (expression.startsWith("async ")) + expression = "async function " + expression.substring("async ".length); + else + expression = "function " + expression; + try { + new Function("(" + expression + ")"); + } catch (e2) { + throw new Error("Passed function is not well-serializable!"); + } + } + } + } + if (/^(async)?\s*function(\s|\()/.test(expression)) + expression = "(" + expression + ")"; + return expression; +} +class JavaScriptErrorInEvaluate extends Error { +} +function isJavaScriptErrorInEvaluate(error2) { + return error2 instanceof JavaScriptErrorInEvaluate; +} +function sparseArrayToString(entries) { + const arrayEntries = []; + for (const { name, value } of entries) { + const index2 = +name; + if (isNaN(index2) || index2 < 0) + continue; + arrayEntries.push({ index: index2, value }); + } + arrayEntries.sort((a, b) => a.index - b.index); + let lastIndex = -1; + const tokens = []; + for (const { index: index2, value } of arrayEntries) { + const emptyItems = index2 - lastIndex - 1; + if (emptyItems === 1) + tokens.push(`empty`); + else if (emptyItems > 1) + tokens.push(`empty x ${emptyItems}`); + tokens.push(String(value)); + lastIndex = index2; + } + return "[" + tokens.join(", ") + "]"; +} +class ProgressController { + constructor(metadata, sdkObject) { + this._forceAbortPromise = new ManualPromise(); + this._cleanups = []; + this._logName = "api"; + this._state = "before"; + this._deadline = 0; + this._timeout = 0; + this.metadata = metadata; + this.sdkObject = sdkObject; + this.instrumentation = sdkObject.instrumentation; + this._forceAbortPromise.catch((e) => null); + } + setLogName(logName) { + this._logName = logName; + } + abort(error2) { + this._forceAbortPromise.reject(error2); + } + async run(task, timeout) { + var _a2, _b2; + if (timeout) { + this._timeout = timeout; + this._deadline = timeout ? monotonicTime() + timeout : 0; + } + assert(this._state === "before"); + this._state = "running"; + (_a2 = this.sdkObject.attribution.context) == null ? void 0 : _a2._activeProgressControllers.add(this); + const progress2 = { + log: (message) => { + if (this._state === "running") + this.metadata.log.push(message); + this.instrumentation.onCallLog(this.sdkObject, this.metadata, this._logName, message); + }, + timeUntilDeadline: () => this._deadline ? this._deadline - monotonicTime() : 2147483647, + // 2^31-1 safe setTimeout in Node. + isRunning: () => this._state === "running", + cleanupWhenAborted: (cleanup) => { + if (this._state === "running") + this._cleanups.push(cleanup); + else + runCleanup(cleanup); + }, + throwIfAborted: () => { + if (this._state === "aborted") + throw new AbortedError(); + }, + metadata: this.metadata + }; + const timeoutError = new TimeoutError$1(`Timeout ${this._timeout}ms exceeded.`); + const timer = setTimeout(() => this._forceAbortPromise.reject(timeoutError), progress2.timeUntilDeadline()); + try { + const promise = task(progress2); + const result = await Promise.race([promise, this._forceAbortPromise]); + this._state = "finished"; + return result; + } catch (e) { + this._state = "aborted"; + await Promise.all(this._cleanups.splice(0).map(runCleanup)); + throw e; + } finally { + (_b2 = this.sdkObject.attribution.context) == null ? void 0 : _b2._activeProgressControllers.delete(this); + clearTimeout(timer); + } + } +} +async function runCleanup(cleanup) { + try { + await cleanup(); + } catch (e) { + } +} +class AbortedError extends Error { +} +const fileUploadSizeLimit$1 = 50 * 1024 * 1024; +async function filesExceedUploadLimit(files) { + const sizes = await Promise.all(files.map(async (file) => (await fs.promises.stat(file)).size)); + return sizes.reduce((total, size) => total + size, 0) >= fileUploadSizeLimit$1; +} +async function prepareFilesForUpload(frame, params) { + const { payloads, streams, directoryStream } = params; + let { localPaths, localDirectory } = params; + if ([payloads, localPaths, localDirectory, streams, directoryStream].filter(Boolean).length !== 1) + throw new Error("Exactly one of payloads, localPaths and streams must be provided"); + if (streams) + localPaths = streams.map((c) => c.path()); + if (directoryStream) + localDirectory = directoryStream.path(); + if (localPaths) { + for (const p of localPaths) + assert(path.isAbsolute(p) && path.resolve(p) === p, "Paths provided to localPaths must be absolute and fully resolved."); + } + let fileBuffers = payloads; + if (!frame._page.browserContext._browser._isCollocatedWithServer) { + if (localPaths) { + if (await filesExceedUploadLimit(localPaths)) + throw new Error("Cannot transfer files larger than 50Mb to a browser not co-located with the server"); + fileBuffers = await Promise.all(localPaths.map(async (item) => { + return { + name: path.basename(item), + buffer: await fs.promises.readFile(item), + lastModifiedMs: (await fs.promises.stat(item)).mtimeMs + }; + })); + localPaths = void 0; + } + } + const filePayloads = fileBuffers == null ? void 0 : fileBuffers.map((payload) => ({ + name: payload.name, + mimeType: payload.mimeType || mime.getType(payload.name) || "application/octet-stream", + buffer: payload.buffer.toString("base64"), + lastModifiedMs: payload.lastModifiedMs + })); + return { localPaths, localDirectory, filePayloads }; +} +const source$4 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/injectedScript.ts\nvar injectedScript_exports = {};\n__export(injectedScript_exports, {\n InjectedScript: () => InjectedScript\n});\nmodule.exports = __toCommonJS(injectedScript_exports);\n\n// packages/playwright-core/src/utils/isomorphic/ariaSnapshot.ts\nfunction parseAriaSnapshot(yaml, text, options = {}) {\n var _a;\n const lineCounter = new yaml.LineCounter();\n const parseOptions = {\n keepSourceTokens: true,\n lineCounter,\n ...options\n };\n const yamlDoc = yaml.parseDocument(text, parseOptions);\n const errors = [];\n const convertRange = (range) => {\n return [lineCounter.linePos(range[0]), lineCounter.linePos(range[1])];\n };\n const addError = (error) => {\n errors.push({\n message: error.message,\n range: [lineCounter.linePos(error.pos[0]), lineCounter.linePos(error.pos[1])]\n });\n };\n const convertSeq = (container, seq) => {\n for (const item of seq.items) {\n const itemIsString = item instanceof yaml.Scalar && typeof item.value === "string";\n if (itemIsString) {\n const childNode = KeyParser.parse(item, parseOptions, errors);\n if (childNode) {\n container.children = container.children || [];\n container.children.push(childNode);\n }\n continue;\n }\n const itemIsMap = item instanceof yaml.YAMLMap;\n if (itemIsMap) {\n convertMap(container, item);\n continue;\n }\n errors.push({\n message: "Sequence items should be strings or maps",\n range: convertRange(item.range || seq.range)\n });\n }\n };\n const convertMap = (container, map) => {\n var _a2;\n for (const entry of map.items) {\n container.children = container.children || [];\n const keyIsString = entry.key instanceof yaml.Scalar && typeof entry.key.value === "string";\n if (!keyIsString) {\n errors.push({\n message: "Only string keys are supported",\n range: convertRange(entry.key.range || map.range)\n });\n continue;\n }\n const key = entry.key;\n const value = entry.value;\n if (key.value === "text") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Text value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n kind: "text",\n text: valueOrRegex(value.value)\n });\n continue;\n }\n if (key.value === "/children") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString || value.value !== "contain" && value.value !== "equal" && value.value !== "deep-equal") {\n errors.push({\n message: \'Strict value should be "contain", "equal" or "deep-equal"\',\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.containerMode = value.value;\n continue;\n }\n if (key.value.startsWith("/")) {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Property value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.props = (_a2 = container.props) != null ? _a2 : {};\n container.props[key.value.slice(1)] = valueOrRegex(value.value);\n continue;\n }\n const childNode = KeyParser.parse(key, parseOptions, errors);\n if (!childNode)\n continue;\n const valueIsScalar = value instanceof yaml.Scalar;\n if (valueIsScalar) {\n const type = typeof value.value;\n if (type !== "string" && type !== "number" && type !== "boolean") {\n errors.push({\n message: "Node value should be a string or a sequence",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n ...childNode,\n children: [{\n kind: "text",\n text: valueOrRegex(String(value.value))\n }]\n });\n continue;\n }\n const valueIsSequence = value instanceof yaml.YAMLSeq;\n if (valueIsSequence) {\n container.children.push(childNode);\n convertSeq(childNode, value);\n continue;\n }\n errors.push({\n message: "Map values should be strings or sequences",\n range: convertRange(entry.value.range || map.range)\n });\n }\n };\n const fragment = { kind: "role", role: "fragment" };\n yamlDoc.errors.forEach(addError);\n if (errors.length)\n return { errors, fragment };\n if (!(yamlDoc.contents instanceof yaml.YAMLSeq)) {\n errors.push({\n message: \'Aria snapshot must be a YAML sequence, elements starting with " -"\',\n range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }]\n });\n }\n if (errors.length)\n return { errors, fragment };\n convertSeq(fragment, yamlDoc.contents);\n if (errors.length)\n return { errors, fragment: emptyFragment };\n if (((_a = fragment.children) == null ? void 0 : _a.length) === 1)\n return { fragment: fragment.children[0], errors };\n return { fragment, errors };\n}\nvar emptyFragment = { kind: "role", role: "fragment" };\nfunction normalizeWhitespace(text) {\n return text.replace(/[\\u200b\\u00ad]/g, "").replace(/[\\r\\n\\s\\t]+/g, " ").trim();\n}\nfunction valueOrRegex(value) {\n return value.startsWith("/") && value.endsWith("/") && value.length > 1 ? { pattern: value.slice(1, -1) } : normalizeWhitespace(value);\n}\nvar KeyParser = class _KeyParser {\n static parse(text, options, errors) {\n try {\n return new _KeyParser(text.value)._parse();\n } catch (e) {\n if (e instanceof ParserError) {\n const message = options.prettyErrors === false ? e.message : e.message + ":\\n\\n" + text.value + "\\n" + " ".repeat(e.pos) + "^\\n";\n errors.push({\n message,\n range: [options.lineCounter.linePos(text.range[0]), options.lineCounter.linePos(text.range[0] + e.pos)]\n });\n return null;\n }\n throw e;\n }\n }\n constructor(input) {\n this._input = input;\n this._pos = 0;\n this._length = input.length;\n }\n _peek() {\n return this._input[this._pos] || "";\n }\n _next() {\n if (this._pos < this._length)\n return this._input[this._pos++];\n return null;\n }\n _eof() {\n return this._pos >= this._length;\n }\n _isWhitespace() {\n return !this._eof() && /\\s/.test(this._peek());\n }\n _skipWhitespace() {\n while (this._isWhitespace())\n this._pos++;\n }\n _readIdentifier(type) {\n if (this._eof())\n this._throwError(`Unexpected end of input when expecting ${type}`);\n const start = this._pos;\n while (!this._eof() && /[a-zA-Z]/.test(this._peek()))\n this._pos++;\n return this._input.slice(start, this._pos);\n }\n _readString() {\n let result = "";\n let escaped = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n } else if (ch === \'"\') {\n return result;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated string");\n }\n _throwError(message, offset = 0) {\n throw new ParserError(message, offset || this._pos);\n }\n _readRegex() {\n let result = "";\n let escaped = false;\n let insideClass = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n result += ch;\n } else if (ch === "/" && !insideClass) {\n return { pattern: result };\n } else if (ch === "[") {\n insideClass = true;\n result += ch;\n } else if (ch === "]" && insideClass) {\n result += ch;\n insideClass = false;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated regex");\n }\n _readStringOrRegex() {\n const ch = this._peek();\n if (ch === \'"\') {\n this._next();\n return normalizeWhitespace(this._readString());\n }\n if (ch === "/") {\n this._next();\n return this._readRegex();\n }\n return null;\n }\n _readAttributes(result) {\n let errorPos = this._pos;\n while (true) {\n this._skipWhitespace();\n if (this._peek() === "[") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n const flagName = this._readIdentifier("attribute");\n this._skipWhitespace();\n let flagValue = "";\n if (this._peek() === "=") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n while (this._peek() !== "]" && !this._isWhitespace() && !this._eof())\n flagValue += this._next();\n }\n this._skipWhitespace();\n if (this._peek() !== "]")\n this._throwError("Expected ]");\n this._next();\n this._applyAttribute(result, flagName, flagValue || "true", errorPos);\n } else {\n break;\n }\n }\n }\n _parse() {\n this._skipWhitespace();\n const role = this._readIdentifier("role");\n this._skipWhitespace();\n const name = this._readStringOrRegex() || "";\n const result = { kind: "role", role, name };\n this._readAttributes(result);\n this._skipWhitespace();\n if (!this._eof())\n this._throwError("Unexpected input");\n return result;\n }\n _applyAttribute(node, key, value, errorPos) {\n if (key === "checked") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "checked" attribute must be a boolean or "mixed"\', errorPos);\n node.checked = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "disabled") {\n this._assert(value === "true" || value === "false", \'Value of "disabled" attribute must be a boolean\', errorPos);\n node.disabled = value === "true";\n return;\n }\n if (key === "expanded") {\n this._assert(value === "true" || value === "false", \'Value of "expanded" attribute must be a boolean\', errorPos);\n node.expanded = value === "true";\n return;\n }\n if (key === "level") {\n this._assert(!isNaN(Number(value)), \'Value of "level" attribute must be a number\', errorPos);\n node.level = Number(value);\n return;\n }\n if (key === "pressed") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "pressed" attribute must be a boolean or "mixed"\', errorPos);\n node.pressed = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "selected") {\n this._assert(value === "true" || value === "false", \'Value of "selected" attribute must be a boolean\', errorPos);\n node.selected = value === "true";\n return;\n }\n this._assert(false, `Unsupported attribute [${key}]`, errorPos);\n }\n _assert(value, message, valuePos) {\n if (!value)\n this._throwError(message || "Assertion error", valuePos);\n }\n};\nvar ParserError = class extends Error {\n constructor(message, pos) {\n super(message);\n this.pos = pos;\n }\n};\n\n// packages/playwright-core/src/utils/isomorphic/cssTokenizer.ts\nvar between = function(num, first, last) {\n return num >= first && num <= last;\n};\nfunction digit(code) {\n return between(code, 48, 57);\n}\nfunction hexdigit(code) {\n return digit(code) || between(code, 65, 70) || between(code, 97, 102);\n}\nfunction uppercaseletter(code) {\n return between(code, 65, 90);\n}\nfunction lowercaseletter(code) {\n return between(code, 97, 122);\n}\nfunction letter(code) {\n return uppercaseletter(code) || lowercaseletter(code);\n}\nfunction nonascii(code) {\n return code >= 128;\n}\nfunction namestartchar(code) {\n return letter(code) || nonascii(code) || code === 95;\n}\nfunction namechar(code) {\n return namestartchar(code) || digit(code) || code === 45;\n}\nfunction nonprintable(code) {\n return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127;\n}\nfunction newline(code) {\n return code === 10;\n}\nfunction whitespace(code) {\n return newline(code) || code === 9 || code === 32;\n}\nvar maximumallowedcodepoint = 1114111;\nvar InvalidCharacterError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "InvalidCharacterError";\n }\n};\nfunction preprocess(str) {\n const codepoints = [];\n for (let i = 0; i < str.length; i++) {\n let code = str.charCodeAt(i);\n if (code === 13 && str.charCodeAt(i + 1) === 10) {\n code = 10;\n i++;\n }\n if (code === 13 || code === 12)\n code = 10;\n if (code === 0)\n code = 65533;\n if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) {\n const lead = code - 55296;\n const trail = str.charCodeAt(i + 1) - 56320;\n code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail;\n i++;\n }\n codepoints.push(code);\n }\n return codepoints;\n}\nfunction stringFromCode(code) {\n if (code <= 65535)\n return String.fromCharCode(code);\n code -= Math.pow(2, 16);\n const lead = Math.floor(code / Math.pow(2, 10)) + 55296;\n const trail = code % Math.pow(2, 10) + 56320;\n return String.fromCharCode(lead) + String.fromCharCode(trail);\n}\nfunction tokenize(str1) {\n const str = preprocess(str1);\n let i = -1;\n const tokens = [];\n let code;\n let line = 0;\n let column = 0;\n let lastLineLength = 0;\n const incrLineno = function() {\n line += 1;\n lastLineLength = column;\n column = 0;\n };\n const locStart = { line, column };\n const codepoint = function(i2) {\n if (i2 >= str.length)\n return -1;\n return str[i2];\n };\n const next = function(num) {\n if (num === void 0)\n num = 1;\n if (num > 3)\n throw "Spec Error: no more than three codepoints of lookahead.";\n return codepoint(i + num);\n };\n const consume = function(num) {\n if (num === void 0)\n num = 1;\n i += num;\n code = codepoint(i);\n if (newline(code))\n incrLineno();\n else\n column += num;\n return true;\n };\n const reconsume = function() {\n i -= 1;\n if (newline(code)) {\n line -= 1;\n column = lastLineLength;\n } else {\n column -= 1;\n }\n locStart.line = line;\n locStart.column = column;\n return true;\n };\n const eof = function(codepoint2) {\n if (codepoint2 === void 0)\n codepoint2 = code;\n return codepoint2 === -1;\n };\n const donothing = function() {\n };\n const parseerror = function() {\n };\n const consumeAToken = function() {\n consumeComments();\n consume();\n if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n return new WhitespaceToken();\n } else if (code === 34) {\n return consumeAStringToken();\n } else if (code === 35) {\n if (namechar(next()) || areAValidEscape(next(1), next(2))) {\n const token = new HashToken("");\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n token.type = "id";\n token.value = consumeAName();\n return token;\n } else {\n return new DelimToken(code);\n }\n } else if (code === 36) {\n if (next() === 61) {\n consume();\n return new SuffixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 39) {\n return consumeAStringToken();\n } else if (code === 40) {\n return new OpenParenToken();\n } else if (code === 41) {\n return new CloseParenToken();\n } else if (code === 42) {\n if (next() === 61) {\n consume();\n return new SubstringMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 43) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 44) {\n return new CommaToken();\n } else if (code === 45) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else if (next(1) === 45 && next(2) === 62) {\n consume(2);\n return new CDCToken();\n } else if (startsWithAnIdentifier()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 46) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 58) {\n return new ColonToken();\n } else if (code === 59) {\n return new SemicolonToken();\n } else if (code === 60) {\n if (next(1) === 33 && next(2) === 45 && next(3) === 45) {\n consume(3);\n return new CDOToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 64) {\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n return new AtKeywordToken(consumeAName());\n else\n return new DelimToken(code);\n } else if (code === 91) {\n return new OpenSquareToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n parseerror();\n return new DelimToken(code);\n }\n } else if (code === 93) {\n return new CloseSquareToken();\n } else if (code === 94) {\n if (next() === 61) {\n consume();\n return new PrefixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 123) {\n return new OpenCurlyToken();\n } else if (code === 124) {\n if (next() === 61) {\n consume();\n return new DashMatchToken();\n } else if (next() === 124) {\n consume();\n return new ColumnToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 125) {\n return new CloseCurlyToken();\n } else if (code === 126) {\n if (next() === 61) {\n consume();\n return new IncludeMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (digit(code)) {\n reconsume();\n return consumeANumericToken();\n } else if (namestartchar(code)) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else if (eof()) {\n return new EOFToken();\n } else {\n return new DelimToken(code);\n }\n };\n const consumeComments = function() {\n while (next(1) === 47 && next(2) === 42) {\n consume(2);\n while (true) {\n consume();\n if (code === 42 && next() === 47) {\n consume();\n break;\n } else if (eof()) {\n parseerror();\n return;\n }\n }\n }\n };\n const consumeANumericToken = function() {\n const num = consumeANumber();\n if (wouldStartAnIdentifier(next(1), next(2), next(3))) {\n const token = new DimensionToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n token.unit = consumeAName();\n return token;\n } else if (next() === 37) {\n consume();\n const token = new PercentageToken();\n token.value = num.value;\n token.repr = num.repr;\n return token;\n } else {\n const token = new NumberToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n return token;\n }\n };\n const consumeAnIdentlikeToken = function() {\n const str2 = consumeAName();\n if (str2.toLowerCase() === "url" && next() === 40) {\n consume();\n while (whitespace(next(1)) && whitespace(next(2)))\n consume();\n if (next() === 34 || next() === 39)\n return new FunctionToken(str2);\n else if (whitespace(next()) && (next(2) === 34 || next(2) === 39))\n return new FunctionToken(str2);\n else\n return consumeAURLToken();\n } else if (next() === 40) {\n consume();\n return new FunctionToken(str2);\n } else {\n return new IdentToken(str2);\n }\n };\n const consumeAStringToken = function(endingCodePoint) {\n if (endingCodePoint === void 0)\n endingCodePoint = code;\n let string = "";\n while (consume()) {\n if (code === endingCodePoint || eof()) {\n return new StringToken(string);\n } else if (newline(code)) {\n parseerror();\n reconsume();\n return new BadStringToken();\n } else if (code === 92) {\n if (eof(next()))\n donothing();\n else if (newline(next()))\n consume();\n else\n string += stringFromCode(consumeEscape());\n } else {\n string += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeAURLToken = function() {\n const token = new URLToken("");\n while (whitespace(next()))\n consume();\n if (eof(next()))\n return token;\n while (consume()) {\n if (code === 41 || eof()) {\n return token;\n } else if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n if (next() === 41 || eof(next())) {\n consume();\n return token;\n } else {\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n token.value += stringFromCode(consumeEscape());\n } else {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else {\n token.value += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeEscape = function() {\n consume();\n if (hexdigit(code)) {\n const digits = [code];\n for (let total = 0; total < 5; total++) {\n if (hexdigit(next())) {\n consume();\n digits.push(code);\n } else {\n break;\n }\n }\n if (whitespace(next()))\n consume();\n let value = parseInt(digits.map(function(x) {\n return String.fromCharCode(x);\n }).join(""), 16);\n if (value > maximumallowedcodepoint)\n value = 65533;\n return value;\n } else if (eof()) {\n return 65533;\n } else {\n return code;\n }\n };\n const areAValidEscape = function(c1, c2) {\n if (c1 !== 92)\n return false;\n if (newline(c2))\n return false;\n return true;\n };\n const startsWithAValidEscape = function() {\n return areAValidEscape(code, next());\n };\n const wouldStartAnIdentifier = function(c1, c2, c3) {\n if (c1 === 45)\n return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3);\n else if (namestartchar(c1))\n return true;\n else if (c1 === 92)\n return areAValidEscape(c1, c2);\n else\n return false;\n };\n const startsWithAnIdentifier = function() {\n return wouldStartAnIdentifier(code, next(1), next(2));\n };\n const wouldStartANumber = function(c1, c2, c3) {\n if (c1 === 43 || c1 === 45) {\n if (digit(c2))\n return true;\n if (c2 === 46 && digit(c3))\n return true;\n return false;\n } else if (c1 === 46) {\n if (digit(c2))\n return true;\n return false;\n } else if (digit(c1)) {\n return true;\n } else {\n return false;\n }\n };\n const startsWithANumber = function() {\n return wouldStartANumber(code, next(1), next(2));\n };\n const consumeAName = function() {\n let result = "";\n while (consume()) {\n if (namechar(code)) {\n result += stringFromCode(code);\n } else if (startsWithAValidEscape()) {\n result += stringFromCode(consumeEscape());\n } else {\n reconsume();\n return result;\n }\n }\n throw new Error("Internal parse error");\n };\n const consumeANumber = function() {\n let repr = "";\n let type = "integer";\n if (next() === 43 || next() === 45) {\n consume();\n repr += stringFromCode(code);\n }\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n if (next(1) === 46 && digit(next(2))) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const c1 = next(1), c2 = next(2), c3 = next(3);\n if ((c1 === 69 || c1 === 101) && digit(c2)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const value = convertAStringToANumber(repr);\n return { type, value, repr };\n };\n const convertAStringToANumber = function(string) {\n return +string;\n };\n const consumeTheRemnantsOfABadURL = function() {\n while (consume()) {\n if (code === 41 || eof()) {\n return;\n } else if (startsWithAValidEscape()) {\n consumeEscape();\n donothing();\n } else {\n donothing();\n }\n }\n };\n let iterationCount = 0;\n while (!eof(next())) {\n tokens.push(consumeAToken());\n iterationCount++;\n if (iterationCount > str.length * 2)\n throw new Error("I\'m infinite-looping!");\n }\n return tokens;\n}\nvar CSSParserToken = class {\n constructor() {\n this.tokenType = "";\n }\n toJSON() {\n return { token: this.tokenType };\n }\n toString() {\n return this.tokenType;\n }\n toSource() {\n return "" + this;\n }\n};\nvar BadStringToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADSTRING";\n }\n};\nvar BadURLToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADURL";\n }\n};\nvar WhitespaceToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "WHITESPACE";\n }\n toString() {\n return "WS";\n }\n toSource() {\n return " ";\n }\n};\nvar CDOToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "CDO";\n }\n toSource() {\n return "";\n }\n};\nvar ColonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ":";\n }\n};\nvar SemicolonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ";";\n }\n};\nvar CommaToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ",";\n }\n};\nvar GroupingToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n this.mirror = "";\n }\n};\nvar OpenCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "{";\n this.value = "{";\n this.mirror = "}";\n }\n};\nvar CloseCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "}";\n this.value = "}";\n this.mirror = "{";\n }\n};\nvar OpenSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "[";\n this.value = "[";\n this.mirror = "]";\n }\n};\nvar CloseSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "]";\n this.value = "]";\n this.mirror = "[";\n }\n};\nvar OpenParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "(";\n this.value = "(";\n this.mirror = ")";\n }\n};\nvar CloseParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = ")";\n this.value = ")";\n this.mirror = "(";\n }\n};\nvar IncludeMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "~=";\n }\n};\nvar DashMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "|=";\n }\n};\nvar PrefixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "^=";\n }\n};\nvar SuffixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "$=";\n }\n};\nvar SubstringMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "*=";\n }\n};\nvar ColumnToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "||";\n }\n};\nvar EOFToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "EOF";\n }\n toSource() {\n return "";\n }\n};\nvar DelimToken = class extends CSSParserToken {\n constructor(code) {\n super();\n this.tokenType = "DELIM";\n this.value = "";\n this.value = stringFromCode(code);\n }\n toString() {\n return "DELIM(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n toSource() {\n if (this.value === "\\\\")\n return "\\\\\\n";\n else\n return this.value;\n }\n};\nvar StringValuedToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n }\n ASCIIMatch(str) {\n return this.value.toLowerCase() === str.toLowerCase();\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n};\nvar IdentToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "IDENT";\n this.value = val;\n }\n toString() {\n return "IDENT(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value);\n }\n};\nvar FunctionToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "FUNCTION";\n this.value = val;\n this.mirror = ")";\n }\n toString() {\n return "FUNCTION(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value) + "(";\n }\n};\nvar AtKeywordToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "AT-KEYWORD";\n this.value = val;\n }\n toString() {\n return "AT(" + this.value + ")";\n }\n toSource() {\n return "@" + escapeIdent(this.value);\n }\n};\nvar HashToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "HASH";\n this.value = val;\n this.type = "unrestricted";\n }\n toString() {\n return "HASH(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n return json;\n }\n toSource() {\n if (this.type === "id")\n return "#" + escapeIdent(this.value);\n else\n return "#" + escapeHash(this.value);\n }\n};\nvar StringToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "STRING";\n this.value = val;\n }\n toString() {\n return \'"\' + escapeString(this.value) + \'"\';\n }\n};\nvar URLToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "URL";\n this.value = val;\n }\n toString() {\n return "URL(" + this.value + ")";\n }\n toSource() {\n return \'url("\' + escapeString(this.value) + \'")\';\n }\n};\nvar NumberToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "NUMBER";\n this.type = "integer";\n this.repr = "";\n }\n toString() {\n if (this.type === "integer")\n return "INT(" + this.value + ")";\n return "NUMBER(" + this.value + ")";\n }\n toJSON() {\n const json = super.toJSON();\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr;\n }\n};\nvar PercentageToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "PERCENTAGE";\n this.repr = "";\n }\n toString() {\n return "PERCENTAGE(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr + "%";\n }\n};\nvar DimensionToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "DIMENSION";\n this.type = "integer";\n this.repr = "";\n this.unit = "";\n }\n toString() {\n return "DIM(" + this.value + "," + this.unit + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n json.unit = this.unit;\n return json;\n }\n toSource() {\n const source = this.repr;\n let unit = escapeIdent(this.unit);\n if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) {\n unit = "\\\\65 " + unit.slice(1, unit.length);\n }\n return source + unit;\n }\n};\nfunction escapeIdent(string) {\n string = "" + string;\n let result = "";\n const firstcode = string.charCodeAt(0);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45)\n result += "\\\\" + code.toString(16) + " ";\n else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + string[i];\n }\n return result;\n}\nfunction escapeHash(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + code.toString(16) + " ";\n }\n return result;\n}\nfunction escapeString(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127)\n result += "\\\\" + code.toString(16) + " ";\n else if (code === 34 || code === 92)\n result += "\\\\" + string[i];\n else\n result += string[i];\n }\n return result;\n}\n\n// packages/playwright-core/src/utils/isomorphic/cssParser.ts\nvar InvalidSelectorError = class extends Error {\n};\nfunction parseCSS(selector, customNames) {\n let tokens;\n try {\n tokens = tokenize(selector);\n if (!(tokens[tokens.length - 1] instanceof EOFToken))\n tokens.push(new EOFToken());\n } catch (e) {\n const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`;\n const index = (e.stack || "").indexOf(e.message);\n if (index !== -1)\n e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);\n e.message = newMessage;\n throw e;\n }\n const unsupportedToken = tokens.find((token) => {\n return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings.\n // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }\n // Or this way :xpath( {complex-xpath-goes-here("hello")} )\n token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings?\n token instanceof URLToken || token instanceof PercentageToken;\n });\n if (unsupportedToken)\n throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n let pos = 0;\n const names = /* @__PURE__ */ new Set();\n function unexpected() {\n return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n }\n function skipWhitespace() {\n while (tokens[pos] instanceof WhitespaceToken)\n pos++;\n }\n function isIdent(p = pos) {\n return tokens[p] instanceof IdentToken;\n }\n function isString(p = pos) {\n return tokens[p] instanceof StringToken;\n }\n function isNumber(p = pos) {\n return tokens[p] instanceof NumberToken;\n }\n function isComma(p = pos) {\n return tokens[p] instanceof CommaToken;\n }\n function isOpenParen(p = pos) {\n return tokens[p] instanceof OpenParenToken;\n }\n function isCloseParen(p = pos) {\n return tokens[p] instanceof CloseParenToken;\n }\n function isFunction(p = pos) {\n return tokens[p] instanceof FunctionToken;\n }\n function isStar(p = pos) {\n return tokens[p] instanceof DelimToken && tokens[p].value === "*";\n }\n function isEOF(p = pos) {\n return tokens[p] instanceof EOFToken;\n }\n function isClauseCombinator(p = pos) {\n return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value);\n }\n function isSelectorClauseEnd(p = pos) {\n return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken;\n }\n function consumeFunctionArguments() {\n const result2 = [consumeArgument()];\n while (true) {\n skipWhitespace();\n if (!isComma())\n break;\n pos++;\n result2.push(consumeArgument());\n }\n return result2;\n }\n function consumeArgument() {\n skipWhitespace();\n if (isNumber())\n return tokens[pos++].value;\n if (isString())\n return tokens[pos++].value;\n return consumeComplexSelector();\n }\n function consumeComplexSelector() {\n const result2 = { simples: [] };\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" });\n } else {\n result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" });\n }\n while (true) {\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value;\n skipWhitespace();\n } else if (isSelectorClauseEnd()) {\n break;\n }\n result2.simples.push({ combinator: "", selector: consumeSimpleSelector() });\n }\n return result2;\n }\n function consumeSimpleSelector() {\n let rawCSSString = "";\n const functions = [];\n while (!isSelectorClauseEnd()) {\n if (isIdent() || isStar()) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof HashToken) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") {\n pos++;\n if (isIdent())\n rawCSSString += "." + tokens[pos++].toSource();\n else\n throw unexpected();\n } else if (tokens[pos] instanceof ColonToken) {\n pos++;\n if (isIdent()) {\n if (!customNames.has(tokens[pos].value.toLowerCase())) {\n rawCSSString += ":" + tokens[pos++].toSource();\n } else {\n const name = tokens[pos++].value.toLowerCase();\n functions.push({ name, args: [] });\n names.add(name);\n }\n } else if (isFunction()) {\n const name = tokens[pos++].value.toLowerCase();\n if (!customNames.has(name)) {\n rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;\n } else {\n functions.push({ name, args: consumeFunctionArguments() });\n names.add(name);\n }\n skipWhitespace();\n if (!isCloseParen())\n throw unexpected();\n pos++;\n } else {\n throw unexpected();\n }\n } else if (tokens[pos] instanceof OpenSquareToken) {\n rawCSSString += "[";\n pos++;\n while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF())\n rawCSSString += tokens[pos++].toSource();\n if (!(tokens[pos] instanceof CloseSquareToken))\n throw unexpected();\n rawCSSString += "]";\n pos++;\n } else {\n throw unexpected();\n }\n }\n if (!rawCSSString && !functions.length)\n throw unexpected();\n return { css: rawCSSString || void 0, functions };\n }\n function consumeBuiltinFunctionArguments() {\n let s = "";\n let balance = 1;\n while (!isEOF()) {\n if (isOpenParen() || isFunction())\n balance++;\n if (isCloseParen())\n balance--;\n if (!balance)\n break;\n s += tokens[pos++].toSource();\n }\n return s;\n }\n const result = consumeFunctionArguments();\n if (!isEOF())\n throw unexpected();\n if (result.some((arg) => typeof arg !== "object" || !("simples" in arg)))\n throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n return { selector: result, names: Array.from(names) };\n}\n\n// packages/playwright-core/src/utils/isomorphic/selectorParser.ts\nvar kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]);\nvar kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]);\nvar customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]);\nfunction parseSelector(selector) {\n const parsedStrings = parseSelectorString(selector);\n const parts = [];\n for (const part of parsedStrings.parts) {\n if (part.name === "css" || part.name === "css:light") {\n if (part.name === "css:light")\n part.body = ":light(" + part.body + ")";\n const parsedCSS = parseCSS(part.body, customCSSNames);\n parts.push({\n name: "css",\n body: parsedCSS.selector,\n source: part.body\n });\n continue;\n }\n if (kNestedSelectorNames.has(part.name)) {\n let innerSelector;\n let distance;\n try {\n const unescaped = JSON.parse("[" + part.body + "]");\n if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string")\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n innerSelector = unescaped[0];\n if (unescaped.length === 2) {\n if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name))\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n distance = unescaped[1];\n }\n } catch (e) {\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n }\n const nested = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } };\n const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame");\n const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1;\n if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), parts.slice(0, lastFrameIndex + 1)))\n nested.body.parsed.parts.splice(0, lastFrameIndex + 1);\n parts.push(nested);\n continue;\n }\n parts.push({ ...part, source: part.body });\n }\n if (kNestedSelectorNames.has(parts[0].name))\n throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`);\n return {\n capture: parsedStrings.capture,\n parts\n };\n}\nfunction selectorPartsEqual(list1, list2) {\n return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 });\n}\nfunction stringifySelector(selector, forceEngineName) {\n if (typeof selector === "string")\n return selector;\n return selector.parts.map((p, i) => {\n let includeEngine = true;\n if (!forceEngineName && i !== selector.capture) {\n if (p.name === "css")\n includeEngine = false;\n else if (p.name === "xpath" && p.source.startsWith("//") || p.source.startsWith(".."))\n includeEngine = false;\n }\n const prefix = includeEngine ? p.name + "=" : "";\n return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`;\n }).join(" >> ");\n}\nfunction visitAllSelectorParts(selector, visitor) {\n const visit = (selector2, nested) => {\n for (const part of selector2.parts) {\n visitor(part, nested);\n if (kNestedSelectorNames.has(part.name))\n visit(part.body.parsed, true);\n }\n };\n visit(selector, false);\n}\nfunction parseSelectorString(selector) {\n let index = 0;\n let quote;\n let start = 0;\n const result = { parts: [] };\n const append = () => {\n const part = selector.substring(start, index).trim();\n const eqIndex = part.indexOf("=");\n let name;\n let body;\n if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {\n name = part.substring(0, eqIndex).trim();\n body = part.substring(eqIndex + 1);\n } else if (part.length > 1 && part[0] === \'"\' && part[part.length - 1] === \'"\') {\n name = "text";\n body = part;\n } else if (part.length > 1 && part[0] === "\'" && part[part.length - 1] === "\'") {\n name = "text";\n body = part;\n } else if (/^\\(*\\/\\//.test(part) || part.startsWith("..")) {\n name = "xpath";\n body = part;\n } else {\n name = "css";\n body = part;\n }\n let capture = false;\n if (name[0] === "*") {\n capture = true;\n name = name.substring(1);\n }\n result.parts.push({ name, body });\n if (capture) {\n if (result.capture !== void 0)\n throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`);\n result.capture = result.parts.length - 1;\n }\n };\n if (!selector.includes(">>")) {\n index = selector.length;\n append();\n return result;\n }\n const shouldIgnoreTextSelectorQuote = () => {\n const prefix = selector.substring(start, index);\n const match = prefix.match(/^\\s*text\\s*=(.*)$/);\n return !!match && !!match[1];\n };\n while (index < selector.length) {\n const c = selector[index];\n if (c === "\\\\" && index + 1 < selector.length) {\n index += 2;\n } else if (c === quote) {\n quote = void 0;\n index++;\n } else if (!quote && (c === \'"\' || c === "\'" || c === "`") && !shouldIgnoreTextSelectorQuote()) {\n quote = c;\n index++;\n } else if (!quote && c === ">" && selector[index + 1] === ">") {\n append();\n index += 2;\n start = index;\n } else {\n index++;\n }\n }\n append();\n return result;\n}\nfunction parseAttributeSelector(selector, allowUnquotedStrings) {\n let wp = 0;\n let EOL = selector.length === 0;\n const next = () => selector[wp] || "";\n const eat1 = () => {\n const result2 = next();\n ++wp;\n EOL = wp >= selector.length;\n return result2;\n };\n const syntaxError = (stage) => {\n if (EOL)\n throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \\`${selector}\\``);\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : ""));\n };\n function skipSpaces() {\n while (!EOL && /\\s/.test(next()))\n eat1();\n }\n function isCSSNameChar(char) {\n return char >= "\\x80" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-";\n }\n function readIdentifier() {\n let result2 = "";\n skipSpaces();\n while (!EOL && isCSSNameChar(next()))\n result2 += eat1();\n return result2;\n }\n function readQuotedString(quote) {\n let result2 = eat1();\n if (result2 !== quote)\n syntaxError("parsing quoted string");\n while (!EOL && next() !== quote) {\n if (next() === "\\\\")\n eat1();\n result2 += eat1();\n }\n if (next() !== quote)\n syntaxError("parsing quoted string");\n result2 += eat1();\n return result2;\n }\n function readRegularExpression() {\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let source = "";\n let inClass = false;\n while (!EOL) {\n if (next() === "\\\\") {\n source += eat1();\n if (EOL)\n syntaxError("parsing regular expression");\n } else if (inClass && next() === "]") {\n inClass = false;\n } else if (!inClass && next() === "[") {\n inClass = true;\n } else if (!inClass && next() === "/") {\n break;\n }\n source += eat1();\n }\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let flags = "";\n while (!EOL && next().match(/[dgimsuy]/))\n flags += eat1();\n try {\n return new RegExp(source, flags);\n } catch (e) {\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\`: ${e.message}`);\n }\n }\n function readAttributeToken() {\n let token = "";\n skipSpaces();\n if (next() === `\'` || next() === `"`)\n token = readQuotedString(next()).slice(1, -1);\n else\n token = readIdentifier();\n if (!token)\n syntaxError("parsing property path");\n return token;\n }\n function readOperator() {\n skipSpaces();\n let op = "";\n if (!EOL)\n op += eat1();\n if (!EOL && op !== "=")\n op += eat1();\n if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op))\n syntaxError("parsing operator");\n return op;\n }\n function readAttribute() {\n eat1();\n const jsonPath = [];\n jsonPath.push(readAttributeToken());\n skipSpaces();\n while (next() === ".") {\n eat1();\n jsonPath.push(readAttributeToken());\n skipSpaces();\n }\n if (next() === "]") {\n eat1();\n return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false };\n }\n const operator = readOperator();\n let value = void 0;\n let caseSensitive = true;\n skipSpaces();\n if (next() === "/") {\n if (operator !== "=")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with regular expression`);\n value = readRegularExpression();\n } else if (next() === `\'` || next() === `"`) {\n value = readQuotedString(next()).slice(1, -1);\n skipSpaces();\n if (next() === "i" || next() === "I") {\n caseSensitive = false;\n eat1();\n } else if (next() === "s" || next() === "S") {\n caseSensitive = true;\n eat1();\n }\n } else {\n value = "";\n while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === "."))\n value += eat1();\n if (value === "true") {\n value = true;\n } else if (value === "false") {\n value = false;\n } else {\n if (!allowUnquotedStrings) {\n value = +value;\n if (Number.isNaN(value))\n syntaxError("parsing attribute value");\n }\n }\n }\n skipSpaces();\n if (next() !== "]")\n syntaxError("parsing attribute value");\n eat1();\n if (operator !== "=" && typeof value !== "string")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);\n return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive };\n }\n const result = {\n name: "",\n attributes: []\n };\n result.name = readIdentifier();\n skipSpaces();\n while (next() === "[") {\n result.attributes.push(readAttribute());\n skipSpaces();\n }\n if (!EOL)\n syntaxError(void 0);\n if (!result.name && !result.attributes.length)\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - selector cannot be empty`);\n return result;\n}\n\n// packages/playwright-core/src/utils/isomorphic/stringUtils.ts\nfunction escapeWithQuotes(text, char = "\'") {\n const stringified = JSON.stringify(text);\n const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\\\"/g, \'"\');\n if (char === "\'")\n return char + escapedText.replace(/[\']/g, "\\\\\'") + char;\n if (char === \'"\')\n return char + escapedText.replace(/["]/g, \'\\\\"\') + char;\n if (char === "`")\n return char + escapedText.replace(/[`]/g, "`") + char;\n throw new Error("Invalid escape char");\n}\nfunction toTitleCase(name) {\n return name.charAt(0).toUpperCase() + name.substring(1);\n}\nfunction toSnakeCase(name) {\n return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();\n}\nfunction quoteCSSAttributeValue(text) {\n return `"${text.replace(/["\\\\]/g, (char) => "\\\\" + char)}"`;\n}\nvar normalizedWhitespaceCache;\nfunction cacheNormalizedWhitespaces() {\n normalizedWhitespaceCache = /* @__PURE__ */ new Map();\n}\nfunction normalizeWhiteSpace(text) {\n let result = normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.get(text);\n if (result === void 0) {\n result = text.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " ");\n normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.set(text, result);\n }\n return result;\n}\nfunction normalizeEscapedRegexQuotes(source) {\n return source.replace(/(^|[^\\\\])(\\\\\\\\)*\\\\([\'"`])/g, "$1$2$3");\n}\nfunction escapeRegexForSelector(re) {\n if (re.unicode || re.unicodeSets)\n return String(re);\n return String(re).replace(/(^|[^\\\\])(\\\\\\\\)*(["\'`])/g, "$1$2\\\\$3").replace(/>>/g, "\\\\>\\\\>");\n}\nfunction escapeForTextSelector(text, exact) {\n if (typeof text !== "string")\n return escapeRegexForSelector(text);\n return `${JSON.stringify(text)}${exact ? "s" : "i"}`;\n}\nfunction escapeForAttributeSelector(value, exact) {\n if (typeof value !== "string")\n return escapeRegexForSelector(value);\n return `"${value.replace(/\\\\/g, "\\\\\\\\").replace(/["]/g, \'\\\\"\')}"${exact ? "s" : "i"}`;\n}\nfunction trimString(input, cap, suffix = "") {\n if (input.length <= cap)\n return input;\n const chars = [...input];\n if (chars.length > cap)\n return chars.slice(0, cap - suffix.length).join("") + suffix;\n return chars.join("");\n}\nfunction trimStringWithEllipsis(input, cap) {\n return trimString(input, cap, "\\u2026");\n}\nfunction escapeRegExp(s) {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");\n}\nfunction longestCommonSubstring(s1, s2) {\n const n = s1.length;\n const m = s2.length;\n let maxLen = 0;\n let endingIndex = 0;\n const dp = Array(n + 1).fill(null).map(() => Array(m + 1).fill(0));\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (s1[i - 1] === s2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n if (dp[i][j] > maxLen) {\n maxLen = dp[i][j];\n endingIndex = i;\n }\n }\n }\n }\n return s1.slice(endingIndex - maxLen, endingIndex);\n}\n\n// packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts\nfunction asLocator(lang, selector, isFrameLocator = false) {\n return asLocators(lang, selector, isFrameLocator, 1)[0];\n}\nfunction asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) {\n try {\n return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize);\n } catch (e) {\n return [selector];\n }\n}\nfunction innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) {\n const parts = [...parsed.parts];\n const tokens = [];\n let nextBase = isFrameLocator ? "frame-locator" : "page";\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const base = nextBase;\n nextBase = "locator";\n if (part.name === "internal:describe")\n continue;\n if (part.name === "nth") {\n if (part.body === "0")\n tokens.push([factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0")]);\n else if (part.body === "-1")\n tokens.push([factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1")]);\n else\n tokens.push([factory.generateLocator(base, "nth", part.body)]);\n continue;\n }\n if (part.name === "visible") {\n tokens.push([factory.generateLocator(base, "visible", part.body), factory.generateLocator(base, "default", `visible=${part.body}`)]);\n continue;\n }\n if (part.name === "internal:text") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "text", text, { exact })]);\n continue;\n }\n if (part.name === "internal:has-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has-not-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-not-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner)));\n continue;\n }\n if (part.name === "internal:has-not") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner)));\n continue;\n }\n if (part.name === "internal:and") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner)));\n continue;\n }\n if (part.name === "internal:or") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner)));\n continue;\n }\n if (part.name === "internal:chain") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner)));\n continue;\n }\n if (part.name === "internal:label") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "label", text, { exact })]);\n continue;\n }\n if (part.name === "internal:role") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const options = { attrs: [] };\n for (const attr of attrSelector.attributes) {\n if (attr.name === "name") {\n options.exact = attr.caseSensitive;\n options.name = attr.value;\n } else {\n if (attr.name === "level" && typeof attr.value === "string")\n attr.value = +attr.value;\n options.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value });\n }\n }\n tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]);\n continue;\n }\n if (part.name === "internal:testid") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { value } = attrSelector.attributes[0];\n tokens.push([factory.generateLocator(base, "test-id", value)]);\n continue;\n }\n if (part.name === "internal:attr") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { name, value, caseSensitive } = attrSelector.attributes[0];\n const text = value;\n const exact = !!caseSensitive;\n if (name === "placeholder") {\n tokens.push([factory.generateLocator(base, "placeholder", text, { exact })]);\n continue;\n }\n if (name === "alt") {\n tokens.push([factory.generateLocator(base, "alt", text, { exact })]);\n continue;\n }\n if (name === "title") {\n tokens.push([factory.generateLocator(base, "title", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:control" && part.body === "enter-frame") {\n const lastTokens = tokens[tokens.length - 1];\n const lastPart = parts[index - 1];\n const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")]));\n if (["xpath", "css"].includes(lastPart.name)) {\n transformed.push(\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })),\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] }, true))\n );\n }\n lastTokens.splice(0, lastTokens.length, ...transformed);\n nextBase = "frame-locator";\n continue;\n }\n const nextPart = parts[index + 1];\n const selectorPart = stringifySelector({ parts: [part] });\n const locatorPart = factory.generateLocator(base, "default", selectorPart);\n if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) {\n const { exact, text } = detectExact(nextPart.body);\n if (!exact) {\n const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text, { exact });\n const options = {};\n if (nextPart.name === "internal:has-text")\n options.hasText = text;\n else\n options.hasNotText = text;\n const combinedPart = factory.generateLocator(base, "default", selectorPart, options);\n tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]);\n index++;\n continue;\n }\n }\n let locatorPartWithEngine;\n if (["xpath", "css"].includes(part.name)) {\n const selectorPart2 = stringifySelector(\n { parts: [part] },\n /* forceEngineName */\n true\n );\n locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart2);\n }\n tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean));\n }\n return combineTokens(factory, tokens, maxOutputSize);\n}\nfunction combineTokens(factory, tokens, maxOutputSize) {\n const currentTokens = tokens.map(() => "");\n const result = [];\n const visit = (index) => {\n if (index === tokens.length) {\n result.push(factory.chainLocators(currentTokens));\n return result.length < maxOutputSize;\n }\n for (const taken of tokens[index]) {\n currentTokens[index] = taken;\n if (!visit(index + 1))\n return false;\n }\n return true;\n };\n visit(0);\n return result;\n}\nfunction detectExact(text) {\n let exact = false;\n const match = text.match(/^\\/(.*)\\/([igm]*)$/);\n if (match)\n return { text: new RegExp(match[1], match[2]) };\n if (text.endsWith(\'"\')) {\n text = JSON.parse(text);\n exact = true;\n } else if (text.endsWith(\'"s\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = true;\n } else if (text.endsWith(\'"i\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = false;\n }\n return { exact, text };\n}\nvar JavaScriptLocatorFactory = class {\n constructor(preferredQuote) {\n this.preferredQuote = preferredQuote;\n }\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `filter({ visible: ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name)) {\n attrs.push(`name: ${this.regexToSourceString(options.name)}`);\n } else if (typeof options.name === "string") {\n attrs.push(`name: ${this.quote(options.name)}`);\n if (options.exact)\n attrs.push(`exact: true`);\n }\n for (const { name, value } of options.attrs)\n attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : "";\n return `getByRole(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter({ hasText: ${this.toHasText(body)} })`;\n case "has-not-text":\n return `filter({ hasNotText: ${this.toHasText(body)} })`;\n case "has":\n return `filter({ has: ${body} })`;\n case "hasNot":\n return `filter({ hasNot: ${body} })`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToSourceString(re) {\n return normalizeEscapedRegexQuotes(String(re));\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToSourceString(body)})`;\n return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToSourceString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToSourceString(value);\n return this.quote(value);\n }\n quote(text) {\n var _a;\n return escapeWithQuotes(text, (_a = this.preferredQuote) != null ? _a : "\'");\n }\n};\nvar PythonLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frame_locator(${this.quote(body)})`;\n case "frame":\n return `content_frame`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first`;\n case "last":\n return `last`;\n case "visible":\n return `filter(visible=${body === "true" ? "True" : "False"})`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name)) {\n attrs.push(`name=${this.regexToString(options.name)}`);\n } else if (typeof options.name === "string") {\n attrs.push(`name=${this.quote(options.name)}`);\n if (options.exact)\n attrs.push(`exact=True`);\n }\n for (const { name, value } of options.attrs) {\n let valueString = typeof value === "string" ? this.quote(value) : value;\n if (typeof value === "boolean")\n valueString = value ? "True" : "False";\n attrs.push(`${toSnakeCase(name)}=${valueString}`);\n }\n const attrString = attrs.length ? `, ${attrs.join(", ")}` : "";\n return `get_by_role(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter(has_text=${this.toHasText(body)})`;\n case "has-not-text":\n return `filter(has_not_text=${this.toHasText(body)})`;\n case "has":\n return `filter(has=${body})`;\n case "hasNot":\n return `filter(has_not=${body})`;\n case "and":\n return `and_(${body})`;\n case "or":\n return `or_(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `get_by_test_id(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("get_by_text", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("get_by_alt_text", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("get_by_placeholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("get_by_label", body, !!options.exact);\n case "title":\n return this.toCallWithExact("get_by_title", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", re.IGNORECASE" : "";\n return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\\\\//, "/").replace(/"/g, \'\\\\"\')}"${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, exact=True)`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return `${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JavaLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n let clazz;\n switch (base) {\n case "page":\n clazz = "Page";\n break;\n case "frame-locator":\n clazz = "FrameLocator";\n break;\n case "locator":\n clazz = "Locator";\n break;\n }\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name)) {\n attrs.push(`.setName(${this.regexToString(options.name)})`);\n } else if (typeof options.name === "string") {\n attrs.push(`.setName(${this.quote(options.name)})`);\n if (options.exact)\n attrs.push(`.setExact(true)`);\n }\n for (const { name, value } of options.attrs)\n attrs.push(`.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`);\n const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : "";\n return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`;\n case "has-text":\n return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`;\n case "has-not-text":\n return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`;\n case "has":\n return `filter(new ${clazz}.FilterOptions().setHas(${body}))`;\n case "hasNot":\n return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact(clazz, "getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", Pattern.CASE_INSENSITIVE" : "";\n return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(clazz, method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar CSharpLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`;\n return `Locator(${this.quote(body)})`;\n case "frame-locator":\n return `FrameLocator(${this.quote(body)})`;\n case "frame":\n return `ContentFrame`;\n case "nth":\n return `Nth(${body})`;\n case "first":\n return `First`;\n case "last":\n return `Last`;\n case "visible":\n return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name)) {\n attrs.push(`NameRegex = ${this.regexToString(options.name)}`);\n } else if (typeof options.name === "string") {\n attrs.push(`Name = ${this.quote(options.name)}`);\n if (options.exact)\n attrs.push(`Exact = true`);\n }\n for (const { name, value } of options.attrs)\n attrs.push(`${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : "";\n return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`;\n case "has-text":\n return `Filter(new() { ${this.toHasText(body)} })`;\n case "has-not-text":\n return `Filter(new() { ${this.toHasNotText(body)} })`;\n case "has":\n return `Filter(new() { Has = ${body} })`;\n case "hasNot":\n return `Filter(new() { HasNot = ${body} })`;\n case "and":\n return `And(${body})`;\n case "or":\n return `Or(${body})`;\n case "chain":\n return `Locator(${body})`;\n case "test-id":\n return `GetByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("GetByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("GetByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("GetByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("GetByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("GetByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = body.flags.includes("i") ? ", RegexOptions.IgnoreCase" : "";\n return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new() { Exact = true })`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return `HasTextRegex = ${this.regexToString(body)}`;\n return `HasText = ${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n toHasNotText(body) {\n if (isRegExp(body))\n return `HasNotTextRegex = ${this.regexToString(body)}`;\n return `HasNotText = ${this.quote(body)}`;\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JsonlLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n return JSON.stringify({\n kind,\n body,\n options\n });\n }\n chainLocators(locators) {\n const objects = locators.map((l) => JSON.parse(l));\n for (let i = 0; i < objects.length - 1; ++i)\n objects[i].next = objects[i + 1];\n return JSON.stringify(objects[0]);\n }\n};\nvar generators = {\n javascript: JavaScriptLocatorFactory,\n python: PythonLocatorFactory,\n java: JavaLocatorFactory,\n csharp: CSharpLocatorFactory,\n jsonl: JsonlLocatorFactory\n};\nfunction isRegExp(obj) {\n return obj instanceof RegExp;\n}\n\n// packages/injected/src/domUtils.ts\nvar globalOptions = {};\nfunction setGlobalOptions(options) {\n globalOptions = options;\n}\nfunction getGlobalOptions() {\n return globalOptions;\n}\nfunction isInsideScope(scope, element) {\n while (element) {\n if (scope.contains(element))\n return true;\n element = enclosingShadowHost(element);\n }\n return false;\n}\nfunction parentElementOrShadowHost(element) {\n if (element.parentElement)\n return element.parentElement;\n if (!element.parentNode)\n return;\n if (element.parentNode.nodeType === 11 && element.parentNode.host)\n return element.parentNode.host;\n}\nfunction enclosingShadowRootOrDocument(element) {\n let node = element;\n while (node.parentNode)\n node = node.parentNode;\n if (node.nodeType === 11 || node.nodeType === 9)\n return node;\n}\nfunction enclosingShadowHost(element) {\n while (element.parentElement)\n element = element.parentElement;\n return parentElementOrShadowHost(element);\n}\nfunction closestCrossShadow(element, css, scope) {\n while (element) {\n const closest = element.closest(css);\n if (scope && closest !== scope && (closest == null ? void 0 : closest.contains(scope)))\n return;\n if (closest)\n return closest;\n element = enclosingShadowHost(element);\n }\n}\nfunction getElementComputedStyle(element, pseudo) {\n return element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : void 0;\n}\nfunction isElementStyleVisibilityVisible(element, style) {\n style = style != null ? style : getElementComputedStyle(element);\n if (!style)\n return true;\n if (Element.prototype.checkVisibility && globalOptions.browserNameForWorkarounds !== "webkit") {\n if (!element.checkVisibility())\n return false;\n } else {\n const detailsOrSummary = element.closest("details,summary");\n if (detailsOrSummary !== element && (detailsOrSummary == null ? void 0 : detailsOrSummary.nodeName) === "DETAILS" && !detailsOrSummary.open)\n return false;\n }\n if (style.visibility !== "visible")\n return false;\n return true;\n}\nfunction box(element) {\n const style = getElementComputedStyle(element);\n if (!style)\n return { visible: true };\n if (style.display === "contents") {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && isElementVisible(child))\n return { visible: true, style };\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return { visible: true, style };\n }\n return { visible: false, style };\n }\n if (!isElementStyleVisibilityVisible(element, style))\n return { style, visible: false };\n const rect = element.getBoundingClientRect();\n return { rect, style, visible: rect.width > 0 && rect.height > 0 };\n}\nfunction isElementVisible(element) {\n return box(element).visible;\n}\nfunction isVisibleTextNode(node) {\n const range = node.ownerDocument.createRange();\n range.selectNode(node);\n const rect = range.getBoundingClientRect();\n return rect.width > 0 && rect.height > 0;\n}\nfunction elementSafeTagName(element) {\n if (element instanceof HTMLFormElement)\n return "FORM";\n return element.tagName.toUpperCase();\n}\n\n// packages/injected/src/roleUtils.ts\nfunction hasExplicitAccessibleName(e) {\n return e.hasAttribute("aria-label") || e.hasAttribute("aria-labelledby");\n}\nvar kAncestorPreventingLandmark = "article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]";\nvar kGlobalAriaAttributes = [\n ["aria-atomic", void 0],\n ["aria-busy", void 0],\n ["aria-controls", void 0],\n ["aria-current", void 0],\n ["aria-describedby", void 0],\n ["aria-details", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-disabled\', undefined],\n ["aria-dropeffect", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-errormessage\', undefined],\n ["aria-flowto", void 0],\n ["aria-grabbed", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-haspopup\', undefined],\n ["aria-hidden", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-invalid\', undefined],\n ["aria-keyshortcuts", void 0],\n ["aria-label", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-labelledby", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-live", void 0],\n ["aria-owns", void 0],\n ["aria-relevant", void 0],\n ["aria-roledescription", ["generic"]]\n];\nfunction hasGlobalAriaAttribute(element, forRole) {\n return kGlobalAriaAttributes.some(([attr, prohibited]) => {\n return !(prohibited == null ? void 0 : prohibited.includes(forRole || "")) && element.hasAttribute(attr);\n });\n}\nfunction hasTabIndex(element) {\n return !Number.isNaN(Number(String(element.getAttribute("tabindex"))));\n}\nfunction isFocusable(element) {\n return !isNativelyDisabled(element) && (isNativelyFocusable(element) || hasTabIndex(element));\n}\nfunction isNativelyFocusable(element) {\n const tagName = elementSafeTagName(element);\n if (["BUTTON", "DETAILS", "SELECT", "TEXTAREA"].includes(tagName))\n return true;\n if (tagName === "A" || tagName === "AREA")\n return element.hasAttribute("href");\n if (tagName === "INPUT")\n return !element.hidden;\n return false;\n}\nvar kImplicitRoleByTagName = {\n "A": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "AREA": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "ARTICLE": () => "article",\n "ASIDE": () => "complementary",\n "BLOCKQUOTE": () => "blockquote",\n "BUTTON": () => "button",\n "CAPTION": () => "caption",\n "CODE": () => "code",\n "DATALIST": () => "listbox",\n "DD": () => "definition",\n "DEL": () => "deletion",\n "DETAILS": () => "group",\n "DFN": () => "term",\n "DIALOG": () => "dialog",\n "DT": () => "term",\n "EM": () => "emphasis",\n "FIELDSET": () => "group",\n "FIGURE": () => "figure",\n "FOOTER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "contentinfo",\n "FORM": (e) => hasExplicitAccessibleName(e) ? "form" : null,\n "H1": () => "heading",\n "H2": () => "heading",\n "H3": () => "heading",\n "H4": () => "heading",\n "H5": () => "heading",\n "H6": () => "heading",\n "HEADER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "banner",\n "HR": () => "separator",\n "HTML": () => "document",\n "IMG": (e) => e.getAttribute("alt") === "" && !e.getAttribute("title") && !hasGlobalAriaAttribute(e) && !hasTabIndex(e) ? "presentation" : "img",\n "INPUT": (e) => {\n const type = e.type.toLowerCase();\n if (type === "search")\n return e.hasAttribute("list") ? "combobox" : "searchbox";\n if (["email", "tel", "text", "url", ""].includes(type)) {\n const list = getIdRefs(e, e.getAttribute("list"))[0];\n return list && elementSafeTagName(list) === "DATALIST" ? "combobox" : "textbox";\n }\n if (type === "hidden")\n return null;\n if (type === "file" && !getGlobalOptions().inputFileRoleTextbox)\n return "button";\n return inputTypeToRole[type] || "textbox";\n },\n "INS": () => "insertion",\n "LI": () => "listitem",\n "MAIN": () => "main",\n "MARK": () => "mark",\n "MATH": () => "math",\n "MENU": () => "list",\n "METER": () => "meter",\n "NAV": () => "navigation",\n "OL": () => "list",\n "OPTGROUP": () => "group",\n "OPTION": () => "option",\n "OUTPUT": () => "status",\n "P": () => "paragraph",\n "PROGRESS": () => "progressbar",\n "SECTION": (e) => hasExplicitAccessibleName(e) ? "region" : null,\n "SELECT": (e) => e.hasAttribute("multiple") || e.size > 1 ? "listbox" : "combobox",\n "STRONG": () => "strong",\n "SUB": () => "subscript",\n "SUP": () => "superscript",\n // For we default to Chrome behavior:\n // - Chrome reports \'img\'.\n // - Firefox reports \'diagram\' that is not in official ARIA spec yet.\n // - Safari reports \'no role\', but still computes accessible name.\n "SVG": () => "img",\n "TABLE": () => "table",\n "TBODY": () => "rowgroup",\n "TD": (e) => {\n const table = closestCrossShadow(e, "table");\n const role = table ? getExplicitAriaRole(table) : "";\n return role === "grid" || role === "treegrid" ? "gridcell" : "cell";\n },\n "TEXTAREA": () => "textbox",\n "TFOOT": () => "rowgroup",\n "TH": (e) => {\n if (e.getAttribute("scope") === "col")\n return "columnheader";\n if (e.getAttribute("scope") === "row")\n return "rowheader";\n const table = closestCrossShadow(e, "table");\n const role = table ? getExplicitAriaRole(table) : "";\n return role === "grid" || role === "treegrid" ? "gridcell" : "cell";\n },\n "THEAD": () => "rowgroup",\n "TIME": () => "time",\n "TR": () => "row",\n "UL": () => "list"\n};\nvar kPresentationInheritanceParents = {\n "DD": ["DL", "DIV"],\n "DIV": ["DL"],\n "DT": ["DL", "DIV"],\n "LI": ["OL", "UL"],\n "TBODY": ["TABLE"],\n "TD": ["TR"],\n "TFOOT": ["TABLE"],\n "TH": ["TR"],\n "THEAD": ["TABLE"],\n "TR": ["THEAD", "TBODY", "TFOOT", "TABLE"]\n};\nfunction getImplicitAriaRole(element) {\n var _a;\n const implicitRole = ((_a = kImplicitRoleByTagName[elementSafeTagName(element)]) == null ? void 0 : _a.call(kImplicitRoleByTagName, element)) || "";\n if (!implicitRole)\n return null;\n let ancestor = element;\n while (ancestor) {\n const parent = parentElementOrShadowHost(ancestor);\n const parents = kPresentationInheritanceParents[elementSafeTagName(ancestor)];\n if (!parents || !parent || !parents.includes(elementSafeTagName(parent)))\n break;\n const parentExplicitRole = getExplicitAriaRole(parent);\n if ((parentExplicitRole === "none" || parentExplicitRole === "presentation") && !hasPresentationConflictResolution(parent, parentExplicitRole))\n return parentExplicitRole;\n ancestor = parent;\n }\n return implicitRole;\n}\nvar validRoles = [\n "alert",\n "alertdialog",\n "application",\n "article",\n "banner",\n "blockquote",\n "button",\n "caption",\n "cell",\n "checkbox",\n "code",\n "columnheader",\n "combobox",\n "complementary",\n "contentinfo",\n "definition",\n "deletion",\n "dialog",\n "directory",\n "document",\n "emphasis",\n "feed",\n "figure",\n "form",\n "generic",\n "grid",\n "gridcell",\n "group",\n "heading",\n "img",\n "insertion",\n "link",\n "list",\n "listbox",\n "listitem",\n "log",\n "main",\n "mark",\n "marquee",\n "math",\n "meter",\n "menu",\n "menubar",\n "menuitem",\n "menuitemcheckbox",\n "menuitemradio",\n "navigation",\n "none",\n "note",\n "option",\n "paragraph",\n "presentation",\n "progressbar",\n "radio",\n "radiogroup",\n "region",\n "row",\n "rowgroup",\n "rowheader",\n "scrollbar",\n "search",\n "searchbox",\n "separator",\n "slider",\n "spinbutton",\n "status",\n "strong",\n "subscript",\n "superscript",\n "switch",\n "tab",\n "table",\n "tablist",\n "tabpanel",\n "term",\n "textbox",\n "time",\n "timer",\n "toolbar",\n "tooltip",\n "tree",\n "treegrid",\n "treeitem"\n];\nfunction getExplicitAriaRole(element) {\n const roles = (element.getAttribute("role") || "").split(" ").map((role) => role.trim());\n return roles.find((role) => validRoles.includes(role)) || null;\n}\nfunction hasPresentationConflictResolution(element, role) {\n return hasGlobalAriaAttribute(element, role) || isFocusable(element);\n}\nfunction getAriaRole(element) {\n const explicitRole = getExplicitAriaRole(element);\n if (!explicitRole)\n return getImplicitAriaRole(element);\n if (explicitRole === "none" || explicitRole === "presentation") {\n const implicitRole = getImplicitAriaRole(element);\n if (hasPresentationConflictResolution(element, implicitRole))\n return implicitRole;\n }\n return explicitRole;\n}\nfunction getAriaBoolean(attr) {\n return attr === null ? void 0 : attr.toLowerCase() === "true";\n}\nfunction isElementIgnoredForAria(element) {\n return ["STYLE", "SCRIPT", "NOSCRIPT", "TEMPLATE"].includes(elementSafeTagName(element));\n}\nfunction isElementHiddenForAria(element) {\n if (isElementIgnoredForAria(element))\n return true;\n const style = getElementComputedStyle(element);\n const isSlot = element.nodeName === "SLOT";\n if ((style == null ? void 0 : style.display) === "contents" && !isSlot) {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && !isElementHiddenForAria(child))\n return false;\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return false;\n }\n return true;\n }\n const isOptionInsideSelect = element.nodeName === "OPTION" && !!element.closest("select");\n if (!isOptionInsideSelect && !isSlot && !isElementStyleVisibilityVisible(element, style))\n return true;\n return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element);\n}\nfunction belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element) {\n let hidden = cacheIsHidden == null ? void 0 : cacheIsHidden.get(element);\n if (hidden === void 0) {\n hidden = false;\n if (element.parentElement && element.parentElement.shadowRoot && !element.assignedSlot)\n hidden = true;\n if (!hidden) {\n const style = getElementComputedStyle(element);\n hidden = !style || style.display === "none" || getAriaBoolean(element.getAttribute("aria-hidden")) === true;\n }\n if (!hidden) {\n const parent = parentElementOrShadowHost(element);\n if (parent)\n hidden = belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent);\n }\n cacheIsHidden == null ? void 0 : cacheIsHidden.set(element, hidden);\n }\n return hidden;\n}\nfunction getIdRefs(element, ref) {\n if (!ref)\n return [];\n const root = enclosingShadowRootOrDocument(element);\n if (!root)\n return [];\n try {\n const ids = ref.split(" ").filter((id) => !!id);\n const result = [];\n for (const id of ids) {\n const firstElement = root.querySelector("#" + CSS.escape(id));\n if (firstElement && !result.includes(firstElement))\n result.push(firstElement);\n }\n return result;\n } catch (e) {\n return [];\n }\n}\nfunction trimFlatString(s) {\n return s.trim();\n}\nfunction asFlatString(s) {\n return s.split("\\xA0").map((chunk) => chunk.replace(/\\r\\n/g, "\\n").replace(/[\\u200b\\u00ad]/g, "").replace(/\\s\\s*/g, " ")).join("\\xA0").trim();\n}\nfunction queryInAriaOwned(element, selector) {\n const result = [...element.querySelectorAll(selector)];\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns"))) {\n if (owned.matches(selector))\n result.push(owned);\n result.push(...owned.querySelectorAll(selector));\n }\n return result;\n}\nfunction getCSSContent(element, pseudo) {\n const cache = pseudo === "::before" ? cachePseudoContentBefore : pseudo === "::after" ? cachePseudoContentAfter : cachePseudoContent;\n if (cache == null ? void 0 : cache.has(element))\n return cache == null ? void 0 : cache.get(element);\n const style = getElementComputedStyle(element, pseudo);\n let content;\n if (style && style.display !== "none" && style.visibility !== "hidden") {\n content = parseCSSContentPropertyAsString(element, style.content, !!pseudo);\n }\n if (pseudo && content !== void 0) {\n const display = (style == null ? void 0 : style.display) || "inline";\n if (display !== "inline")\n content = " " + content + " ";\n }\n if (cache)\n cache.set(element, content);\n return content;\n}\nfunction parseCSSContentPropertyAsString(element, content, isPseudo) {\n if (!content || content === "none" || content === "normal") {\n return;\n }\n try {\n let tokens = tokenize(content).filter((token) => !(token instanceof WhitespaceToken));\n const delimIndex = tokens.findIndex((token) => token instanceof DelimToken && token.value === "/");\n if (delimIndex !== -1) {\n tokens = tokens.slice(delimIndex + 1);\n } else if (!isPseudo) {\n return;\n }\n const accumulated = [];\n let index = 0;\n while (index < tokens.length) {\n if (tokens[index] instanceof StringToken) {\n accumulated.push(tokens[index].value);\n index++;\n } else if (index + 2 < tokens.length && tokens[index] instanceof FunctionToken && tokens[index].value === "attr" && tokens[index + 1] instanceof IdentToken && tokens[index + 2] instanceof CloseParenToken) {\n const attrName = tokens[index + 1].value;\n accumulated.push(element.getAttribute(attrName) || "");\n index += 3;\n } else {\n return;\n }\n }\n return accumulated.join("");\n } catch {\n }\n}\nfunction getAriaLabelledByElements(element) {\n const ref = element.getAttribute("aria-labelledby");\n if (ref === null)\n return null;\n const refs = getIdRefs(element, ref);\n return refs.length ? refs : null;\n}\nfunction allowsNameFromContent(role, targetDescendant) {\n const alwaysAllowsNameFromContent = ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem"].includes(role);\n const descendantAllowsNameFromContent = targetDescendant && ["", "caption", "code", "contentinfo", "definition", "deletion", "emphasis", "insertion", "list", "listitem", "mark", "none", "paragraph", "presentation", "region", "row", "rowgroup", "section", "strong", "subscript", "superscript", "table", "term", "time"].includes(role);\n return alwaysAllowsNameFromContent || descendantAllowsNameFromContent;\n}\nfunction getElementAccessibleName(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleNameHidden : cacheAccessibleName;\n let accessibleName = cache == null ? void 0 : cache.get(element);\n if (accessibleName === void 0) {\n accessibleName = "";\n const elementProhibitsNaming = ["caption", "code", "definition", "deletion", "emphasis", "generic", "insertion", "mark", "paragraph", "presentation", "strong", "subscript", "suggestion", "superscript", "term", "time"].includes(getAriaRole(element) || "");\n if (!elementProhibitsNaming) {\n accessibleName = asFlatString(getTextAlternativeInternal(element, {\n includeHidden,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInTargetElement: "self"\n }));\n }\n cache == null ? void 0 : cache.set(element, accessibleName);\n }\n return accessibleName;\n}\nfunction getElementAccessibleDescription(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleDescriptionHidden : cacheAccessibleDescription;\n let accessibleDescription = cache == null ? void 0 : cache.get(element);\n if (accessibleDescription === void 0) {\n accessibleDescription = "";\n if (element.hasAttribute("aria-describedby")) {\n const describedBy = getIdRefs(element, element.getAttribute("aria-describedby"));\n accessibleDescription = asFlatString(describedBy.map((ref) => getTextAlternativeInternal(ref, {\n includeHidden,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: ref, hidden: isElementHiddenForAria(ref) }\n })).join(" "));\n } else if (element.hasAttribute("aria-description")) {\n accessibleDescription = asFlatString(element.getAttribute("aria-description") || "");\n } else {\n accessibleDescription = asFlatString(element.getAttribute("title") || "");\n }\n cache == null ? void 0 : cache.set(element, accessibleDescription);\n }\n return accessibleDescription;\n}\nfunction getAriaInvalid(element) {\n const ariaInvalid = element.getAttribute("aria-invalid");\n if (!ariaInvalid || ariaInvalid.trim() === "" || ariaInvalid.toLocaleLowerCase() === "false")\n return "false";\n if (ariaInvalid === "true" || ariaInvalid === "grammar" || ariaInvalid === "spelling")\n return ariaInvalid;\n return "true";\n}\nfunction getValidityInvalid(element) {\n if ("validity" in element) {\n const validity = element.validity;\n return (validity == null ? void 0 : validity.valid) === false;\n }\n return false;\n}\nfunction getElementAccessibleErrorMessage(element) {\n const cache = cacheAccessibleErrorMessage;\n let accessibleErrorMessage = cacheAccessibleErrorMessage == null ? void 0 : cacheAccessibleErrorMessage.get(element);\n if (accessibleErrorMessage === void 0) {\n accessibleErrorMessage = "";\n const isAriaInvalid = getAriaInvalid(element) !== "false";\n const isValidityInvalid = getValidityInvalid(element);\n if (isAriaInvalid || isValidityInvalid) {\n const errorMessageId = element.getAttribute("aria-errormessage");\n const errorMessages = getIdRefs(element, errorMessageId);\n const parts = errorMessages.map((errorMessage) => asFlatString(\n getTextAlternativeInternal(errorMessage, {\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: errorMessage, hidden: isElementHiddenForAria(errorMessage) }\n })\n ));\n accessibleErrorMessage = parts.join(" ").trim();\n }\n cache == null ? void 0 : cache.set(element, accessibleErrorMessage);\n }\n return accessibleErrorMessage;\n}\nfunction getTextAlternativeInternal(element, options) {\n var _a, _b, _c, _d;\n if (options.visitedElements.has(element))\n return "";\n const childOptions = {\n ...options,\n embeddedInTargetElement: options.embeddedInTargetElement === "self" ? "descendant" : options.embeddedInTargetElement\n };\n if (!options.includeHidden) {\n const isEmbeddedInHiddenReferenceTraversal = !!((_a = options.embeddedInLabelledBy) == null ? void 0 : _a.hidden) || !!((_b = options.embeddedInDescribedBy) == null ? void 0 : _b.hidden) || !!((_c = options.embeddedInNativeTextAlternative) == null ? void 0 : _c.hidden) || !!((_d = options.embeddedInLabel) == null ? void 0 : _d.hidden);\n if (isElementIgnoredForAria(element) || !isEmbeddedInHiddenReferenceTraversal && isElementHiddenForAria(element)) {\n options.visitedElements.add(element);\n return "";\n }\n }\n const labelledBy = getAriaLabelledByElements(element);\n if (!options.embeddedInLabelledBy) {\n const accessibleName = (labelledBy || []).map((ref) => getTextAlternativeInternal(ref, {\n ...options,\n embeddedInLabelledBy: { element: ref, hidden: isElementHiddenForAria(ref) },\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0,\n embeddedInLabel: void 0,\n embeddedInNativeTextAlternative: void 0\n })).join(" ");\n if (accessibleName)\n return accessibleName;\n }\n const role = getAriaRole(element) || "";\n const tagName = elementSafeTagName(element);\n if (!!options.embeddedInLabel || !!options.embeddedInLabelledBy || options.embeddedInTargetElement === "descendant") {\n const isOwnLabel = [...element.labels || []].includes(element);\n const isOwnLabelledBy = (labelledBy || []).includes(element);\n if (!isOwnLabel && !isOwnLabelledBy) {\n if (role === "textbox") {\n options.visitedElements.add(element);\n if (tagName === "INPUT" || tagName === "TEXTAREA")\n return element.value;\n return element.textContent || "";\n }\n if (["combobox", "listbox"].includes(role)) {\n options.visitedElements.add(element);\n let selectedOptions;\n if (tagName === "SELECT") {\n selectedOptions = [...element.selectedOptions];\n if (!selectedOptions.length && element.options.length)\n selectedOptions.push(element.options[0]);\n } else {\n const listbox = role === "combobox" ? queryInAriaOwned(element, "*").find((e) => getAriaRole(e) === "listbox") : element;\n selectedOptions = listbox ? queryInAriaOwned(listbox, \'[aria-selected="true"]\').filter((e) => getAriaRole(e) === "option") : [];\n }\n if (!selectedOptions.length && tagName === "INPUT") {\n return element.value;\n }\n return selectedOptions.map((option) => getTextAlternativeInternal(option, childOptions)).join(" ");\n }\n if (["progressbar", "scrollbar", "slider", "spinbutton", "meter"].includes(role)) {\n options.visitedElements.add(element);\n if (element.hasAttribute("aria-valuetext"))\n return element.getAttribute("aria-valuetext") || "";\n if (element.hasAttribute("aria-valuenow"))\n return element.getAttribute("aria-valuenow") || "";\n return element.getAttribute("value") || "";\n }\n if (["menu"].includes(role)) {\n options.visitedElements.add(element);\n return "";\n }\n }\n }\n const ariaLabel = element.getAttribute("aria-label") || "";\n if (trimFlatString(ariaLabel)) {\n options.visitedElements.add(element);\n return ariaLabel;\n }\n if (!["presentation", "none"].includes(role)) {\n if (tagName === "INPUT" && ["button", "submit", "reset"].includes(element.type)) {\n options.visitedElements.add(element);\n const value = element.value || "";\n if (trimFlatString(value))\n return value;\n if (element.type === "submit")\n return "Submit";\n if (element.type === "reset")\n return "Reset";\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (!getGlobalOptions().inputFileRoleTextbox && tagName === "INPUT" && element.type === "file") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return "Choose File";\n }\n if (tagName === "INPUT" && element.type === "image") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return alt;\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return title;\n return "Submit";\n }\n if (!labelledBy && tagName === "BUTTON") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n }\n if (!labelledBy && tagName === "OUTPUT") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return element.getAttribute("title") || "";\n }\n if (!labelledBy && (tagName === "TEXTAREA" || tagName === "SELECT" || tagName === "INPUT")) {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const usePlaceholder = tagName === "INPUT" && ["text", "password", "search", "tel", "email", "url"].includes(element.type) || tagName === "TEXTAREA";\n const placeholder = element.getAttribute("placeholder") || "";\n const title = element.getAttribute("title") || "";\n if (!usePlaceholder || title)\n return title;\n return placeholder;\n }\n if (!labelledBy && tagName === "FIELDSET") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "LEGEND") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (!labelledBy && tagName === "FIGURE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "FIGCAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "IMG") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return alt;\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "TABLE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "CAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const summary = element.getAttribute("summary") || "";\n if (summary)\n return summary;\n }\n if (tagName === "AREA") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return alt;\n const title = element.getAttribute("title") || "";\n return title;\n }\n if (tagName === "SVG" || element.ownerSVGElement) {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "TITLE" && child.ownerSVGElement) {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInLabelledBy: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n }\n if (element.ownerSVGElement && tagName === "A") {\n const title = element.getAttribute("xlink:title") || "";\n if (trimFlatString(title)) {\n options.visitedElements.add(element);\n return title;\n }\n }\n }\n const shouldNameFromContentForSummary = tagName === "SUMMARY" && !["presentation", "none"].includes(role);\n if (allowsNameFromContent(role, options.embeddedInTargetElement === "descendant") || shouldNameFromContentForSummary || !!options.embeddedInLabelledBy || !!options.embeddedInDescribedBy || !!options.embeddedInLabel || !!options.embeddedInNativeTextAlternative) {\n options.visitedElements.add(element);\n const accessibleName = innerAccumulatedElementText(element, childOptions);\n const maybeTrimmedAccessibleName = options.embeddedInTargetElement === "self" ? trimFlatString(accessibleName) : accessibleName;\n if (maybeTrimmedAccessibleName)\n return accessibleName;\n }\n if (!["presentation", "none"].includes(role) || tagName === "IFRAME") {\n options.visitedElements.add(element);\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return title;\n }\n options.visitedElements.add(element);\n return "";\n}\nfunction innerAccumulatedElementText(element, options) {\n const tokens = [];\n const visit = (node, skipSlotted) => {\n var _a;\n if (skipSlotted && node.assignedSlot)\n return;\n if (node.nodeType === 1) {\n const display = ((_a = getElementComputedStyle(node)) == null ? void 0 : _a.display) || "inline";\n let token = getTextAlternativeInternal(node, options);\n if (display !== "inline" || node.nodeName === "BR")\n token = " " + token + " ";\n tokens.push(token);\n } else if (node.nodeType === 3) {\n tokens.push(node.textContent || "");\n }\n };\n tokens.push(getCSSContent(element, "::before") || "");\n const content = getCSSContent(element);\n if (content !== void 0) {\n tokens.push(content);\n } else {\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(child, false);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling)\n visit(child, true);\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(child, true);\n }\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns")))\n visit(owned, true);\n }\n }\n tokens.push(getCSSContent(element, "::after") || "");\n return tokens.join("");\n}\nvar kAriaSelectedRoles = ["gridcell", "option", "row", "tab", "rowheader", "columnheader", "treeitem"];\nfunction getAriaSelected(element) {\n if (elementSafeTagName(element) === "OPTION")\n return element.selected;\n if (kAriaSelectedRoles.includes(getAriaRole(element) || ""))\n return getAriaBoolean(element.getAttribute("aria-selected")) === true;\n return false;\n}\nvar kAriaCheckedRoles = ["checkbox", "menuitemcheckbox", "option", "radio", "switch", "menuitemradio", "treeitem"];\nfunction getAriaChecked(element) {\n const result = getChecked(element, true);\n return result === "error" ? false : result;\n}\nfunction getCheckedAllowMixed(element) {\n return getChecked(element, true);\n}\nfunction getCheckedWithoutMixed(element) {\n const result = getChecked(element, false);\n return result;\n}\nfunction getChecked(element, allowMixed) {\n const tagName = elementSafeTagName(element);\n if (allowMixed && tagName === "INPUT" && element.indeterminate)\n return "mixed";\n if (tagName === "INPUT" && ["checkbox", "radio"].includes(element.type))\n return element.checked;\n if (kAriaCheckedRoles.includes(getAriaRole(element) || "")) {\n const checked = element.getAttribute("aria-checked");\n if (checked === "true")\n return true;\n if (allowMixed && checked === "mixed")\n return "mixed";\n return false;\n }\n return "error";\n}\nvar kAriaReadonlyRoles = ["checkbox", "combobox", "grid", "gridcell", "listbox", "radiogroup", "slider", "spinbutton", "textbox", "columnheader", "rowheader", "searchbox", "switch", "treegrid"];\nfunction getReadonly(element) {\n const tagName = elementSafeTagName(element);\n if (["INPUT", "TEXTAREA", "SELECT"].includes(tagName))\n return element.hasAttribute("readonly");\n if (kAriaReadonlyRoles.includes(getAriaRole(element) || ""))\n return element.getAttribute("aria-readonly") === "true";\n if (element.isContentEditable)\n return false;\n return "error";\n}\nvar kAriaPressedRoles = ["button"];\nfunction getAriaPressed(element) {\n if (kAriaPressedRoles.includes(getAriaRole(element) || "")) {\n const pressed = element.getAttribute("aria-pressed");\n if (pressed === "true")\n return true;\n if (pressed === "mixed")\n return "mixed";\n }\n return false;\n}\nvar kAriaExpandedRoles = ["application", "button", "checkbox", "combobox", "gridcell", "link", "listbox", "menuitem", "row", "rowheader", "tab", "treeitem", "columnheader", "menuitemcheckbox", "menuitemradio", "rowheader", "switch"];\nfunction getAriaExpanded(element) {\n if (elementSafeTagName(element) === "DETAILS")\n return element.open;\n if (kAriaExpandedRoles.includes(getAriaRole(element) || "")) {\n const expanded = element.getAttribute("aria-expanded");\n if (expanded === null)\n return void 0;\n if (expanded === "true")\n return true;\n return false;\n }\n return void 0;\n}\nvar kAriaLevelRoles = ["heading", "listitem", "row", "treeitem"];\nfunction getAriaLevel(element) {\n const native = { "H1": 1, "H2": 2, "H3": 3, "H4": 4, "H5": 5, "H6": 6 }[elementSafeTagName(element)];\n if (native)\n return native;\n if (kAriaLevelRoles.includes(getAriaRole(element) || "")) {\n const attr = element.getAttribute("aria-level");\n const value = attr === null ? Number.NaN : Number(attr);\n if (Number.isInteger(value) && value >= 1)\n return value;\n }\n return 0;\n}\nvar kAriaDisabledRoles = ["application", "button", "composite", "gridcell", "group", "input", "link", "menuitem", "scrollbar", "separator", "tab", "checkbox", "columnheader", "combobox", "grid", "listbox", "menu", "menubar", "menuitemcheckbox", "menuitemradio", "option", "radio", "radiogroup", "row", "rowheader", "searchbox", "select", "slider", "spinbutton", "switch", "tablist", "textbox", "toolbar", "tree", "treegrid", "treeitem"];\nfunction getAriaDisabled(element) {\n return isNativelyDisabled(element) || hasExplicitAriaDisabled(element);\n}\nfunction isNativelyDisabled(element) {\n const isNativeFormControl = ["BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "OPTGROUP"].includes(element.tagName);\n return isNativeFormControl && (element.hasAttribute("disabled") || belongsToDisabledFieldSet(element));\n}\nfunction belongsToDisabledFieldSet(element) {\n const fieldSetElement = element == null ? void 0 : element.closest("FIELDSET[DISABLED]");\n if (!fieldSetElement)\n return false;\n const legendElement = fieldSetElement.querySelector(":scope > LEGEND");\n return !legendElement || !legendElement.contains(element);\n}\nfunction hasExplicitAriaDisabled(element, isAncestor = false) {\n if (!element)\n return false;\n if (isAncestor || kAriaDisabledRoles.includes(getAriaRole(element) || "")) {\n const attribute = (element.getAttribute("aria-disabled") || "").toLowerCase();\n if (attribute === "true")\n return true;\n if (attribute === "false")\n return false;\n return hasExplicitAriaDisabled(parentElementOrShadowHost(element), true);\n }\n return false;\n}\nfunction getAccessibleNameFromAssociatedLabels(labels, options) {\n return [...labels].map((label) => getTextAlternativeInternal(label, {\n ...options,\n embeddedInLabel: { element: label, hidden: isElementHiddenForAria(label) },\n embeddedInNativeTextAlternative: void 0,\n embeddedInLabelledBy: void 0,\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0\n })).filter((accessibleName) => !!accessibleName).join(" ");\n}\nfunction receivesPointerEvents(element) {\n const cache = cachePointerEvents;\n let e = element;\n let result;\n const parents = [];\n for (; e; e = parentElementOrShadowHost(e)) {\n const cached = cache.get(e);\n if (cached !== void 0) {\n result = cached;\n break;\n }\n parents.push(e);\n const style = getElementComputedStyle(e);\n if (!style) {\n result = true;\n break;\n }\n const value = style.pointerEvents;\n if (value) {\n result = value !== "none";\n break;\n }\n }\n if (result === void 0)\n result = true;\n for (const parent of parents)\n cache.set(parent, result);\n return result;\n}\nvar cacheAccessibleName;\nvar cacheAccessibleNameHidden;\nvar cacheAccessibleDescription;\nvar cacheAccessibleDescriptionHidden;\nvar cacheAccessibleErrorMessage;\nvar cacheIsHidden;\nvar cachePseudoContent;\nvar cachePseudoContentBefore;\nvar cachePseudoContentAfter;\nvar cachePointerEvents;\nvar cachesCounter = 0;\nfunction beginAriaCaches() {\n ++cachesCounter;\n cacheAccessibleName != null ? cacheAccessibleName : cacheAccessibleName = /* @__PURE__ */ new Map();\n cacheAccessibleNameHidden != null ? cacheAccessibleNameHidden : cacheAccessibleNameHidden = /* @__PURE__ */ new Map();\n cacheAccessibleDescription != null ? cacheAccessibleDescription : cacheAccessibleDescription = /* @__PURE__ */ new Map();\n cacheAccessibleDescriptionHidden != null ? cacheAccessibleDescriptionHidden : cacheAccessibleDescriptionHidden = /* @__PURE__ */ new Map();\n cacheAccessibleErrorMessage != null ? cacheAccessibleErrorMessage : cacheAccessibleErrorMessage = /* @__PURE__ */ new Map();\n cacheIsHidden != null ? cacheIsHidden : cacheIsHidden = /* @__PURE__ */ new Map();\n cachePseudoContent != null ? cachePseudoContent : cachePseudoContent = /* @__PURE__ */ new Map();\n cachePseudoContentBefore != null ? cachePseudoContentBefore : cachePseudoContentBefore = /* @__PURE__ */ new Map();\n cachePseudoContentAfter != null ? cachePseudoContentAfter : cachePseudoContentAfter = /* @__PURE__ */ new Map();\n cachePointerEvents != null ? cachePointerEvents : cachePointerEvents = /* @__PURE__ */ new Map();\n}\nfunction endAriaCaches() {\n if (!--cachesCounter) {\n cacheAccessibleName = void 0;\n cacheAccessibleNameHidden = void 0;\n cacheAccessibleDescription = void 0;\n cacheAccessibleDescriptionHidden = void 0;\n cacheAccessibleErrorMessage = void 0;\n cacheIsHidden = void 0;\n cachePseudoContent = void 0;\n cachePseudoContentBefore = void 0;\n cachePseudoContentAfter = void 0;\n cachePointerEvents = void 0;\n }\n}\nvar inputTypeToRole = {\n "button": "button",\n "checkbox": "checkbox",\n "image": "button",\n "number": "spinbutton",\n "radio": "radio",\n "range": "slider",\n "reset": "button",\n "submit": "button"\n};\n\n// packages/injected/src/yaml.ts\nfunction yamlEscapeKeyIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return `\'` + str.replace(/\'/g, `\'\'`) + `\'`;\n}\nfunction yamlEscapeValueIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return \'"\' + str.replace(/[\\\\"\\x00-\\x1f\\x7f-\\x9f]/g, (c) => {\n switch (c) {\n case "\\\\":\n return "\\\\\\\\";\n case \'"\':\n return \'\\\\"\';\n case "\\b":\n return "\\\\b";\n case "\\f":\n return "\\\\f";\n case "\\n":\n return "\\\\n";\n case "\\r":\n return "\\\\r";\n case " ":\n return "\\\\t";\n default:\n const code = c.charCodeAt(0);\n return "\\\\x" + code.toString(16).padStart(2, "0");\n }\n }) + \'"\';\n}\nfunction yamlStringNeedsQuotes(str) {\n if (str.length === 0)\n return true;\n if (/^\\s|\\s$/.test(str))\n return true;\n if (/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f]/.test(str))\n return true;\n if (/^-/.test(str))\n return true;\n if (/[\\n:](\\s|$)/.test(str))\n return true;\n if (/\\s#/.test(str))\n return true;\n if (/[\\n\\r]/.test(str))\n return true;\n if (/^[&*\\],?!>|@"\'#%]/.test(str))\n return true;\n if (/[{}`]/.test(str))\n return true;\n if (/^\\[/.test(str))\n return true;\n if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null"].includes(str.toLowerCase()))\n return true;\n return false;\n}\n\n// packages/injected/src/ariaSnapshot.ts\nvar lastRef = 0;\nfunction generateAriaTree(rootElement, options) {\n const visited = /* @__PURE__ */ new Set();\n const snapshot = {\n root: { role: "fragment", name: "", children: [], element: rootElement, props: {}, box: box(rootElement), receivesPointerEvents: true },\n elements: /* @__PURE__ */ new Map()\n };\n const visit = (ariaNode, node) => {\n if (visited.has(node))\n return;\n visited.add(node);\n if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {\n const text = node.nodeValue;\n if (ariaNode.role !== "textbox" && text)\n ariaNode.children.push(node.nodeValue || "");\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE)\n return;\n const element = node;\n let isVisible = !isElementHiddenForAria(element);\n if (options == null ? void 0 : options.forAI)\n isVisible = isVisible || isElementVisible(element);\n if (!isVisible)\n return;\n const ariaChildren = [];\n if (element.hasAttribute("aria-owns")) {\n const ids = element.getAttribute("aria-owns").split(/\\s+/);\n for (const id of ids) {\n const ownedElement = rootElement.ownerDocument.getElementById(id);\n if (ownedElement)\n ariaChildren.push(ownedElement);\n }\n }\n const childAriaNode = toAriaNode(element, options);\n if (childAriaNode) {\n if (childAriaNode.ref)\n snapshot.elements.set(childAriaNode.ref, element);\n ariaNode.children.push(childAriaNode);\n }\n processElement(childAriaNode || ariaNode, element, ariaChildren);\n };\n function processElement(ariaNode, element, ariaChildren = []) {\n var _a;\n const display = ((_a = getElementComputedStyle(element)) == null ? void 0 : _a.display) || "inline";\n const treatAsBlock = display !== "inline" || element.nodeName === "BR" ? " " : "";\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n ariaNode.children.push(getCSSContent(element, "::before") || "");\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(ariaNode, child);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (!child.assignedSlot)\n visit(ariaNode, child);\n }\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(ariaNode, child);\n }\n }\n for (const child of ariaChildren)\n visit(ariaNode, child);\n ariaNode.children.push(getCSSContent(element, "::after") || "");\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n if (ariaNode.children.length === 1 && ariaNode.name === ariaNode.children[0])\n ariaNode.children = [];\n if (ariaNode.role === "link" && element.hasAttribute("href")) {\n const href = element.getAttribute("href");\n ariaNode.props["url"] = href;\n }\n }\n beginAriaCaches();\n try {\n visit(snapshot.root, rootElement);\n } finally {\n endAriaCaches();\n }\n normalizeStringChildren(snapshot.root);\n normalizeGenericRoles(snapshot.root);\n return snapshot;\n}\nfunction ariaRef(element, role, name, options) {\n var _a;\n if (!(options == null ? void 0 : options.forAI))\n return void 0;\n let ariaRef2;\n ariaRef2 = element._ariaRef;\n if (!ariaRef2 || ariaRef2.role !== role || ariaRef2.name !== name) {\n ariaRef2 = { role, name, ref: ((_a = options == null ? void 0 : options.refPrefix) != null ? _a : "") + "e" + ++lastRef };\n element._ariaRef = ariaRef2;\n }\n return ariaRef2.ref;\n}\nfunction toAriaNode(element, options) {\n var _a;\n if (element.nodeName === "IFRAME") {\n return {\n role: "iframe",\n name: "",\n ref: ariaRef(element, "iframe", "", options),\n children: [],\n props: {},\n element,\n box: box(element),\n receivesPointerEvents: true\n };\n }\n const defaultRole = (options == null ? void 0 : options.forAI) ? "generic" : null;\n const role = (_a = getAriaRole(element)) != null ? _a : defaultRole;\n if (!role || role === "presentation" || role === "none")\n return null;\n const name = normalizeWhiteSpace(getElementAccessibleName(element, false) || "");\n const receivesPointerEvents3 = receivesPointerEvents(element);\n const result = {\n role,\n name,\n ref: ariaRef(element, role, name, options),\n children: [],\n props: {},\n element,\n box: box(element),\n receivesPointerEvents: receivesPointerEvents3\n };\n if (kAriaCheckedRoles.includes(role))\n result.checked = getAriaChecked(element);\n if (kAriaDisabledRoles.includes(role))\n result.disabled = getAriaDisabled(element);\n if (kAriaExpandedRoles.includes(role))\n result.expanded = getAriaExpanded(element);\n if (kAriaLevelRoles.includes(role))\n result.level = getAriaLevel(element);\n if (kAriaPressedRoles.includes(role))\n result.pressed = getAriaPressed(element);\n if (kAriaSelectedRoles.includes(role))\n result.selected = getAriaSelected(element);\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n if (element.type !== "checkbox" && element.type !== "radio" && (element.type !== "file" || getGlobalOptions().inputFileRoleTextbox))\n result.children = [element.value];\n }\n return result;\n}\nfunction normalizeGenericRoles(node) {\n const normalizeChildren = (node2) => {\n const result = [];\n for (const child of node2.children || []) {\n if (typeof child === "string") {\n result.push(child);\n continue;\n }\n const normalized = normalizeChildren(child);\n result.push(...normalized);\n }\n const removeSelf = node2.role === "generic" && result.length <= 1 && result.every((c) => typeof c !== "string" && receivesPointerEvents2(c));\n if (removeSelf)\n return result;\n node2.children = result;\n return [node2];\n };\n normalizeChildren(node);\n}\nfunction normalizeStringChildren(rootA11yNode) {\n const flushChildren = (buffer, normalizedChildren) => {\n if (!buffer.length)\n return;\n const text = normalizeWhiteSpace(buffer.join(""));\n if (text)\n normalizedChildren.push(text);\n buffer.length = 0;\n };\n const visit = (ariaNode) => {\n const normalizedChildren = [];\n const buffer = [];\n for (const child of ariaNode.children || []) {\n if (typeof child === "string") {\n buffer.push(child);\n } else {\n flushChildren(buffer, normalizedChildren);\n visit(child);\n normalizedChildren.push(child);\n }\n }\n flushChildren(buffer, normalizedChildren);\n ariaNode.children = normalizedChildren.length ? normalizedChildren : [];\n if (ariaNode.children.length === 1 && ariaNode.children[0] === ariaNode.name)\n ariaNode.children = [];\n };\n visit(rootA11yNode);\n}\nfunction matchesText(text, template) {\n if (!template)\n return true;\n if (!text)\n return false;\n if (typeof template === "string")\n return text === template;\n return !!text.match(new RegExp(template.pattern));\n}\nfunction matchesTextNode(text, template) {\n return matchesText(text, template.text);\n}\nfunction matchesName(text, template) {\n return matchesText(text, template.name);\n}\nfunction matchesAriaTree(rootElement, template) {\n const snapshot = generateAriaTree(rootElement);\n const matches = matchesNodeDeep(snapshot.root, template, false, false);\n return {\n matches,\n received: {\n raw: renderAriaTree(snapshot, { mode: "raw" }),\n regex: renderAriaTree(snapshot, { mode: "regex" })\n }\n };\n}\nfunction getAllByAria(rootElement, template) {\n const root = generateAriaTree(rootElement).root;\n const matches = matchesNodeDeep(root, template, true, false);\n return matches.map((n) => n.element);\n}\nfunction matchesNode(node, template, isDeepEqual) {\n var _a;\n if (typeof node === "string" && template.kind === "text")\n return matchesTextNode(node, template);\n if (node === null || typeof node !== "object" || template.kind !== "role")\n return false;\n if (template.role !== "fragment" && template.role !== node.role)\n return false;\n if (template.checked !== void 0 && template.checked !== node.checked)\n return false;\n if (template.disabled !== void 0 && template.disabled !== node.disabled)\n return false;\n if (template.expanded !== void 0 && template.expanded !== node.expanded)\n return false;\n if (template.level !== void 0 && template.level !== node.level)\n return false;\n if (template.pressed !== void 0 && template.pressed !== node.pressed)\n return false;\n if (template.selected !== void 0 && template.selected !== node.selected)\n return false;\n if (!matchesName(node.name, template))\n return false;\n if (!matchesText(node.props.url, (_a = template.props) == null ? void 0 : _a.url))\n return false;\n if (template.containerMode === "contain")\n return containsList(node.children || [], template.children || []);\n if (template.containerMode === "equal")\n return listEqual(node.children || [], template.children || [], false);\n if (template.containerMode === "deep-equal" || isDeepEqual)\n return listEqual(node.children || [], template.children || [], true);\n return containsList(node.children || [], template.children || []);\n}\nfunction listEqual(children, template, isDeepEqual) {\n if (template.length !== children.length)\n return false;\n for (let i = 0; i < template.length; ++i) {\n if (!matchesNode(children[i], template[i], isDeepEqual))\n return false;\n }\n return true;\n}\nfunction containsList(children, template) {\n if (template.length > children.length)\n return false;\n const cc = children.slice();\n const tt = template.slice();\n for (const t of tt) {\n let c = cc.shift();\n while (c) {\n if (matchesNode(c, t, false))\n break;\n c = cc.shift();\n }\n if (!c)\n return false;\n }\n return true;\n}\nfunction matchesNodeDeep(root, template, collectAll, isDeepEqual) {\n const results = [];\n const visit = (node, parent) => {\n if (matchesNode(node, template, isDeepEqual)) {\n const result = typeof node === "string" ? parent : node;\n if (result)\n results.push(result);\n return !collectAll;\n }\n if (typeof node === "string")\n return false;\n for (const child of node.children || []) {\n if (visit(child, node))\n return true;\n }\n return false;\n };\n visit(root, null);\n return results;\n}\nfunction renderAriaTree(ariaSnapshot, options) {\n const lines = [];\n const includeText = (options == null ? void 0 : options.mode) === "regex" ? textContributesInfo : () => true;\n const renderString = (options == null ? void 0 : options.mode) === "regex" ? convertToBestGuessRegex : (str) => str;\n const visit = (ariaNode2, parentAriaNode, indent) => {\n if (typeof ariaNode2 === "string") {\n if (parentAriaNode && !includeText(parentAriaNode, ariaNode2))\n return;\n const text = yamlEscapeValueIfNeeded(renderString(ariaNode2));\n if (text)\n lines.push(indent + "- text: " + text);\n return;\n }\n let key = ariaNode2.role;\n if (ariaNode2.name && ariaNode2.name.length <= 900) {\n const name = renderString(ariaNode2.name);\n if (name) {\n const stringifiedName = name.startsWith("/") && name.endsWith("/") ? name : JSON.stringify(name);\n key += " " + stringifiedName;\n }\n }\n if (ariaNode2.checked === "mixed")\n key += ` [checked=mixed]`;\n if (ariaNode2.checked === true)\n key += ` [checked]`;\n if (ariaNode2.disabled)\n key += ` [disabled]`;\n if (ariaNode2.expanded)\n key += ` [expanded]`;\n if (ariaNode2.level)\n key += ` [level=${ariaNode2.level}]`;\n if (ariaNode2.pressed === "mixed")\n key += ` [pressed=mixed]`;\n if (ariaNode2.pressed === true)\n key += ` [pressed]`;\n if (ariaNode2.selected === true)\n key += ` [selected]`;\n if ((options == null ? void 0 : options.forAI) && receivesPointerEvents2(ariaNode2)) {\n const ref = ariaNode2.ref;\n const cursor = hasPointerCursor(ariaNode2) ? " [cursor=pointer]" : "";\n if (ref)\n key += ` [ref=${ref}]${cursor}`;\n }\n const escapedKey = indent + "- " + yamlEscapeKeyIfNeeded(key);\n const hasProps = !!Object.keys(ariaNode2.props).length;\n if (!ariaNode2.children.length && !hasProps) {\n lines.push(escapedKey);\n } else if (ariaNode2.children.length === 1 && typeof ariaNode2.children[0] === "string" && !hasProps) {\n const text = includeText(ariaNode2, ariaNode2.children[0]) ? renderString(ariaNode2.children[0]) : null;\n if (text)\n lines.push(escapedKey + ": " + yamlEscapeValueIfNeeded(text));\n else\n lines.push(escapedKey);\n } else {\n lines.push(escapedKey + ":");\n for (const [name, value] of Object.entries(ariaNode2.props))\n lines.push(indent + " - /" + name + ": " + yamlEscapeValueIfNeeded(value));\n for (const child of ariaNode2.children || [])\n visit(child, ariaNode2, indent + " ");\n }\n };\n const ariaNode = ariaSnapshot.root;\n if (ariaNode.role === "fragment") {\n for (const child of ariaNode.children || [])\n visit(child, ariaNode, "");\n } else {\n visit(ariaNode, null, "");\n }\n return lines.join("\\n");\n}\nfunction convertToBestGuessRegex(text) {\n const dynamicContent = [\n // 2mb\n { regex: /\\b[\\d,.]+[bkmBKM]+\\b/, replacement: "[\\\\d,.]+[bkmBKM]+" },\n // 2ms, 20s\n { regex: /\\b\\d+[hmsp]+\\b/, replacement: "\\\\d+[hmsp]+" },\n { regex: /\\b[\\d,.]+[hmsp]+\\b/, replacement: "[\\\\d,.]+[hmsp]+" },\n // Do not replace single digits with regex by default.\n // 2+ digits: [Issue 22, 22.3, 2.33, 2,333]\n { regex: /\\b\\d+,\\d+\\b/, replacement: "\\\\d+,\\\\d+" },\n { regex: /\\b\\d+\\.\\d{2,}\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\.\\d+\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\b/, replacement: "\\\\d+" }\n ];\n let pattern = "";\n let lastIndex = 0;\n const combinedRegex = new RegExp(dynamicContent.map((r) => "(" + r.regex.source + ")").join("|"), "g");\n text.replace(combinedRegex, (match, ...args) => {\n const offset = args[args.length - 2];\n const groups = args.slice(0, -2);\n pattern += escapeRegExp(text.slice(lastIndex, offset));\n for (let i = 0; i < groups.length; i++) {\n if (groups[i]) {\n const { replacement } = dynamicContent[i];\n pattern += replacement;\n break;\n }\n }\n lastIndex = offset + match.length;\n return match;\n });\n if (!pattern)\n return text;\n pattern += escapeRegExp(text.slice(lastIndex));\n return String(new RegExp(pattern));\n}\nfunction textContributesInfo(node, text) {\n if (!text.length)\n return false;\n if (!node.name)\n return true;\n if (node.name.length > text.length)\n return false;\n const substr = text.length <= 200 && node.name.length <= 200 ? longestCommonSubstring(text, node.name) : "";\n let filtered = text;\n while (substr && filtered.includes(substr))\n filtered = filtered.replace(substr, "");\n return filtered.trim().length / text.length > 0.1;\n}\nfunction receivesPointerEvents2(ariaNode) {\n return ariaNode.box.visible && ariaNode.receivesPointerEvents;\n}\nfunction hasPointerCursor(ariaNode) {\n var _a;\n return ((_a = ariaNode.box.style) == null ? void 0 : _a.cursor) === "pointer";\n}\n\n// packages/injected/src/highlight.css?inline\nvar highlight_default = ":host{font-size:13px;font-family:system-ui,Ubuntu,Droid Sans,sans-serif;color:#333}svg{position:absolute;height:0}x-pw-tooltip{backdrop-filter:blur(5px);background-color:#fff;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:none;font-size:12.8px;font-weight:400;left:0;line-height:1.5;max-width:600px;position:absolute;top:0;padding:0;flex-direction:column;overflow:hidden}x-pw-tooltip-line{display:flex;max-width:600px;padding:6px;user-select:none;cursor:pointer}x-pw-tooltip-line.selectable:hover{background-color:#f2f2f2;overflow:hidden}x-pw-tooltip-footer{display:flex;max-width:600px;padding:6px;user-select:none;color:#777}x-pw-dialog{background-color:#fff;pointer-events:auto;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:flex;flex-direction:column;position:absolute;width:400px;height:150px;z-index:10;font-size:13px}x-pw-dialog-body{display:flex;flex-direction:column;flex:auto}x-pw-dialog-body label{margin:5px 8px;display:flex;flex-direction:row;align-items:center}x-pw-highlight{position:absolute;top:0;left:0;width:0;height:0}x-pw-action-point{position:absolute;width:20px;height:20px;background:red;border-radius:10px;margin:-10px 0 0 -10px;z-index:2}x-pw-separator{height:1px;margin:6px 9px;background:#949494e5}x-pw-tool-gripper{height:28px;width:24px;margin:2px 0;cursor:grab}x-pw-tool-gripper:active{cursor:grabbing}x-pw-tool-gripper>x-div{width:16px;height:16px;margin:6px 4px;clip-path:url(#icon-gripper);background-color:#555}x-pw-tools-list>label{display:flex;align-items:center;margin:0 10px;user-select:none}x-pw-tools-list{display:flex;width:100%;border-bottom:1px solid #dddddd}x-pw-tool-item{pointer-events:auto;height:28px;width:28px;border-radius:3px}x-pw-tool-item:not(.disabled){cursor:pointer}x-pw-tool-item:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.toggled{background-color:#8acae480}x-pw-tool-item.toggled:not(.disabled):hover{background-color:#8acae4c4}x-pw-tool-item>x-div{width:16px;height:16px;margin:6px;background-color:#3a3a3a}x-pw-tool-item.disabled>x-div{background-color:#61616180;cursor:default}x-pw-tool-item.record.toggled{background-color:transparent}x-pw-tool-item.record.toggled:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.record.toggled>x-div{background-color:#a1260d}x-pw-tool-item.record.disabled.toggled>x-div{opacity:.8}x-pw-tool-item.accept>x-div{background-color:#388a34}x-pw-tool-item.record>x-div{clip-path:url(#icon-circle-large-filled)}x-pw-tool-item.pick-locator>x-div{clip-path:url(#icon-inspect)}x-pw-tool-item.text>x-div{clip-path:url(#icon-whole-word)}x-pw-tool-item.visibility>x-div{clip-path:url(#icon-eye)}x-pw-tool-item.value>x-div{clip-path:url(#icon-symbol-constant)}x-pw-tool-item.snapshot>x-div{clip-path:url(#icon-gist)}x-pw-tool-item.accept>x-div{clip-path:url(#icon-check)}x-pw-tool-item.cancel>x-div{clip-path:url(#icon-close)}x-pw-tool-item.succeeded>x-div{clip-path:url(#icon-pass);background-color:#388a34!important}x-pw-overlay{position:absolute;top:0;max-width:min-content;z-index:2147483647;background:transparent;pointer-events:auto}x-pw-overlay x-pw-tools-list{background-color:#fffd;box-shadow:#0000001a 0 5px 5px;border-radius:3px;border-bottom:none}x-pw-overlay x-pw-tool-item{margin:2px}textarea.text-editor{font-family:system-ui,Ubuntu,Droid Sans,sans-serif;flex:auto;border:none;margin:6px 10px;color:#333;outline:1px solid transparent!important;resize:none;padding:0;font-size:13px}textarea.text-editor.does-not-match{outline:1px solid red!important}x-div{display:block}x-spacer{flex:auto}*{box-sizing:border-box}*[hidden]{display:none!important}x-locator-editor{flex:none;width:100%;height:60px;padding:4px;border-bottom:1px solid #dddddd;outline:1px solid transparent}x-locator-editor.does-not-match{outline:1px solid red}.CodeMirror{width:100%!important;height:100%!important}\\n";\n\n// packages/injected/src/highlight.ts\nvar Highlight = class {\n constructor(injectedScript) {\n this._renderedEntries = [];\n this._language = "javascript";\n this._injectedScript = injectedScript;\n const document = injectedScript.document;\n this._isUnderTest = injectedScript.isUnderTest;\n this._glassPaneElement = document.createElement("x-pw-glass");\n this._glassPaneElement.style.position = "fixed";\n this._glassPaneElement.style.top = "0";\n this._glassPaneElement.style.right = "0";\n this._glassPaneElement.style.bottom = "0";\n this._glassPaneElement.style.left = "0";\n this._glassPaneElement.style.zIndex = "2147483646";\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.display = "flex";\n this._glassPaneElement.style.backgroundColor = "transparent";\n for (const eventName of ["click", "auxclick", "dragstart", "input", "keydown", "keyup", "pointerdown", "pointerup", "mousedown", "mouseup", "mouseleave", "focus", "scroll"]) {\n this._glassPaneElement.addEventListener(eventName, (e) => {\n e.stopPropagation();\n e.stopImmediatePropagation();\n });\n }\n this._actionPointElement = document.createElement("x-pw-action-point");\n this._actionPointElement.setAttribute("hidden", "true");\n this._glassPaneShadow = this._glassPaneElement.attachShadow({ mode: this._isUnderTest ? "open" : "closed" });\n if (typeof this._glassPaneShadow.adoptedStyleSheets.push === "function") {\n const sheet = new this._injectedScript.window.CSSStyleSheet();\n sheet.replaceSync(highlight_default);\n this._glassPaneShadow.adoptedStyleSheets.push(sheet);\n } else {\n const styleElement = this._injectedScript.document.createElement("style");\n styleElement.textContent = highlight_default;\n this._glassPaneShadow.appendChild(styleElement);\n }\n this._glassPaneShadow.appendChild(this._actionPointElement);\n }\n install() {\n if (this._injectedScript.document.documentElement && !this._injectedScript.document.documentElement.contains(this._glassPaneElement))\n this._injectedScript.document.documentElement.appendChild(this._glassPaneElement);\n }\n setLanguage(language) {\n this._language = language;\n }\n runHighlightOnRaf(selector) {\n if (this._rafRequest)\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n const elements = this._injectedScript.querySelectorAll(selector, this._injectedScript.document.documentElement);\n const locator = asLocator(this._language, stringifySelector(selector));\n const color = elements.length > 1 ? "#f6b26b7f" : "#6fa8dc7f";\n this.updateHighlight(elements.map((element, index) => {\n const suffix = elements.length > 1 ? ` [${index + 1} of ${elements.length}]` : "";\n return { element, color, tooltipText: locator + suffix };\n }));\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(() => this.runHighlightOnRaf(selector));\n }\n uninstall() {\n if (this._rafRequest)\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._glassPaneElement.remove();\n }\n showActionPoint(x, y) {\n this._actionPointElement.style.top = y + "px";\n this._actionPointElement.style.left = x + "px";\n this._actionPointElement.hidden = false;\n }\n hideActionPoint() {\n this._actionPointElement.hidden = true;\n }\n clearHighlight() {\n var _a, _b;\n for (const entry of this._renderedEntries) {\n (_a = entry.highlightElement) == null ? void 0 : _a.remove();\n (_b = entry.tooltipElement) == null ? void 0 : _b.remove();\n }\n this._renderedEntries = [];\n }\n maskElements(elements, color) {\n this.updateHighlight(elements.map((element) => ({ element, color })));\n }\n updateHighlight(entries) {\n if (this._highlightIsUpToDate(entries))\n return;\n this.clearHighlight();\n for (const entry of entries) {\n const highlightElement = this._createHighlightElement();\n this._glassPaneShadow.appendChild(highlightElement);\n let tooltipElement;\n if (entry.tooltipText) {\n tooltipElement = this._injectedScript.document.createElement("x-pw-tooltip");\n this._glassPaneShadow.appendChild(tooltipElement);\n tooltipElement.style.top = "0";\n tooltipElement.style.left = "0";\n tooltipElement.style.display = "flex";\n const lineElement = this._injectedScript.document.createElement("x-pw-tooltip-line");\n lineElement.textContent = entry.tooltipText;\n tooltipElement.appendChild(lineElement);\n }\n this._renderedEntries.push({ targetElement: entry.element, color: entry.color, tooltipElement, highlightElement });\n }\n for (const entry of this._renderedEntries) {\n entry.box = entry.targetElement.getBoundingClientRect();\n if (!entry.tooltipElement)\n continue;\n const { anchorLeft, anchorTop } = this.tooltipPosition(entry.box, entry.tooltipElement);\n entry.tooltipTop = anchorTop;\n entry.tooltipLeft = anchorLeft;\n }\n for (const entry of this._renderedEntries) {\n if (entry.tooltipElement) {\n entry.tooltipElement.style.top = entry.tooltipTop + "px";\n entry.tooltipElement.style.left = entry.tooltipLeft + "px";\n }\n const box2 = entry.box;\n entry.highlightElement.style.backgroundColor = entry.color;\n entry.highlightElement.style.left = box2.x + "px";\n entry.highlightElement.style.top = box2.y + "px";\n entry.highlightElement.style.width = box2.width + "px";\n entry.highlightElement.style.height = box2.height + "px";\n entry.highlightElement.style.display = "block";\n if (this._isUnderTest)\n console.error("Highlight box for test: " + JSON.stringify({ x: box2.x, y: box2.y, width: box2.width, height: box2.height }));\n }\n }\n firstBox() {\n var _a;\n return (_a = this._renderedEntries[0]) == null ? void 0 : _a.box;\n }\n tooltipPosition(box2, tooltipElement) {\n const tooltipWidth = tooltipElement.offsetWidth;\n const tooltipHeight = tooltipElement.offsetHeight;\n const totalWidth = this._glassPaneElement.offsetWidth;\n const totalHeight = this._glassPaneElement.offsetHeight;\n let anchorLeft = box2.left;\n if (anchorLeft + tooltipWidth > totalWidth - 5)\n anchorLeft = totalWidth - tooltipWidth - 5;\n let anchorTop = box2.bottom + 5;\n if (anchorTop + tooltipHeight > totalHeight - 5) {\n if (box2.top > tooltipHeight + 5) {\n anchorTop = box2.top - tooltipHeight - 5;\n } else {\n anchorTop = totalHeight - 5 - tooltipHeight;\n }\n }\n return { anchorLeft, anchorTop };\n }\n _highlightIsUpToDate(entries) {\n if (entries.length !== this._renderedEntries.length)\n return false;\n for (let i = 0; i < this._renderedEntries.length; ++i) {\n if (entries[i].element !== this._renderedEntries[i].targetElement)\n return false;\n if (entries[i].color !== this._renderedEntries[i].color)\n return false;\n const oldBox = this._renderedEntries[i].box;\n if (!oldBox)\n return false;\n const box2 = entries[i].element.getBoundingClientRect();\n if (box2.top !== oldBox.top || box2.right !== oldBox.right || box2.bottom !== oldBox.bottom || box2.left !== oldBox.left)\n return false;\n }\n return true;\n }\n _createHighlightElement() {\n return this._injectedScript.document.createElement("x-pw-highlight");\n }\n appendChild(element) {\n this._glassPaneShadow.appendChild(element);\n }\n};\n\n// packages/injected/src/layoutSelectorUtils.ts\nfunction boxRightOf(box1, box2, maxDistance) {\n const distance = box1.left - box2.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxLeftOf(box1, box2, maxDistance) {\n const distance = box2.left - box1.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxAbove(box1, box2, maxDistance) {\n const distance = box2.top - box1.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxBelow(box1, box2, maxDistance) {\n const distance = box1.top - box2.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxNear(box1, box2, maxDistance) {\n const kThreshold = maxDistance === void 0 ? 50 : maxDistance;\n let score = 0;\n if (box1.left - box2.right >= 0)\n score += box1.left - box2.right;\n if (box2.left - box1.right >= 0)\n score += box2.left - box1.right;\n if (box2.top - box1.bottom >= 0)\n score += box2.top - box1.bottom;\n if (box1.top - box2.bottom >= 0)\n score += box1.top - box2.bottom;\n return score > kThreshold ? void 0 : score;\n}\nvar kLayoutSelectorNames = ["left-of", "right-of", "above", "below", "near"];\nfunction layoutSelectorScore(name, element, inner, maxDistance) {\n const box2 = element.getBoundingClientRect();\n const scorer = { "left-of": boxLeftOf, "right-of": boxRightOf, "above": boxAbove, "below": boxBelow, "near": boxNear }[name];\n let bestScore;\n for (const e of inner) {\n if (e === element)\n continue;\n const score = scorer(box2, e.getBoundingClientRect(), maxDistance);\n if (score === void 0)\n continue;\n if (bestScore === void 0 || score < bestScore)\n bestScore = score;\n }\n return bestScore;\n}\n\n// packages/injected/src/selectorUtils.ts\nfunction matchesComponentAttribute(obj, attr) {\n for (const token of attr.jsonPath) {\n if (obj !== void 0 && obj !== null)\n obj = obj[token];\n }\n return matchesAttributePart(obj, attr);\n}\nfunction matchesAttributePart(value, attr) {\n const objValue = typeof value === "string" && !attr.caseSensitive ? value.toUpperCase() : value;\n const attrValue = typeof attr.value === "string" && !attr.caseSensitive ? attr.value.toUpperCase() : attr.value;\n if (attr.op === "")\n return !!objValue;\n if (attr.op === "=") {\n if (attrValue instanceof RegExp)\n return typeof objValue === "string" && !!objValue.match(attrValue);\n return objValue === attrValue;\n }\n if (typeof objValue !== "string" || typeof attrValue !== "string")\n return false;\n if (attr.op === "*=")\n return objValue.includes(attrValue);\n if (attr.op === "^=")\n return objValue.startsWith(attrValue);\n if (attr.op === "$=")\n return objValue.endsWith(attrValue);\n if (attr.op === "|=")\n return objValue === attrValue || objValue.startsWith(attrValue + "-");\n if (attr.op === "~=")\n return objValue.split(" ").includes(attrValue);\n return false;\n}\nfunction shouldSkipForTextMatching(element) {\n const document = element.ownerDocument;\n return element.nodeName === "SCRIPT" || element.nodeName === "NOSCRIPT" || element.nodeName === "STYLE" || document.head && document.head.contains(element);\n}\nfunction elementText(cache, root) {\n let value = cache.get(root);\n if (value === void 0) {\n value = { full: "", normalized: "", immediate: [] };\n if (!shouldSkipForTextMatching(root)) {\n let currentImmediate = "";\n if (root instanceof HTMLInputElement && (root.type === "submit" || root.type === "button")) {\n value = { full: root.value, normalized: normalizeWhiteSpace(root.value), immediate: [root.value] };\n } else {\n for (let child = root.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.TEXT_NODE) {\n value.full += child.nodeValue || "";\n currentImmediate += child.nodeValue || "";\n } else if (child.nodeType === Node.COMMENT_NODE) {\n continue;\n } else {\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n currentImmediate = "";\n if (child.nodeType === Node.ELEMENT_NODE)\n value.full += elementText(cache, child).full;\n }\n }\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n if (root.shadowRoot)\n value.full += elementText(cache, root.shadowRoot).full;\n if (value.full)\n value.normalized = normalizeWhiteSpace(value.full);\n }\n }\n cache.set(root, value);\n }\n return value;\n}\nfunction elementMatchesText(cache, element, matcher) {\n if (shouldSkipForTextMatching(element))\n return "none";\n if (!matcher(elementText(cache, element)))\n return "none";\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.ELEMENT_NODE && matcher(elementText(cache, child)))\n return "selfAndChildren";\n }\n if (element.shadowRoot && matcher(elementText(cache, element.shadowRoot)))\n return "selfAndChildren";\n return "self";\n}\nfunction getElementLabels(textCache, element) {\n const labels = getAriaLabelledByElements(element);\n if (labels)\n return labels.map((label) => elementText(textCache, label));\n const ariaLabel = element.getAttribute("aria-label");\n if (ariaLabel !== null && !!ariaLabel.trim())\n return [{ full: ariaLabel, normalized: normalizeWhiteSpace(ariaLabel), immediate: [ariaLabel] }];\n const isNonHiddenInput = element.nodeName === "INPUT" && element.type !== "hidden";\n if (["BUTTON", "METER", "OUTPUT", "PROGRESS", "SELECT", "TEXTAREA"].includes(element.nodeName) || isNonHiddenInput) {\n const labels2 = element.labels;\n if (labels2)\n return [...labels2].map((label) => elementText(textCache, label));\n }\n return [];\n}\n\n// packages/injected/src/reactSelectorEngine.ts\nfunction getFunctionComponentName(component) {\n return component.displayName || component.name || "Anonymous";\n}\nfunction getComponentName(reactElement) {\n if (reactElement.type) {\n switch (typeof reactElement.type) {\n case "function":\n return getFunctionComponentName(reactElement.type);\n case "string":\n return reactElement.type;\n case "object":\n return reactElement.type.displayName || (reactElement.type.render ? getFunctionComponentName(reactElement.type.render) : "");\n }\n }\n if (reactElement._currentElement) {\n const elementType = reactElement._currentElement.type;\n if (typeof elementType === "string")\n return elementType;\n if (typeof elementType === "function")\n return elementType.displayName || elementType.name || "Anonymous";\n }\n return "";\n}\nfunction getComponentKey(reactElement) {\n var _a, _b;\n return (_b = reactElement.key) != null ? _b : (_a = reactElement._currentElement) == null ? void 0 : _a.key;\n}\nfunction getChildren(reactElement) {\n if (reactElement.child) {\n const children = [];\n for (let child = reactElement.child; child; child = child.sibling)\n children.push(child);\n return children;\n }\n if (!reactElement._currentElement)\n return [];\n const isKnownElement = (reactElement2) => {\n var _a;\n const elementType = (_a = reactElement2._currentElement) == null ? void 0 : _a.type;\n return typeof elementType === "function" || typeof elementType === "string";\n };\n if (reactElement._renderedComponent) {\n const child = reactElement._renderedComponent;\n return isKnownElement(child) ? [child] : [];\n }\n if (reactElement._renderedChildren)\n return [...Object.values(reactElement._renderedChildren)].filter(isKnownElement);\n return [];\n}\nfunction getProps(reactElement) {\n var _a;\n const props = (\n // React 16+\n reactElement.memoizedProps || // React 15\n ((_a = reactElement._currentElement) == null ? void 0 : _a.props)\n );\n if (!props || typeof props === "string")\n return props;\n const result = { ...props };\n delete result.children;\n return result;\n}\nfunction buildComponentsTree(reactElement) {\n var _a;\n const treeNode = {\n key: getComponentKey(reactElement),\n name: getComponentName(reactElement),\n children: getChildren(reactElement).map(buildComponentsTree),\n rootElements: [],\n props: getProps(reactElement)\n };\n const rootElement = (\n // React 16+\n // @see https://github.com/baruchvlz/resq/blob/5c15a5e04d3f7174087248f5a158c3d6dcc1ec72/src/utils.js#L29\n reactElement.stateNode || // React 15\n reactElement._hostNode || ((_a = reactElement._renderedComponent) == null ? void 0 : _a._hostNode)\n );\n if (rootElement instanceof Element) {\n treeNode.rootElements.push(rootElement);\n } else {\n for (const child of treeNode.children)\n treeNode.rootElements.push(...child.rootElements);\n }\n return treeNode;\n}\nfunction filterComponentsTree(treeNode, searchFn, result = []) {\n if (searchFn(treeNode))\n result.push(treeNode);\n for (const child of treeNode.children)\n filterComponentsTree(child, searchFn, result);\n return result;\n}\nfunction findReactRoots(root, roots = []) {\n const document = root.ownerDocument || root;\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);\n do {\n const node = walker.currentNode;\n const reactNode = node;\n const rootKey = Object.keys(reactNode).find((key) => key.startsWith("__reactContainer") && reactNode[key] !== null);\n if (rootKey) {\n roots.push(reactNode[rootKey].stateNode.current);\n } else {\n const legacyRootKey = "_reactRootContainer";\n if (reactNode.hasOwnProperty(legacyRootKey) && reactNode[legacyRootKey] !== null) {\n roots.push(reactNode[legacyRootKey]._internalRoot.current);\n }\n }\n if (node instanceof Element && node.hasAttribute("data-reactroot")) {\n for (const key of Object.keys(node)) {\n if (key.startsWith("__reactInternalInstance") || key.startsWith("__reactFiber"))\n roots.push(node[key]);\n }\n }\n const shadowRoot = node instanceof Element ? node.shadowRoot : null;\n if (shadowRoot)\n findReactRoots(shadowRoot, roots);\n } while (walker.nextNode());\n return roots;\n}\nvar createReactEngine = () => ({\n queryAll(scope, selector) {\n const { name, attributes } = parseAttributeSelector(selector, false);\n const reactRoots = findReactRoots(scope.ownerDocument || scope);\n const trees = reactRoots.map((reactRoot) => buildComponentsTree(reactRoot));\n const treeNodes = trees.map((tree) => filterComponentsTree(tree, (treeNode) => {\n var _a;\n const props = (_a = treeNode.props) != null ? _a : {};\n if (treeNode.key !== void 0)\n props.key = treeNode.key;\n if (name && treeNode.name !== name)\n return false;\n if (treeNode.rootElements.some((domNode) => !isInsideScope(scope, domNode)))\n return false;\n for (const attr of attributes) {\n if (!matchesComponentAttribute(props, attr))\n return false;\n }\n return true;\n })).flat();\n const allRootElements = /* @__PURE__ */ new Set();\n for (const treeNode of treeNodes) {\n for (const domNode of treeNode.rootElements)\n allRootElements.add(domNode);\n }\n return [...allRootElements];\n }\n});\n\n// packages/injected/src/roleSelectorEngine.ts\nvar kSupportedAttributes = ["selected", "checked", "pressed", "expanded", "level", "disabled", "name", "include-hidden"];\nkSupportedAttributes.sort();\nfunction validateSupportedRole(attr, roles, role) {\n if (!roles.includes(role))\n throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map((role2) => `"${role2}"`).join(", ")}`);\n}\nfunction validateSupportedValues(attr, values) {\n if (attr.op !== "" && !values.includes(attr.value))\n throw new Error(`"${attr.name}" must be one of ${values.map((v) => JSON.stringify(v)).join(", ")}`);\n}\nfunction validateSupportedOp(attr, ops) {\n if (!ops.includes(attr.op))\n throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);\n}\nfunction validateAttributes(attrs, role) {\n const options = { role };\n for (const attr of attrs) {\n switch (attr.name) {\n case "checked": {\n validateSupportedRole(attr.name, kAriaCheckedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.checked = attr.op === "" ? true : attr.value;\n break;\n }\n case "pressed": {\n validateSupportedRole(attr.name, kAriaPressedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.pressed = attr.op === "" ? true : attr.value;\n break;\n }\n case "selected": {\n validateSupportedRole(attr.name, kAriaSelectedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.selected = attr.op === "" ? true : attr.value;\n break;\n }\n case "expanded": {\n validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.expanded = attr.op === "" ? true : attr.value;\n break;\n }\n case "level": {\n validateSupportedRole(attr.name, kAriaLevelRoles, role);\n if (typeof attr.value === "string")\n attr.value = +attr.value;\n if (attr.op !== "=" || typeof attr.value !== "number" || Number.isNaN(attr.value))\n throw new Error(`"level" attribute must be compared to a number`);\n options.level = attr.value;\n break;\n }\n case "disabled": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.disabled = attr.op === "" ? true : attr.value;\n break;\n }\n case "name": {\n if (attr.op === "")\n throw new Error(`"name" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"name" attribute must be a string or a regular expression`);\n options.name = attr.value;\n options.nameOp = attr.op;\n options.exact = attr.caseSensitive;\n break;\n }\n case "include-hidden": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.includeHidden = attr.op === "" ? true : attr.value;\n break;\n }\n default: {\n throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map((a) => `"${a}"`).join(", ")}.`);\n }\n }\n }\n return options;\n}\nfunction queryRole(scope, options, internal) {\n const result = [];\n const match = (element) => {\n if (getAriaRole(element) !== options.role)\n return;\n if (options.selected !== void 0 && getAriaSelected(element) !== options.selected)\n return;\n if (options.checked !== void 0 && getAriaChecked(element) !== options.checked)\n return;\n if (options.pressed !== void 0 && getAriaPressed(element) !== options.pressed)\n return;\n if (options.expanded !== void 0 && getAriaExpanded(element) !== options.expanded)\n return;\n if (options.level !== void 0 && getAriaLevel(element) !== options.level)\n return;\n if (options.disabled !== void 0 && getAriaDisabled(element) !== options.disabled)\n return;\n if (!options.includeHidden) {\n const isHidden = isElementHiddenForAria(element);\n if (isHidden)\n return;\n }\n if (options.name !== void 0) {\n const accessibleName = normalizeWhiteSpace(getElementAccessibleName(element, !!options.includeHidden));\n if (typeof options.name === "string")\n options.name = normalizeWhiteSpace(options.name);\n if (internal && !options.exact && options.nameOp === "=")\n options.nameOp = "*=";\n if (!matchesAttributePart(accessibleName, { name: "", jsonPath: [], op: options.nameOp || "=", value: options.name, caseSensitive: !!options.exact }))\n return;\n }\n result.push(element);\n };\n const query = (root) => {\n const shadows = [];\n if (root.shadowRoot)\n shadows.push(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n match(element);\n if (element.shadowRoot)\n shadows.push(element.shadowRoot);\n }\n shadows.forEach(query);\n };\n query(scope);\n return result;\n}\nfunction createRoleEngine(internal) {\n return {\n queryAll: (scope, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n const role = parsed.name.toLowerCase();\n if (!role)\n throw new Error(`Role must not be empty`);\n const options = validateAttributes(parsed.attributes, role);\n beginAriaCaches();\n try {\n return queryRole(scope, options, internal);\n } finally {\n endAriaCaches();\n }\n }\n };\n}\n\n// packages/injected/src/selectorEvaluator.ts\nvar SelectorEvaluatorImpl = class {\n constructor() {\n this._retainCacheCounter = 0;\n this._cacheText = /* @__PURE__ */ new Map();\n this._cacheQueryCSS = /* @__PURE__ */ new Map();\n this._cacheMatches = /* @__PURE__ */ new Map();\n this._cacheQuery = /* @__PURE__ */ new Map();\n this._cacheMatchesSimple = /* @__PURE__ */ new Map();\n this._cacheMatchesParents = /* @__PURE__ */ new Map();\n this._cacheCallMatches = /* @__PURE__ */ new Map();\n this._cacheCallQuery = /* @__PURE__ */ new Map();\n this._cacheQuerySimple = /* @__PURE__ */ new Map();\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("not", notEngine);\n this._engines.set("is", isEngine);\n this._engines.set("where", isEngine);\n this._engines.set("has", hasEngine);\n this._engines.set("scope", scopeEngine);\n this._engines.set("light", lightEngine);\n this._engines.set("visible", visibleEngine);\n this._engines.set("text", textEngine);\n this._engines.set("text-is", textIsEngine);\n this._engines.set("text-matches", textMatchesEngine);\n this._engines.set("has-text", hasTextEngine);\n this._engines.set("right-of", createLayoutEngine("right-of"));\n this._engines.set("left-of", createLayoutEngine("left-of"));\n this._engines.set("above", createLayoutEngine("above"));\n this._engines.set("below", createLayoutEngine("below"));\n this._engines.set("near", createLayoutEngine("near"));\n this._engines.set("nth-match", nthMatchEngine);\n const allNames = [...this._engines.keys()];\n allNames.sort();\n const parserNames = [...customCSSNames];\n parserNames.sort();\n if (allNames.join("|") !== parserNames.join("|"))\n throw new Error(`Please keep customCSSNames in sync with evaluator engines: ${allNames.join("|")} vs ${parserNames.join("|")}`);\n }\n begin() {\n ++this._retainCacheCounter;\n }\n end() {\n --this._retainCacheCounter;\n if (!this._retainCacheCounter) {\n this._cacheQueryCSS.clear();\n this._cacheMatches.clear();\n this._cacheQuery.clear();\n this._cacheMatchesSimple.clear();\n this._cacheMatchesParents.clear();\n this._cacheCallMatches.clear();\n this._cacheCallQuery.clear();\n this._cacheQuerySimple.clear();\n this._cacheText.clear();\n }\n }\n _cached(cache, main, rest, cb) {\n if (!cache.has(main))\n cache.set(main, []);\n const entries = cache.get(main);\n const entry = entries.find((e) => rest.every((value, index) => e.rest[index] === value));\n if (entry)\n return entry.result;\n const result = cb();\n entries.push({ rest, result });\n return result;\n }\n _checkSelector(s) {\n const wellFormed = typeof s === "object" && s && (Array.isArray(s) || "simples" in s && s.simples.length);\n if (!wellFormed)\n throw new Error(`Malformed selector "${s}"`);\n return s;\n }\n matches(element, s, context) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheMatches, element, [selector, context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._matchesEngine(isEngine, element, selector, context);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n if (!this._matchesSimple(element, selector.simples[selector.simples.length - 1].selector, context))\n return false;\n return this._matchesParents(element, selector, selector.simples.length - 2, context);\n });\n } finally {\n this.end();\n }\n }\n query(context, s) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheQuery, selector, [context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._queryEngine(isEngine, context, selector);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n const previousScoreMap = this._scoreMap;\n this._scoreMap = /* @__PURE__ */ new Map();\n let elements = this._querySimple(context, selector.simples[selector.simples.length - 1].selector);\n elements = elements.filter((element) => this._matchesParents(element, selector, selector.simples.length - 2, context));\n if (this._scoreMap.size) {\n elements.sort((a, b) => {\n const aScore = this._scoreMap.get(a);\n const bScore = this._scoreMap.get(b);\n if (aScore === bScore)\n return 0;\n if (aScore === void 0)\n return 1;\n if (bScore === void 0)\n return -1;\n return aScore - bScore;\n });\n }\n this._scoreMap = previousScoreMap;\n return elements;\n });\n } finally {\n this.end();\n }\n }\n _markScore(element, score) {\n if (this._scoreMap)\n this._scoreMap.set(element, score);\n }\n _hasScopeClause(selector) {\n return selector.simples.some((simple) => simple.selector.functions.some((f) => f.name === "scope"));\n }\n _expandContextForScopeMatching(context) {\n if (context.scope.nodeType !== 1)\n return context;\n const scope = parentElementOrShadowHost(context.scope);\n if (!scope)\n return context;\n return { ...context, scope, originalScope: context.originalScope || context.scope };\n }\n _matchesSimple(element, simple, context) {\n return this._cached(this._cacheMatchesSimple, element, [simple, context.scope, context.pierceShadow, context.originalScope], () => {\n if (element === context.scope)\n return false;\n if (simple.css && !this._matchesCSS(element, simple.css))\n return false;\n for (const func of simple.functions) {\n if (!this._matchesEngine(this._getEngine(func.name), element, func.args, context))\n return false;\n }\n return true;\n });\n }\n _querySimple(context, simple) {\n if (!simple.functions.length)\n return this._queryCSS(context, simple.css || "*");\n return this._cached(this._cacheQuerySimple, simple, [context.scope, context.pierceShadow, context.originalScope], () => {\n let css = simple.css;\n const funcs = simple.functions;\n if (css === "*" && funcs.length)\n css = void 0;\n let elements;\n let firstIndex = -1;\n if (css !== void 0) {\n elements = this._queryCSS(context, css);\n } else {\n firstIndex = funcs.findIndex((func) => this._getEngine(func.name).query !== void 0);\n if (firstIndex === -1)\n firstIndex = 0;\n elements = this._queryEngine(this._getEngine(funcs[firstIndex].name), context, funcs[firstIndex].args);\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches !== void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches === void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n return elements;\n });\n }\n _matchesParents(element, complex, index, context) {\n if (index < 0)\n return true;\n return this._cached(this._cacheMatchesParents, element, [complex, index, context.scope, context.pierceShadow, context.originalScope], () => {\n const { selector: simple, combinator } = complex.simples[index];\n if (combinator === ">") {\n const parent = parentElementOrShadowHostInContext(element, context);\n if (!parent || !this._matchesSimple(parent, simple, context))\n return false;\n return this._matchesParents(parent, complex, index - 1, context);\n }\n if (combinator === "+") {\n const previousSibling = previousSiblingInContext(element, context);\n if (!previousSibling || !this._matchesSimple(previousSibling, simple, context))\n return false;\n return this._matchesParents(previousSibling, complex, index - 1, context);\n }\n if (combinator === "") {\n let parent = parentElementOrShadowHostInContext(element, context);\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n if (combinator === "~") {\n let previousSibling = previousSiblingInContext(element, context);\n while (previousSibling) {\n if (this._matchesSimple(previousSibling, simple, context)) {\n if (this._matchesParents(previousSibling, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "~")\n break;\n }\n previousSibling = previousSiblingInContext(previousSibling, context);\n }\n return false;\n }\n if (combinator === ">=") {\n let parent = element;\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n throw new Error(`Unsupported combinator "${combinator}"`);\n });\n }\n _matchesEngine(engine, element, args, context) {\n if (engine.matches)\n return this._callMatches(engine, element, args, context);\n if (engine.query)\n return this._callQuery(engine, args, context).includes(element);\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _queryEngine(engine, context, args) {\n if (engine.query)\n return this._callQuery(engine, args, context);\n if (engine.matches)\n return this._queryCSS(context, "*").filter((element) => this._callMatches(engine, element, args, context));\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _callMatches(engine, element, args, context) {\n return this._cached(this._cacheCallMatches, element, [engine, context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.matches(element, args, context, this);\n });\n }\n _callQuery(engine, args, context) {\n return this._cached(this._cacheCallQuery, engine, [context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.query(context, args, this);\n });\n }\n _matchesCSS(element, css) {\n return element.matches(css);\n }\n _queryCSS(context, css) {\n return this._cached(this._cacheQueryCSS, css, [context.scope, context.pierceShadow, context.originalScope], () => {\n let result = [];\n function query(root) {\n result = result.concat([...root.querySelectorAll(css)]);\n if (!context.pierceShadow)\n return;\n if (root.shadowRoot)\n query(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n if (element.shadowRoot)\n query(element.shadowRoot);\n }\n }\n query(context.scope);\n return result;\n });\n }\n _getEngine(name) {\n const engine = this._engines.get(name);\n if (!engine)\n throw new Error(`Unknown selector engine "${name}"`);\n return engine;\n }\n};\nvar isEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n return args.some((selector) => evaluator.matches(element, selector, context));\n },\n query(context, args, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n let elements = [];\n for (const arg of args)\n elements = elements.concat(evaluator.query(context, arg));\n return args.length === 1 ? elements : sortInDOMOrder(elements);\n }\n};\nvar hasEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"has" engine expects non-empty selector list`);\n return evaluator.query({ ...context, scope: element }, args).length > 0;\n }\n // TODO: we can implement efficient "query" by matching "args" and returning\n // all parents/descendants, just have to be careful with the ":scope" matching.\n};\nvar scopeEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9)\n return element === actualScope.documentElement;\n return element === actualScope;\n },\n query(context, args, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9) {\n const root = actualScope.documentElement;\n return root ? [root] : [];\n }\n if (actualScope.nodeType === 1)\n return [actualScope];\n return [];\n }\n};\nvar notEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"not" engine expects non-empty selector list`);\n return !evaluator.matches(element, args, context);\n }\n};\nvar lightEngine = {\n query(context, args, evaluator) {\n return evaluator.query({ ...context, pierceShadow: false }, args);\n },\n matches(element, args, context, evaluator) {\n return evaluator.matches(element, args, { ...context, pierceShadow: false });\n }\n};\nvar visibleEngine = {\n matches(element, args, context, evaluator) {\n if (args.length)\n throw new Error(`"visible" engine expects no arguments`);\n return isElementVisible(element);\n }\n};\nvar textEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar textIsEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text-is" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]);\n const matcher = (elementText2) => {\n if (!text && !elementText2.immediate.length)\n return true;\n return elementText2.immediate.some((s) => normalizeWhiteSpace(s) === text);\n };\n return elementMatchesText(evaluator._cacheText, element, matcher) !== "none";\n }\n};\nvar textMatchesEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0 || typeof args[0] !== "string" || args.length > 2 || args.length === 2 && typeof args[1] !== "string")\n throw new Error(`"text-matches" engine expects a regexp body and optional regexp flags`);\n const re = new RegExp(args[0], args.length === 2 ? args[1] : void 0);\n const matcher = (elementText2) => re.test(elementText2.full);\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar hasTextEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"has-text" engine expects a single string`);\n if (shouldSkipForTextMatching(element))\n return false;\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return matcher(elementText(evaluator._cacheText, element));\n }\n};\nfunction createLayoutEngine(name) {\n return {\n matches(element, args, context, evaluator) {\n const maxDistance = args.length && typeof args[args.length - 1] === "number" ? args[args.length - 1] : void 0;\n const queryArgs = maxDistance === void 0 ? args : args.slice(0, args.length - 1);\n if (args.length < 1 + (maxDistance === void 0 ? 0 : 1))\n throw new Error(`"${name}" engine expects a selector list and optional maximum distance in pixels`);\n const inner = evaluator.query(context, queryArgs);\n const score = layoutSelectorScore(name, element, inner, maxDistance);\n if (score === void 0)\n return false;\n evaluator._markScore(element, score);\n return true;\n }\n };\n}\nvar nthMatchEngine = {\n query(context, args, evaluator) {\n let index = args[args.length - 1];\n if (args.length < 2)\n throw new Error(`"nth-match" engine expects non-empty selector list and an index argument`);\n if (typeof index !== "number" || index < 1)\n throw new Error(`"nth-match" engine expects a one-based index as the last argument`);\n const elements = isEngine.query(context, args.slice(0, args.length - 1), evaluator);\n index--;\n return index < elements.length ? [elements[index]] : [];\n }\n};\nfunction parentElementOrShadowHostInContext(element, context) {\n if (element === context.scope)\n return;\n if (!context.pierceShadow)\n return element.parentElement || void 0;\n return parentElementOrShadowHost(element);\n}\nfunction previousSiblingInContext(element, context) {\n if (element === context.scope)\n return;\n return element.previousElementSibling || void 0;\n}\nfunction sortInDOMOrder(elements) {\n const elementToEntry = /* @__PURE__ */ new Map();\n const roots = [];\n const result = [];\n function append(element) {\n let entry = elementToEntry.get(element);\n if (entry)\n return entry;\n const parent = parentElementOrShadowHost(element);\n if (parent) {\n const parentEntry = append(parent);\n parentEntry.children.push(element);\n } else {\n roots.push(element);\n }\n entry = { children: [], taken: false };\n elementToEntry.set(element, entry);\n return entry;\n }\n for (const e of elements)\n append(e).taken = true;\n function visit(element) {\n const entry = elementToEntry.get(element);\n if (entry.taken)\n result.push(element);\n if (entry.children.length > 1) {\n const set = new Set(entry.children);\n entry.children = [];\n let child = element.firstElementChild;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n child = element.shadowRoot ? element.shadowRoot.firstElementChild : null;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n }\n entry.children.forEach(visit);\n }\n roots.forEach(visit);\n return result;\n}\n\n// packages/injected/src/selectorGenerator.ts\nvar kTextScoreRange = 10;\nvar kExactPenalty = kTextScoreRange / 2;\nvar kTestIdScore = 1;\nvar kOtherTestIdScore = 2;\nvar kIframeByAttributeScore = 10;\nvar kBeginPenalizedScore = 50;\nvar kRoleWithNameScore = 100;\nvar kPlaceholderScore = 120;\nvar kLabelScore = 140;\nvar kAltTextScore = 160;\nvar kTextScore = 180;\nvar kTitleScore = 200;\nvar kTextScoreRegex = 250;\nvar kPlaceholderScoreExact = kPlaceholderScore + kExactPenalty;\nvar kLabelScoreExact = kLabelScore + kExactPenalty;\nvar kRoleWithNameScoreExact = kRoleWithNameScore + kExactPenalty;\nvar kAltTextScoreExact = kAltTextScore + kExactPenalty;\nvar kTextScoreExact = kTextScore + kExactPenalty;\nvar kTitleScoreExact = kTitleScore + kExactPenalty;\nvar kEndPenalizedScore = 300;\nvar kCSSIdScore = 500;\nvar kRoleWithoutNameScore = 510;\nvar kCSSInputTypeNameScore = 520;\nvar kCSSTagNameScore = 530;\nvar kNthScore = 1e4;\nvar kCSSFallbackScore = 1e7;\nvar kScoreThresholdForTextExpect = 1e3;\nfunction generateSelector(injectedScript, targetElement, options) {\n var _a;\n injectedScript._evaluator.begin();\n const cache = { allowText: /* @__PURE__ */ new Map(), disallowText: /* @__PURE__ */ new Map() };\n beginAriaCaches();\n try {\n let selectors = [];\n if (options.forTextExpect) {\n let targetTokens = cssFallback(injectedScript, targetElement.ownerDocument.documentElement, options);\n for (let element = targetElement; element; element = parentElementOrShadowHost(element)) {\n const tokens = generateSelectorFor(cache, injectedScript, element, { ...options, noText: true });\n if (!tokens)\n continue;\n const score = combineScores(tokens);\n if (score <= kScoreThresholdForTextExpect) {\n targetTokens = tokens;\n break;\n }\n }\n selectors = [joinTokens(targetTokens)];\n } else {\n if (!targetElement.matches("input,textarea,select") && !targetElement.isContentEditable) {\n const interactiveParent = closestCrossShadow(targetElement, "button,select,input,[role=button],[role=checkbox],[role=radio],a,[role=link]", options.root);\n if (interactiveParent && isElementVisible(interactiveParent))\n targetElement = interactiveParent;\n }\n if (options.multiple) {\n const withText = generateSelectorFor(cache, injectedScript, targetElement, options);\n const withoutText = generateSelectorFor(cache, injectedScript, targetElement, { ...options, noText: true });\n let tokens = [withText, withoutText];\n cache.allowText.clear();\n cache.disallowText.clear();\n if (withText && hasCSSIdToken(withText))\n tokens.push(generateSelectorFor(cache, injectedScript, targetElement, { ...options, noCSSId: true }));\n if (withoutText && hasCSSIdToken(withoutText))\n tokens.push(generateSelectorFor(cache, injectedScript, targetElement, { ...options, noText: true, noCSSId: true }));\n tokens = tokens.filter(Boolean);\n if (!tokens.length) {\n const css = cssFallback(injectedScript, targetElement, options);\n tokens.push(css);\n if (hasCSSIdToken(css))\n tokens.push(cssFallback(injectedScript, targetElement, { ...options, noCSSId: true }));\n }\n selectors = [...new Set(tokens.map((t) => joinTokens(t)))];\n } else {\n const targetTokens = generateSelectorFor(cache, injectedScript, targetElement, options) || cssFallback(injectedScript, targetElement, options);\n selectors = [joinTokens(targetTokens)];\n }\n }\n const selector = selectors[0];\n const parsedSelector = injectedScript.parseSelector(selector);\n return {\n selector,\n selectors,\n elements: injectedScript.querySelectorAll(parsedSelector, (_a = options.root) != null ? _a : targetElement.ownerDocument)\n };\n } finally {\n endAriaCaches();\n injectedScript._evaluator.end();\n }\n}\nfunction filterRegexTokens(textCandidates) {\n return textCandidates.filter((c) => c[0].selector[0] !== "/");\n}\nfunction generateSelectorFor(cache, injectedScript, targetElement, options) {\n if (options.root && !isInsideScope(options.root, targetElement))\n throw new Error(`Target element must belong to the root\'s subtree`);\n if (targetElement === options.root)\n return [{ engine: "css", selector: ":scope", score: 1 }];\n if (targetElement.ownerDocument.documentElement === targetElement)\n return [{ engine: "css", selector: "html", score: 1 }];\n const calculate = (element, allowText) => {\n var _a;\n const allowNthMatch = element === targetElement;\n let textCandidates = allowText ? buildTextCandidates(injectedScript, element, element === targetElement) : [];\n if (element !== targetElement) {\n textCandidates = filterRegexTokens(textCandidates);\n }\n const noTextCandidates = buildNoTextCandidates(injectedScript, element, options).filter((token) => !options.omitInternalEngines || !token.engine.startsWith("internal:")).map((token) => [token]);\n let result = chooseFirstSelector(injectedScript, (_a = options.root) != null ? _a : targetElement.ownerDocument, element, [...textCandidates, ...noTextCandidates], allowNthMatch);\n textCandidates = filterRegexTokens(textCandidates);\n const checkWithText = (textCandidatesToUse) => {\n const allowParentText = allowText && !textCandidatesToUse.length;\n const candidates = [...textCandidatesToUse, ...noTextCandidates].filter((c) => {\n if (!result)\n return true;\n return combineScores(c) < combineScores(result);\n });\n let bestPossibleInParent = candidates[0];\n if (!bestPossibleInParent)\n return;\n for (let parent = parentElementOrShadowHost(element); parent && parent !== options.root; parent = parentElementOrShadowHost(parent)) {\n const parentTokens = calculateCached(parent, allowParentText);\n if (!parentTokens)\n continue;\n if (result && combineScores([...parentTokens, ...bestPossibleInParent]) >= combineScores(result))\n continue;\n bestPossibleInParent = chooseFirstSelector(injectedScript, parent, element, candidates, allowNthMatch);\n if (!bestPossibleInParent)\n return;\n const combined = [...parentTokens, ...bestPossibleInParent];\n if (!result || combineScores(combined) < combineScores(result))\n result = combined;\n }\n };\n checkWithText(textCandidates);\n if (element === targetElement && textCandidates.length)\n checkWithText([]);\n return result;\n };\n const calculateCached = (element, allowText) => {\n const map = allowText ? cache.allowText : cache.disallowText;\n let value = map.get(element);\n if (value === void 0) {\n value = calculate(element, allowText);\n map.set(element, value);\n }\n return value;\n };\n return calculate(targetElement, !options.noText);\n}\nfunction buildNoTextCandidates(injectedScript, element, options) {\n const candidates = [];\n {\n for (const attr of ["data-testid", "data-test-id", "data-test"]) {\n if (attr !== options.testIdAttributeName && element.getAttribute(attr))\n candidates.push({ engine: "css", selector: `[${attr}=${quoteCSSAttributeValue(element.getAttribute(attr))}]`, score: kOtherTestIdScore });\n }\n if (!options.noCSSId) {\n const idAttr = element.getAttribute("id");\n if (idAttr && !isGuidLike(idAttr))\n candidates.push({ engine: "css", selector: makeSelectorForId(idAttr), score: kCSSIdScore });\n }\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore });\n }\n if (element.nodeName === "IFRAME") {\n for (const attribute of ["name", "title"]) {\n if (element.getAttribute(attribute))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[${attribute}=${quoteCSSAttributeValue(element.getAttribute(attribute))}]`, score: kIframeByAttributeScore });\n }\n if (element.getAttribute(options.testIdAttributeName))\n candidates.push({ engine: "css", selector: `[${options.testIdAttributeName}=${quoteCSSAttributeValue(element.getAttribute(options.testIdAttributeName))}]`, score: kTestIdScore });\n penalizeScoreForLength([candidates]);\n return candidates;\n }\n if (element.getAttribute(options.testIdAttributeName))\n candidates.push({ engine: "internal:testid", selector: `[${options.testIdAttributeName}=${escapeForAttributeSelector(element.getAttribute(options.testIdAttributeName), true)}]`, score: kTestIdScore });\n if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") {\n const input = element;\n if (input.placeholder) {\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(input.placeholder, true)}]`, score: kPlaceholderScoreExact });\n for (const alternative of suitableTextAlternatives(input.placeholder))\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(alternative.text, false)}]`, score: kPlaceholderScore - alternative.scoreBonus });\n }\n }\n const labels = getElementLabels(injectedScript._evaluator._cacheText, element);\n for (const label of labels) {\n const labelText = label.normalized;\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(labelText, true), score: kLabelScoreExact });\n for (const alternative of suitableTextAlternatives(labelText))\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(alternative.text, false), score: kLabelScore - alternative.scoreBonus });\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole))\n candidates.push({ engine: "internal:role", selector: ariaRole, score: kRoleWithoutNameScore });\n if (element.getAttribute("name") && ["BUTTON", "FORM", "FIELDSET", "FRAME", "IFRAME", "INPUT", "KEYGEN", "OBJECT", "OUTPUT", "SELECT", "TEXTAREA", "MAP", "META", "PARAM"].includes(element.nodeName))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[name=${quoteCSSAttributeValue(element.getAttribute("name"))}]`, score: kCSSInputTypeNameScore });\n if (["INPUT", "TEXTAREA"].includes(element.nodeName) && element.getAttribute("type") !== "hidden") {\n if (element.getAttribute("type"))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[type=${quoteCSSAttributeValue(element.getAttribute("type"))}]`, score: kCSSInputTypeNameScore });\n }\n if (["INPUT", "TEXTAREA", "SELECT"].includes(element.nodeName) && element.getAttribute("type") !== "hidden")\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSInputTypeNameScore + 1 });\n penalizeScoreForLength([candidates]);\n return candidates;\n}\nfunction buildTextCandidates(injectedScript, element, isTargetNode) {\n if (element.nodeName === "SELECT")\n return [];\n const candidates = [];\n const title = element.getAttribute("title");\n if (title) {\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(title, true)}]`, score: kTitleScoreExact }]);\n for (const alternative of suitableTextAlternatives(title))\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(alternative.text, false)}]`, score: kTitleScore - alternative.scoreBonus }]);\n }\n const alt = element.getAttribute("alt");\n if (alt && ["APPLET", "AREA", "IMG", "INPUT"].includes(element.nodeName)) {\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alt, true)}]`, score: kAltTextScoreExact }]);\n for (const alternative of suitableTextAlternatives(alt))\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alternative.text, false)}]`, score: kAltTextScore - alternative.scoreBonus }]);\n }\n const text = elementText(injectedScript._evaluator._cacheText, element).normalized;\n const textAlternatives = text ? suitableTextAlternatives(text) : [];\n if (text) {\n if (isTargetNode) {\n if (text.length <= 80)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(text, true), score: kTextScoreExact }]);\n for (const alternative of textAlternatives)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n }\n const cssToken = { engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore };\n for (const alternative of textAlternatives)\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole)) {\n const ariaName = getElementAccessibleName(element, false);\n if (ariaName) {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}]`, score: kRoleWithNameScoreExact };\n candidates.push([roleToken]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus }]);\n } else {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}`, score: kRoleWithoutNameScore };\n for (const alternative of textAlternatives)\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n }\n penalizeScoreForLength(candidates);\n return candidates;\n}\nfunction makeSelectorForId(id) {\n return /^[a-zA-Z][a-zA-Z0-9\\-\\_]+$/.test(id) ? "#" + id : `[id=${quoteCSSAttributeValue(id)}]`;\n}\nfunction hasCSSIdToken(tokens) {\n return tokens.some((token) => token.engine === "css" && (token.selector.startsWith("#") || token.selector.startsWith(\'[id="\')));\n}\nfunction cssFallback(injectedScript, targetElement, options) {\n var _a;\n const root = (_a = options.root) != null ? _a : targetElement.ownerDocument;\n const tokens = [];\n function uniqueCSSSelector(prefix) {\n const path = tokens.slice();\n if (prefix)\n path.unshift(prefix);\n const selector = path.join(" > ");\n const parsedSelector = injectedScript.parseSelector(selector);\n const node = injectedScript.querySelector(parsedSelector, root, false);\n return node === targetElement ? selector : void 0;\n }\n function makeStrict(selector) {\n const token = { engine: "css", selector, score: kCSSFallbackScore };\n const parsedSelector = injectedScript.parseSelector(selector);\n const elements = injectedScript.querySelectorAll(parsedSelector, root);\n if (elements.length === 1)\n return [token];\n const nth = { engine: "nth", selector: String(elements.indexOf(targetElement)), score: kNthScore };\n return [token, nth];\n }\n for (let element = targetElement; element && element !== root; element = parentElementOrShadowHost(element)) {\n let bestTokenForLevel = "";\n if (element.id && !options.noCSSId) {\n const token = makeSelectorForId(element.id);\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n bestTokenForLevel = token;\n }\n const parent = element.parentNode;\n const classes = [...element.classList].map(escapeClassName);\n for (let i = 0; i < classes.length; ++i) {\n const token = "." + classes.slice(0, i + 1).join(".");\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel && parent) {\n const sameClassSiblings = parent.querySelectorAll(token);\n if (sameClassSiblings.length === 1)\n bestTokenForLevel = token;\n }\n }\n if (parent) {\n const siblings = [...parent.children];\n const nodeName = element.nodeName;\n const sameTagSiblings = siblings.filter((sibling) => sibling.nodeName === nodeName);\n const token = sameTagSiblings.indexOf(element) === 0 ? escapeNodeName(element) : `${escapeNodeName(element)}:nth-child(${1 + siblings.indexOf(element)})`;\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel)\n bestTokenForLevel = token;\n } else if (!bestTokenForLevel) {\n bestTokenForLevel = escapeNodeName(element);\n }\n tokens.unshift(bestTokenForLevel);\n }\n return makeStrict(uniqueCSSSelector());\n}\nfunction penalizeScoreForLength(groups) {\n for (const group of groups) {\n for (const token of group) {\n if (token.score > kBeginPenalizedScore && token.score < kEndPenalizedScore)\n token.score += Math.min(kTextScoreRange, token.selector.length / 10 | 0);\n }\n }\n}\nfunction joinTokens(tokens) {\n const parts = [];\n let lastEngine = "";\n for (const { engine, selector } of tokens) {\n if (parts.length && (lastEngine !== "css" || engine !== "css" || selector.startsWith(":nth-match(")))\n parts.push(">>");\n lastEngine = engine;\n if (engine === "css")\n parts.push(selector);\n else\n parts.push(`${engine}=${selector}`);\n }\n return parts.join(" ");\n}\nfunction combineScores(tokens) {\n let score = 0;\n for (let i = 0; i < tokens.length; i++)\n score += tokens[i].score * (tokens.length - i);\n return score;\n}\nfunction chooseFirstSelector(injectedScript, scope, targetElement, selectors, allowNthMatch) {\n const joined = selectors.map((tokens) => ({ tokens, score: combineScores(tokens) }));\n joined.sort((a, b) => a.score - b.score);\n let bestWithIndex = null;\n for (const { tokens } of joined) {\n const parsedSelector = injectedScript.parseSelector(joinTokens(tokens));\n const result = injectedScript.querySelectorAll(parsedSelector, scope);\n if (result[0] === targetElement && result.length === 1) {\n return tokens;\n }\n const index = result.indexOf(targetElement);\n if (!allowNthMatch || bestWithIndex || index === -1 || result.length > 5)\n continue;\n const nth = { engine: "nth", selector: String(index), score: kNthScore };\n bestWithIndex = [...tokens, nth];\n }\n return bestWithIndex;\n}\nfunction isGuidLike(id) {\n let lastCharacterType;\n let transitionCount = 0;\n for (let i = 0; i < id.length; ++i) {\n const c = id[i];\n let characterType;\n if (c === "-" || c === "_")\n continue;\n if (c >= "a" && c <= "z")\n characterType = "lower";\n else if (c >= "A" && c <= "Z")\n characterType = "upper";\n else if (c >= "0" && c <= "9")\n characterType = "digit";\n else\n characterType = "other";\n if (characterType === "lower" && lastCharacterType === "upper") {\n lastCharacterType = characterType;\n continue;\n }\n if (lastCharacterType && lastCharacterType !== characterType)\n ++transitionCount;\n lastCharacterType = characterType;\n }\n return transitionCount >= id.length / 4;\n}\nfunction trimWordBoundary(text, maxLength) {\n if (text.length <= maxLength)\n return text;\n text = text.substring(0, maxLength);\n const match = text.match(/^(.*)\\b(.+?)$/);\n if (!match)\n return "";\n return match[1].trimEnd();\n}\nfunction suitableTextAlternatives(text) {\n let result = [];\n {\n const match = text.match(/^([\\d.,]+)[^.,\\w]/);\n const leadingNumberLength = match ? match[1].length : 0;\n if (leadingNumberLength) {\n const alt = trimWordBoundary(text.substring(leadingNumberLength).trimStart(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n {\n const match = text.match(/[^.,\\w]([\\d.,]+)$/);\n const trailingNumberLength = match ? match[1].length : 0;\n if (trailingNumberLength) {\n const alt = trimWordBoundary(text.substring(0, text.length - trailingNumberLength).trimEnd(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n if (text.length <= 30) {\n result.push({ text, scoreBonus: 0 });\n } else {\n result.push({ text: trimWordBoundary(text, 80), scoreBonus: 0 });\n result.push({ text: trimWordBoundary(text, 30), scoreBonus: 1 });\n }\n result = result.filter((r) => r.text);\n if (!result.length)\n result.push({ text: text.substring(0, 80), scoreBonus: 0 });\n return result;\n}\nfunction escapeNodeName(node) {\n return node.nodeName.toLocaleLowerCase().replace(/[:\\.]/g, (char) => "\\\\" + char);\n}\nfunction escapeClassName(className) {\n let result = "";\n for (let i = 0; i < className.length; i++)\n result += cssEscapeCharacter(className, i);\n return result;\n}\nfunction cssEscapeCharacter(s, i) {\n const c = s.charCodeAt(i);\n if (c === 0)\n return "\\uFFFD";\n if (c >= 1 && c <= 31 || c >= 48 && c <= 57 && (i === 0 || i === 1 && s.charCodeAt(0) === 45))\n return "\\\\" + c.toString(16) + " ";\n if (i === 0 && c === 45 && s.length === 1)\n return "\\\\" + s.charAt(i);\n if (c >= 128 || c === 45 || c === 95 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122)\n return s.charAt(i);\n return "\\\\" + s.charAt(i);\n}\n\n// packages/injected/src/vueSelectorEngine.ts\nfunction basename(filename, ext) {\n const normalized = filename.replace(/^[a-zA-Z]:/, "").replace(/\\\\/g, "/");\n let result = normalized.substring(normalized.lastIndexOf("/") + 1);\n if (ext && result.endsWith(ext))\n result = result.substring(0, result.length - ext.length);\n return result;\n}\nfunction toUpper(_, c) {\n return c ? c.toUpperCase() : "";\n}\nvar classifyRE = /(?:^|[-_/])(\\w)/g;\nvar classify = (str) => {\n return str && str.replace(classifyRE, toUpper);\n};\nfunction buildComponentsTreeVue3(instance) {\n function getComponentTypeName(options) {\n const name = options.name || options._componentTag || options.__playwright_guessedName;\n if (name)\n return name;\n const file = options.__file;\n if (file)\n return classify(basename(file, ".vue"));\n }\n function saveComponentName(instance2, key) {\n instance2.type.__playwright_guessedName = key;\n return key;\n }\n function getInstanceName(instance2) {\n var _a, _b, _c, _d;\n const name = getComponentTypeName(instance2.type || {});\n if (name)\n return name;\n if (instance2.root === instance2)\n return "Root";\n for (const key in (_b = (_a = instance2.parent) == null ? void 0 : _a.type) == null ? void 0 : _b.components) {\n if (((_c = instance2.parent) == null ? void 0 : _c.type.components[key]) === instance2.type)\n return saveComponentName(instance2, key);\n }\n for (const key in (_d = instance2.appContext) == null ? void 0 : _d.components) {\n if (instance2.appContext.components[key] === instance2.type)\n return saveComponentName(instance2, key);\n }\n return "Anonymous Component";\n }\n function isBeingDestroyed(instance2) {\n return instance2._isBeingDestroyed || instance2.isUnmounted;\n }\n function isFragment(instance2) {\n return instance2.subTree.type.toString() === "Symbol(Fragment)";\n }\n function getInternalInstanceChildren(subTree) {\n const list = [];\n if (subTree.component)\n list.push(subTree.component);\n if (subTree.suspense)\n list.push(...getInternalInstanceChildren(subTree.suspense.activeBranch));\n if (Array.isArray(subTree.children)) {\n subTree.children.forEach((childSubTree) => {\n if (childSubTree.component)\n list.push(childSubTree.component);\n else\n list.push(...getInternalInstanceChildren(childSubTree));\n });\n }\n return list.filter((child) => {\n var _a;\n return !isBeingDestroyed(child) && !((_a = child.type.devtools) == null ? void 0 : _a.hide);\n });\n }\n function getRootElementsFromComponentInstance(instance2) {\n if (isFragment(instance2))\n return getFragmentRootElements(instance2.subTree);\n return [instance2.subTree.el];\n }\n function getFragmentRootElements(vnode) {\n if (!vnode.children)\n return [];\n const list = [];\n for (let i = 0, l = vnode.children.length; i < l; i++) {\n const childVnode = vnode.children[i];\n if (childVnode.component)\n list.push(...getRootElementsFromComponentInstance(childVnode.component));\n else if (childVnode.el)\n list.push(childVnode.el);\n }\n return list;\n }\n function buildComponentsTree2(instance2) {\n return {\n name: getInstanceName(instance2),\n children: getInternalInstanceChildren(instance2.subTree).map(buildComponentsTree2),\n rootElements: getRootElementsFromComponentInstance(instance2),\n props: instance2.props\n };\n }\n return buildComponentsTree2(instance);\n}\nfunction buildComponentsTreeVue2(instance) {\n function getComponentName2(options) {\n const name = options.displayName || options.name || options._componentTag;\n if (name)\n return name;\n const file = options.__file;\n if (file)\n return classify(basename(file, ".vue"));\n }\n function getInstanceName(instance2) {\n const name = getComponentName2(instance2.$options || instance2.fnOptions || {});\n if (name)\n return name;\n return instance2.$root === instance2 ? "Root" : "Anonymous Component";\n }\n function getInternalInstanceChildren(instance2) {\n if (instance2.$children)\n return instance2.$children;\n if (Array.isArray(instance2.subTree.children))\n return instance2.subTree.children.filter((vnode) => !!vnode.component).map((vnode) => vnode.component);\n return [];\n }\n function buildComponentsTree2(instance2) {\n return {\n name: getInstanceName(instance2),\n children: getInternalInstanceChildren(instance2).map(buildComponentsTree2),\n rootElements: [instance2.$el],\n props: instance2._props\n };\n }\n return buildComponentsTree2(instance);\n}\nfunction filterComponentsTree2(treeNode, searchFn, result = []) {\n if (searchFn(treeNode))\n result.push(treeNode);\n for (const child of treeNode.children)\n filterComponentsTree2(child, searchFn, result);\n return result;\n}\nfunction findVueRoots(root, roots = []) {\n const document = root.ownerDocument || root;\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);\n const vue2Roots = /* @__PURE__ */ new Set();\n do {\n const node = walker.currentNode;\n if (node.__vue__)\n vue2Roots.add(node.__vue__.$root);\n if (node.__vue_app__ && node._vnode && node._vnode.component)\n roots.push({ root: node._vnode.component, version: 3 });\n const shadowRoot = node instanceof Element ? node.shadowRoot : null;\n if (shadowRoot)\n findVueRoots(shadowRoot, roots);\n } while (walker.nextNode());\n for (const vue2root of vue2Roots) {\n roots.push({\n version: 2,\n root: vue2root\n });\n }\n return roots;\n}\nvar createVueEngine = () => ({\n queryAll(scope, selector) {\n const document = scope.ownerDocument || scope;\n const { name, attributes } = parseAttributeSelector(selector, false);\n const vueRoots = findVueRoots(document);\n const trees = vueRoots.map((vueRoot) => vueRoot.version === 3 ? buildComponentsTreeVue3(vueRoot.root) : buildComponentsTreeVue2(vueRoot.root));\n const treeNodes = trees.map((tree) => filterComponentsTree2(tree, (treeNode) => {\n if (name && treeNode.name !== name)\n return false;\n if (treeNode.rootElements.some((rootElement) => !isInsideScope(scope, rootElement)))\n return false;\n for (const attr of attributes) {\n if (!matchesComponentAttribute(treeNode.props, attr))\n return false;\n }\n return true;\n })).flat();\n const allRootElements = /* @__PURE__ */ new Set();\n for (const treeNode of treeNodes) {\n for (const rootElement of treeNode.rootElements)\n allRootElements.add(rootElement);\n }\n return [...allRootElements];\n }\n});\n\n// packages/injected/src/xpathSelectorEngine.ts\nvar XPathEngine = {\n queryAll(root, selector) {\n if (selector.startsWith("/") && root.nodeType !== Node.DOCUMENT_NODE)\n selector = "." + selector;\n const result = [];\n const document = root.ownerDocument || root;\n if (!document)\n return result;\n const it = document.evaluate(selector, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);\n for (let node = it.iterateNext(); node; node = it.iterateNext()) {\n if (node.nodeType === Node.ELEMENT_NODE)\n result.push(node);\n }\n return result;\n }\n};\n\n// packages/playwright-core/src/utils/isomorphic/locatorUtils.ts\nfunction getByAttributeTextSelector(attrName, text, options) {\n return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, (options == null ? void 0 : options.exact) || false)}]`;\n}\nfunction getByTestIdSelector(testIdAttributeName, testId) {\n return `internal:testid=[${testIdAttributeName}=${escapeForAttributeSelector(testId, true)}]`;\n}\nfunction getByLabelSelector(text, options) {\n return "internal:label=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByAltTextSelector(text, options) {\n return getByAttributeTextSelector("alt", text, options);\n}\nfunction getByTitleSelector(text, options) {\n return getByAttributeTextSelector("title", text, options);\n}\nfunction getByPlaceholderSelector(text, options) {\n return getByAttributeTextSelector("placeholder", text, options);\n}\nfunction getByTextSelector(text, options) {\n return "internal:text=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByRoleSelector(role, options = {}) {\n const props = [];\n if (options.checked !== void 0)\n props.push(["checked", String(options.checked)]);\n if (options.disabled !== void 0)\n props.push(["disabled", String(options.disabled)]);\n if (options.selected !== void 0)\n props.push(["selected", String(options.selected)]);\n if (options.expanded !== void 0)\n props.push(["expanded", String(options.expanded)]);\n if (options.includeHidden !== void 0)\n props.push(["include-hidden", String(options.includeHidden)]);\n if (options.level !== void 0)\n props.push(["level", String(options.level)]);\n if (options.name !== void 0)\n props.push(["name", escapeForAttributeSelector(options.name, !!options.exact)]);\n if (options.pressed !== void 0)\n props.push(["pressed", String(options.pressed)]);\n return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`;\n}\n\n// packages/injected/src/consoleApi.ts\nvar selectorSymbol = Symbol("selector");\nselectorSymbol;\nvar _Locator = class _Locator {\n constructor(injectedScript, selector, options) {\n if (options == null ? void 0 : options.hasText)\n selector += ` >> internal:has-text=${escapeForTextSelector(options.hasText, false)}`;\n if (options == null ? void 0 : options.hasNotText)\n selector += ` >> internal:has-not-text=${escapeForTextSelector(options.hasNotText, false)}`;\n if (options == null ? void 0 : options.has)\n selector += ` >> internal:has=` + JSON.stringify(options.has[selectorSymbol]);\n if (options == null ? void 0 : options.hasNot)\n selector += ` >> internal:has-not=` + JSON.stringify(options.hasNot[selectorSymbol]);\n if ((options == null ? void 0 : options.visible) !== void 0)\n selector += ` >> visible=${options.visible ? "true" : "false"}`;\n this[selectorSymbol] = selector;\n if (selector) {\n const parsed = injectedScript.parseSelector(selector);\n this.element = injectedScript.querySelector(parsed, injectedScript.document, false);\n this.elements = injectedScript.querySelectorAll(parsed, injectedScript.document);\n }\n const selectorBase = selector;\n const self = this;\n self.locator = (selector2, options2) => {\n return new _Locator(injectedScript, selectorBase ? selectorBase + " >> " + selector2 : selector2, options2);\n };\n self.getByTestId = (testId) => self.locator(getByTestIdSelector(injectedScript.testIdAttributeNameForStrictErrorAndConsoleCodegen(), testId));\n self.getByAltText = (text, options2) => self.locator(getByAltTextSelector(text, options2));\n self.getByLabel = (text, options2) => self.locator(getByLabelSelector(text, options2));\n self.getByPlaceholder = (text, options2) => self.locator(getByPlaceholderSelector(text, options2));\n self.getByText = (text, options2) => self.locator(getByTextSelector(text, options2));\n self.getByTitle = (text, options2) => self.locator(getByTitleSelector(text, options2));\n self.getByRole = (role, options2 = {}) => self.locator(getByRoleSelector(role, options2));\n self.filter = (options2) => new _Locator(injectedScript, selector, options2);\n self.first = () => self.locator("nth=0");\n self.last = () => self.locator("nth=-1");\n self.nth = (index) => self.locator(`nth=${index}`);\n self.and = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:and=` + JSON.stringify(locator[selectorSymbol]));\n self.or = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:or=` + JSON.stringify(locator[selectorSymbol]));\n }\n};\nvar Locator = _Locator;\nvar ConsoleAPI = class {\n constructor(injectedScript) {\n this._injectedScript = injectedScript;\n }\n install() {\n if (this._injectedScript.window.playwright)\n return;\n this._injectedScript.window.playwright = {\n $: (selector, strict) => this._querySelector(selector, !!strict),\n $$: (selector) => this._querySelectorAll(selector),\n inspect: (selector) => this._inspect(selector),\n selector: (element) => this._selector(element),\n generateLocator: (element, language) => this._generateLocator(element, language),\n ariaSnapshot: (element, options) => {\n return this._injectedScript.ariaSnapshot(element || this._injectedScript.document.body, options);\n },\n resume: () => this._resume(),\n ...new Locator(this._injectedScript, "")\n };\n delete this._injectedScript.window.playwright.filter;\n delete this._injectedScript.window.playwright.first;\n delete this._injectedScript.window.playwright.last;\n delete this._injectedScript.window.playwright.nth;\n delete this._injectedScript.window.playwright.and;\n delete this._injectedScript.window.playwright.or;\n }\n _querySelector(selector, strict) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.query(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelector(parsed, this._injectedScript.document, strict);\n }\n _querySelectorAll(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.$$(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelectorAll(parsed, this._injectedScript.document);\n }\n _inspect(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.inspect(\'Playwright >> selector\').`);\n this._injectedScript.window.inspect(this._querySelector(selector, false));\n }\n _selector(element) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.selector(element).`);\n return this._injectedScript.generateSelectorSimple(element);\n }\n _generateLocator(element, language) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.locator(element).`);\n const selector = this._injectedScript.generateSelectorSimple(element);\n return asLocator(language || "javascript", selector);\n }\n _resume() {\n this._injectedScript.window.__pw_resume().catch(() => {\n });\n }\n};\n\n// packages/playwright-core/src/utils/isomorphic/utilityScriptSerializers.ts\nfunction isRegExp2(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0 });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp2(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n // eslint-disable-next-line no-restricted-globals\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n return returnByValue ? this._promiseAwareJsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _promiseAwareJsonValueNoThrow(value) {\n const safeJson = (value2) => {\n try {\n return this.jsonValue(true, value2);\n } catch (e) {\n return void 0;\n }\n };\n if (value && typeof value === "object" && typeof value.then === "function") {\n return (async () => {\n const promiseValue = await value;\n return safeJson(promiseValue);\n })();\n }\n return safeJson(value);\n }\n};\n\n// packages/injected/src/injectedScript.ts\nvar InjectedScript = class {\n // eslint-disable-next-line no-restricted-globals\n constructor(window, options) {\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = "data-testid";\n // Recorder must use any external dependencies through InjectedScript.\n // Otherwise it will end up with a copy of all modules it uses, and any\n // module-level globals will be duplicated, which leads to subtle bugs.\n this.utils = {\n asLocator,\n cacheNormalizedWhitespaces,\n elementText,\n getAriaRole,\n getElementAccessibleDescription,\n getElementAccessibleName,\n isElementVisible,\n isInsideScope,\n normalizeWhiteSpace,\n parseAriaSnapshot,\n // Builtins protect injected code from clock emulation.\n builtins: null\n };\n this.window = window;\n this.document = window.document;\n this.isUnderTest = options.isUnderTest;\n this.utils.builtins = new UtilityScript(window, options.isUnderTest).builtins;\n this._sdkLanguage = options.sdkLanguage;\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = options.testIdAttributeName;\n this._evaluator = new SelectorEvaluatorImpl();\n this.consoleApi = new ConsoleAPI(this);\n this.onGlobalListenersRemoved = /* @__PURE__ */ new Set();\n this._autoClosingTags = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]);\n this._booleanAttributes = /* @__PURE__ */ new Set(["checked", "selected", "disabled", "readonly", "multiple"]);\n this._eventTypes = /* @__PURE__ */ new Map([\n ["auxclick", "mouse"],\n ["click", "mouse"],\n ["dblclick", "mouse"],\n ["mousedown", "mouse"],\n ["mouseeenter", "mouse"],\n ["mouseleave", "mouse"],\n ["mousemove", "mouse"],\n ["mouseout", "mouse"],\n ["mouseover", "mouse"],\n ["mouseup", "mouse"],\n ["mouseleave", "mouse"],\n ["mousewheel", "mouse"],\n ["keydown", "keyboard"],\n ["keyup", "keyboard"],\n ["keypress", "keyboard"],\n ["textInput", "keyboard"],\n ["touchstart", "touch"],\n ["touchmove", "touch"],\n ["touchend", "touch"],\n ["touchcancel", "touch"],\n ["pointerover", "pointer"],\n ["pointerout", "pointer"],\n ["pointerenter", "pointer"],\n ["pointerleave", "pointer"],\n ["pointerdown", "pointer"],\n ["pointerup", "pointer"],\n ["pointermove", "pointer"],\n ["pointercancel", "pointer"],\n ["gotpointercapture", "pointer"],\n ["lostpointercapture", "pointer"],\n ["focus", "focus"],\n ["blur", "focus"],\n ["drag", "drag"],\n ["dragstart", "drag"],\n ["dragend", "drag"],\n ["dragover", "drag"],\n ["dragenter", "drag"],\n ["dragleave", "drag"],\n ["dragexit", "drag"],\n ["drop", "drag"],\n ["wheel", "wheel"],\n ["deviceorientation", "deviceorientation"],\n ["deviceorientationabsolute", "deviceorientation"],\n ["devicemotion", "devicemotion"]\n ]);\n this._hoverHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousemove"]);\n this._tapHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["pointerdown", "pointerup", "touchstart", "touchend", "touchcancel"]);\n this._mouseHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousedown", "mouseup", "pointerdown", "pointerup", "click", "auxclick", "dblclick", "contextmenu"]);\n this._allHitTargetInterceptorEvents = /* @__PURE__ */ new Set([...this._hoverHitTargetInterceptorEvents, ...this._tapHitTargetInterceptorEvents, ...this._mouseHitTargetInterceptorEvents]);\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("xpath", XPathEngine);\n this._engines.set("xpath:light", XPathEngine);\n this._engines.set("_react", createReactEngine());\n this._engines.set("_vue", createVueEngine());\n this._engines.set("role", createRoleEngine(false));\n this._engines.set("text", this._createTextEngine(true, false));\n this._engines.set("text:light", this._createTextEngine(false, false));\n this._engines.set("id", this._createAttributeEngine("id", true));\n this._engines.set("id:light", this._createAttributeEngine("id", false));\n this._engines.set("data-testid", this._createAttributeEngine("data-testid", true));\n this._engines.set("data-testid:light", this._createAttributeEngine("data-testid", false));\n this._engines.set("data-test-id", this._createAttributeEngine("data-test-id", true));\n this._engines.set("data-test-id:light", this._createAttributeEngine("data-test-id", false));\n this._engines.set("data-test", this._createAttributeEngine("data-test", true));\n this._engines.set("data-test:light", this._createAttributeEngine("data-test", false));\n this._engines.set("css", this._createCSSEngine());\n this._engines.set("nth", { queryAll: () => [] });\n this._engines.set("visible", this._createVisibleEngine());\n this._engines.set("internal:control", this._createControlEngine());\n this._engines.set("internal:has", this._createHasEngine());\n this._engines.set("internal:has-not", this._createHasNotEngine());\n this._engines.set("internal:and", { queryAll: () => [] });\n this._engines.set("internal:or", { queryAll: () => [] });\n this._engines.set("internal:chain", this._createInternalChainEngine());\n this._engines.set("internal:label", this._createInternalLabelEngine());\n this._engines.set("internal:text", this._createTextEngine(true, true));\n this._engines.set("internal:has-text", this._createInternalHasTextEngine());\n this._engines.set("internal:has-not-text", this._createInternalHasNotTextEngine());\n this._engines.set("internal:attr", this._createNamedAttributeEngine());\n this._engines.set("internal:testid", this._createNamedAttributeEngine());\n this._engines.set("internal:role", createRoleEngine(true));\n this._engines.set("internal:describe", this._createDescribeEngine());\n this._engines.set("aria-ref", this._createAriaRefEngine());\n for (const { name, source } of options.customEngines)\n this._engines.set(name, this.eval(source));\n this._stableRafCount = options.stableRafCount;\n this._browserName = options.browserName;\n setGlobalOptions({ browserNameForWorkarounds: options.browserName, inputFileRoleTextbox: options.inputFileRoleTextbox });\n this._setupGlobalListenersRemovalDetection();\n this._setupHitTargetInterceptors();\n if (this.isUnderTest)\n this.window.__injectedScript = this;\n }\n eval(expression) {\n return this.window.eval(expression);\n }\n testIdAttributeNameForStrictErrorAndConsoleCodegen() {\n return this._testIdAttributeNameForStrictErrorAndConsoleCodegen;\n }\n parseSelector(selector) {\n const result = parseSelector(selector);\n visitAllSelectorParts(result, (part) => {\n if (!this._engines.has(part.name))\n throw this.createStacklessError(`Unknown engine "${part.name}" while parsing selector ${selector}`);\n });\n return result;\n }\n generateSelector(targetElement, options) {\n return generateSelector(this, targetElement, options);\n }\n generateSelectorSimple(targetElement, options) {\n return generateSelector(this, targetElement, { ...options, testIdAttributeName: this._testIdAttributeNameForStrictErrorAndConsoleCodegen }).selector;\n }\n querySelector(selector, root, strict) {\n const result = this.querySelectorAll(selector, root);\n if (strict && result.length > 1)\n throw this.strictModeViolationError(selector, result);\n return result[0];\n }\n _queryNth(elements, part) {\n const list = [...elements];\n let nth = +part.body;\n if (nth === -1)\n nth = list.length - 1;\n return new Set(list.slice(nth, nth + 1));\n }\n _queryLayoutSelector(elements, part, originalRoot) {\n const name = part.name;\n const body = part.body;\n const result = [];\n const inner = this.querySelectorAll(body.parsed, originalRoot);\n for (const element of elements) {\n const score = layoutSelectorScore(name, element, inner, body.distance);\n if (score !== void 0)\n result.push({ element, score });\n }\n result.sort((a, b) => a.score - b.score);\n return new Set(result.map((r) => r.element));\n }\n ariaSnapshot(node, options) {\n if (node.nodeType !== Node.ELEMENT_NODE)\n throw this.createStacklessError("Can only capture aria snapshot of Element nodes.");\n this._lastAriaSnapshot = generateAriaTree(node, options);\n return renderAriaTree(this._lastAriaSnapshot, options);\n }\n getAllByAria(document, template) {\n return getAllByAria(document.documentElement, template);\n }\n querySelectorAll(selector, root) {\n if (selector.capture !== void 0) {\n if (selector.parts.some((part) => part.name === "nth"))\n throw this.createStacklessError(`Can\'t query n-th element in a request with the capture.`);\n const withHas = { parts: selector.parts.slice(0, selector.capture + 1) };\n if (selector.capture < selector.parts.length - 1) {\n const parsed = { parts: selector.parts.slice(selector.capture + 1) };\n const has = { name: "internal:has", body: { parsed }, source: stringifySelector(parsed) };\n withHas.parts.push(has);\n }\n return this.querySelectorAll(withHas, root);\n }\n if (!root["querySelectorAll"])\n throw this.createStacklessError("Node is not queryable.");\n if (selector.capture !== void 0) {\n throw this.createStacklessError("Internal error: there should not be a capture in the selector.");\n }\n if (root.nodeType === 11 && selector.parts.length === 1 && selector.parts[0].name === "css" && selector.parts[0].source === ":scope")\n return [root];\n this._evaluator.begin();\n try {\n let roots = /* @__PURE__ */ new Set([root]);\n for (const part of selector.parts) {\n if (part.name === "nth") {\n roots = this._queryNth(roots, part);\n } else if (part.name === "internal:and") {\n const andElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(andElements.filter((e) => roots.has(e)));\n } else if (part.name === "internal:or") {\n const orElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(sortInDOMOrder(/* @__PURE__ */ new Set([...roots, ...orElements])));\n } else if (kLayoutSelectorNames.includes(part.name)) {\n roots = this._queryLayoutSelector(roots, part, root);\n } else {\n const next = /* @__PURE__ */ new Set();\n for (const root2 of roots) {\n const all = this._queryEngineAll(part, root2);\n for (const one of all)\n next.add(one);\n }\n roots = next;\n }\n }\n return [...roots];\n } finally {\n this._evaluator.end();\n }\n }\n _queryEngineAll(part, root) {\n const result = this._engines.get(part.name).queryAll(root, part.body);\n for (const element of result) {\n if (!("nodeName" in element))\n throw this.createStacklessError(`Expected a Node but got ${Object.prototype.toString.call(element)}`);\n }\n return result;\n }\n _createAttributeEngine(attribute, shadow) {\n const toCSS = (selector) => {\n const css = `[${attribute}=${JSON.stringify(selector)}]`;\n return [{ simples: [{ selector: { css, functions: [] }, combinator: "" }] }];\n };\n return {\n queryAll: (root, selector) => {\n return this._evaluator.query({ scope: root, pierceShadow: shadow }, toCSS(selector));\n }\n };\n }\n _createCSSEngine() {\n return {\n queryAll: (root, body) => {\n return this._evaluator.query({ scope: root, pierceShadow: true }, body);\n }\n };\n }\n _createTextEngine(shadow, internal) {\n const queryAll = (root, selector) => {\n const { matcher, kind } = createTextMatcher(selector, internal);\n const result = [];\n let lastDidNotMatchSelf = null;\n const appendElement = (element) => {\n if (kind === "lax" && lastDidNotMatchSelf && lastDidNotMatchSelf.contains(element))\n return false;\n const matches = elementMatchesText(this._evaluator._cacheText, element, matcher);\n if (matches === "none")\n lastDidNotMatchSelf = element;\n if (matches === "self" || matches === "selfAndChildren" && kind === "strict" && !internal)\n result.push(element);\n };\n if (root.nodeType === Node.ELEMENT_NODE)\n appendElement(root);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: shadow }, "*");\n for (const element of elements)\n appendElement(element);\n return result;\n };\n return { queryAll };\n }\n _createInternalHasTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [element] : [];\n }\n };\n }\n _createInternalHasNotTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [] : [element];\n }\n };\n }\n _createInternalLabelEngine() {\n return {\n queryAll: (root, selector) => {\n const { matcher } = createTextMatcher(selector, true);\n const allElements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, "*");\n return allElements.filter((element) => {\n return getElementLabels(this._evaluator._cacheText, element).some((label) => matcher(label));\n });\n }\n };\n }\n _createNamedAttributeEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed attribute selector: " + selector);\n const { name, value, caseSensitive } = parsed.attributes[0];\n const lowerCaseValue = caseSensitive ? null : value.toLowerCase();\n let matcher;\n if (value instanceof RegExp)\n matcher = (s) => !!s.match(value);\n else if (caseSensitive)\n matcher = (s) => s === value;\n else\n matcher = (s) => s.toLowerCase().includes(lowerCaseValue);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, `[${name}]`);\n return elements.filter((e) => matcher(e.getAttribute(name)));\n };\n return { queryAll };\n }\n _createDescribeEngine() {\n const queryAll = (root) => {\n if (root.nodeType !== 1)\n return [];\n return [root];\n };\n return { queryAll };\n }\n _createControlEngine() {\n return {\n queryAll(root, body) {\n if (body === "enter-frame")\n return [];\n if (body === "return-empty")\n return [];\n if (body === "component") {\n if (root.nodeType !== 1)\n return [];\n return [root.childElementCount === 1 ? root.firstElementChild : root];\n }\n throw new Error(`Internal error, unknown internal:control selector ${body}`);\n }\n };\n }\n _createHasEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [root] : [];\n };\n return { queryAll };\n }\n _createHasNotEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [] : [root];\n };\n return { queryAll };\n }\n _createVisibleEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const visible = body === "true";\n return isElementVisible(root) === visible ? [root] : [];\n };\n return { queryAll };\n }\n _createInternalChainEngine() {\n const queryAll = (root, body) => {\n return this.querySelectorAll(body.parsed, root);\n };\n return { queryAll };\n }\n extend(source, params) {\n const constrFunction = this.window.eval(`\n (() => {\n const module = {};\n ${source}\n return module.exports.default();\n })()`);\n return new constrFunction(this, params);\n }\n async viewportRatio(element) {\n return await new Promise((resolve) => {\n const observer = new IntersectionObserver((entries) => {\n resolve(entries[0].intersectionRatio);\n observer.disconnect();\n });\n observer.observe(element);\n this.utils.builtins.requestAnimationFrame(() => {\n });\n });\n }\n getElementBorderWidth(node) {\n if (node.nodeType !== Node.ELEMENT_NODE || !node.ownerDocument || !node.ownerDocument.defaultView)\n return { left: 0, top: 0 };\n const style = node.ownerDocument.defaultView.getComputedStyle(node);\n return { left: parseInt(style.borderLeftWidth || "", 10), top: parseInt(style.borderTopWidth || "", 10) };\n }\n describeIFrameStyle(iframe) {\n if (!iframe.ownerDocument || !iframe.ownerDocument.defaultView)\n return "error:notconnected";\n const defaultView = iframe.ownerDocument.defaultView;\n for (let e = iframe; e; e = parentElementOrShadowHost(e)) {\n if (defaultView.getComputedStyle(e).transform !== "none")\n return "transformed";\n }\n const iframeStyle = defaultView.getComputedStyle(iframe);\n return {\n left: parseInt(iframeStyle.borderLeftWidth || "", 10) + parseInt(iframeStyle.paddingLeft || "", 10),\n top: parseInt(iframeStyle.borderTopWidth || "", 10) + parseInt(iframeStyle.paddingTop || "", 10)\n };\n }\n retarget(node, behavior) {\n let element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;\n if (!element)\n return null;\n if (behavior === "none")\n return element;\n if (!element.matches("input, textarea, select") && !element.isContentEditable) {\n if (behavior === "button-link")\n element = element.closest("button, [role=button], a, [role=link]") || element;\n else\n element = element.closest("button, [role=button], [role=checkbox], [role=radio]") || element;\n }\n if (behavior === "follow-label") {\n if (!element.matches("a, input, textarea, button, select, [role=link], [role=button], [role=checkbox], [role=radio]") && !element.isContentEditable) {\n const enclosingLabel = element.closest("label");\n if (enclosingLabel && enclosingLabel.control)\n element = enclosingLabel.control;\n }\n }\n return element;\n }\n async checkElementStates(node, states) {\n if (states.includes("stable")) {\n const stableResult = await this._checkElementIsStable(node);\n if (stableResult === false)\n return { missingState: "stable" };\n if (stableResult === "error:notconnected")\n return "error:notconnected";\n }\n for (const state of states) {\n if (state !== "stable") {\n const result = this.elementState(node, state);\n if (result.received === "error:notconnected")\n return "error:notconnected";\n if (!result.matches)\n return { missingState: state };\n }\n }\n }\n async _checkElementIsStable(node) {\n const continuePolling = Symbol("continuePolling");\n let lastRect;\n let stableRafCounter = 0;\n let lastTime = 0;\n const check = () => {\n const element = this.retarget(node, "no-follow-label");\n if (!element)\n return "error:notconnected";\n const time = this.utils.builtins.performance.now();\n if (this._stableRafCount > 1 && time - lastTime < 15)\n return continuePolling;\n lastTime = time;\n const clientRect = element.getBoundingClientRect();\n const rect = { x: clientRect.top, y: clientRect.left, width: clientRect.width, height: clientRect.height };\n if (lastRect) {\n const samePosition = rect.x === lastRect.x && rect.y === lastRect.y && rect.width === lastRect.width && rect.height === lastRect.height;\n if (!samePosition)\n return false;\n if (++stableRafCounter >= this._stableRafCount)\n return true;\n }\n lastRect = rect;\n return continuePolling;\n };\n let fulfill;\n let reject;\n const result = new Promise((f, r) => {\n fulfill = f;\n reject = r;\n });\n const raf = () => {\n try {\n const success = check();\n if (success !== continuePolling)\n fulfill(success);\n else\n this.utils.builtins.requestAnimationFrame(raf);\n } catch (e) {\n reject(e);\n }\n };\n this.utils.builtins.requestAnimationFrame(raf);\n return result;\n }\n _createAriaRefEngine() {\n const queryAll = (root, selector) => {\n var _a, _b;\n const result = (_b = (_a = this._lastAriaSnapshot) == null ? void 0 : _a.elements) == null ? void 0 : _b.get(selector);\n return result && result.isConnected ? [result] : [];\n };\n return { queryAll };\n }\n elementState(node, state) {\n const element = this.retarget(node, ["visible", "hidden"].includes(state) ? "none" : "follow-label");\n if (!element || !element.isConnected) {\n if (state === "hidden")\n return { matches: true, received: "hidden" };\n return { matches: false, received: "error:notconnected" };\n }\n if (state === "visible" || state === "hidden") {\n const visible = isElementVisible(element);\n return {\n matches: state === "visible" ? visible : !visible,\n received: visible ? "visible" : "hidden"\n };\n }\n if (state === "disabled" || state === "enabled") {\n const disabled = getAriaDisabled(element);\n return {\n matches: state === "disabled" ? disabled : !disabled,\n received: disabled ? "disabled" : "enabled"\n };\n }\n if (state === "editable") {\n const disabled = getAriaDisabled(element);\n const readonly = getReadonly(element);\n if (readonly === "error")\n throw this.createStacklessError("Element is not an
"); + if ((internalTLS == null ? void 0 : internalTLS.alpnProtocol) === "h2") { + if ("performServerHandshake" in http) { + this.target.removeListener("close", this._targetCloseEventListener); + const session = http.performServerHandshake(internalTLS); + session.on("error", () => { + this.target.destroy(); + this._targetCloseEventListener(); + }); + session.once("stream", (stream2) => { + stream2.respond({ + "content-type": "text/html", + [http.constants.HTTP2_HEADER_STATUS]: 503 + }); + const cleanup = () => { + session.close(); + this.target.destroy(); + this._targetCloseEventListener(); + }; + stream2.end(responseBody, cleanup); + stream2.once("error", cleanup); + }); + } else { + this.target.destroy(); + } + } else { + internalTLS.end([ + "HTTP/1.1 503 Internal Server Error", + "Content-Type: text/html; charset=utf-8", + "Content-Length: " + Buffer.byteLength(responseBody), + "", + responseBody + ].join("\r\n")); + this.target.destroy(); + } + }; + if (this._closed) { + internalTLS.destroy(); + return; + } + targetTLS = tls.connect({ + socket: this.target, + host: this.host, + port: this.port, + rejectUnauthorized: !this.socksProxy.ignoreHTTPSErrors, + ALPNProtocols: [internalTLS.alpnProtocol || "http/1.1"], + servername: !net.isIP(this.host) ? this.host : void 0, + secureContext: this.socksProxy.secureContextMap.get(new URL(`https://${this.host}:${this.port}`).origin) + }); + targetTLS.once("secureConnect", () => { + internalTLS.pipe(targetTLS); + targetTLS.pipe(internalTLS); + }); + internalTLS.once("error", () => this.target.destroy()); + targetTLS.once("error", handleError); + }); + }); + } +} +class ClientCertificatesProxy { + constructor(contextOptions) { + this._connections = /* @__PURE__ */ new Map(); + this.secureContextMap = /* @__PURE__ */ new Map(); + verifyClientCertificates(contextOptions.clientCertificates); + this.alpnCache = new ALPNCache(); + this.ignoreHTTPSErrors = contextOptions.ignoreHTTPSErrors; + this.proxyAgentFromOptions = createProxyAgent(contextOptions.proxy); + this._initSecureContexts(contextOptions.clientCertificates); + this._socksProxy = new SocksProxy(); + this._socksProxy.setPattern("*"); + this._socksProxy.addListener(SocksProxy.Events.SocksRequested, async (payload) => { + try { + const connection = new SocksProxyConnection(this, payload.uid, payload.host, payload.port); + await connection.connect(); + this._connections.set(payload.uid, connection); + } catch (error2) { + this._socksProxy.socketFailed({ uid: payload.uid, errorCode: error2.code }); + } + }); + this._socksProxy.addListener(SocksProxy.Events.SocksData, async (payload) => { + var _a2; + (_a2 = this._connections.get(payload.uid)) == null ? void 0 : _a2.onData(payload.data); + }); + this._socksProxy.addListener(SocksProxy.Events.SocksClosed, (payload) => { + var _a2; + (_a2 = this._connections.get(payload.uid)) == null ? void 0 : _a2.onClose(); + this._connections.delete(payload.uid); + }); + loadDummyServerCertsIfNeeded(); + } + _initSecureContexts(clientCertificates) { + const origin2certs = /* @__PURE__ */ new Map(); + for (const cert of clientCertificates || []) { + const origin = normalizeOrigin(cert.origin); + const certs = origin2certs.get(origin) || []; + certs.push(cert); + origin2certs.set(origin, certs); + } + for (const [origin, certs] of origin2certs) { + try { + this.secureContextMap.set(origin, tls.createSecureContext(convertClientCertificatesToTLSOptions(certs))); + } catch (error2) { + error2 = rewriteOpenSSLErrorIfNeeded(error2); + throw rewriteErrorMessage(error2, `Failed to load client certificate: ${error2.message}`); + } + } + } + async listen() { + const port = await this._socksProxy.listen(0, "127.0.0.1"); + return { server: `socks5://127.0.0.1:${port}` }; + } + async close() { + await this._socksProxy.close(); + } +} +function normalizeOrigin(origin) { + try { + return new URL(origin).origin; + } catch (error2) { + return origin; + } +} +function convertClientCertificatesToTLSOptions(clientCertificates) { + if (!clientCertificates || !clientCertificates.length) + return; + const tlsOptions = { + pfx: [], + key: [], + cert: [] + }; + for (const cert of clientCertificates) { + if (cert.cert) + tlsOptions.cert.push(cert.cert); + if (cert.key) + tlsOptions.key.push({ pem: cert.key, passphrase: cert.passphrase }); + if (cert.pfx) + tlsOptions.pfx.push({ buf: cert.pfx, passphrase: cert.passphrase }); + } + return tlsOptions; +} +function getMatchingTLSOptionsForOrigin(clientCertificates, origin) { + const matchingCerts = clientCertificates == null ? void 0 : clientCertificates.filter( + (c) => normalizeOrigin(c.origin) === origin + ); + return convertClientCertificatesToTLSOptions(matchingCerts); +} +function rewriteToLocalhostIfNeeded(host) { + return host === "local.playwright" ? "localhost" : host; +} +function rewriteOpenSSLErrorIfNeeded(error2) { + if (error2.message !== "unsupported" && error2.code !== "ERR_CRYPTO_UNSUPPORTED_OPERATION") + return error2; + return rewriteErrorMessage(error2, [ + "Unsupported TLS certificate.", + "Most likely, the security algorithm of the given certificate was deprecated by OpenSSL.", + "For more details, see https://github.com/openssl/openssl/blob/master/README-PROVIDERS.md#the-legacy-provider", + "You could probably modernize the certificate by following the steps at https://github.com/nodejs/node/issues/40672#issuecomment-1243648223" + ].join("\n")); +} +let APIRequestContext$1 = (_f = class extends SdkObject { + constructor(parent) { + super(parent, "request-context"); + this.fetchResponses = /* @__PURE__ */ new Map(); + this.fetchLog = /* @__PURE__ */ new Map(); + this._activeProgressControllers = /* @__PURE__ */ new Set(); + _f.allInstances.add(this); + } + static findResponseBody(guid) { + for (const request2 of _f.allInstances) { + const body = request2.fetchResponses.get(guid); + if (body) + return body; + } + return void 0; + } + _disposeImpl() { + _f.allInstances.delete(this); + this.fetchResponses.clear(); + this.fetchLog.clear(); + this.emit(_f.Events.Dispose); + } + disposeResponse(fetchUid) { + this.fetchResponses.delete(fetchUid); + this.fetchLog.delete(fetchUid); + } + _storeResponseBody(body) { + const uid = createGuid(); + this.fetchResponses.set(uid, body); + return uid; + } + async fetch(params, metadata) { + var _a2; + const defaults = this._defaultOptions(); + const headers = { + "user-agent": defaults.userAgent, + "accept": "*/*", + "accept-encoding": "gzip,deflate,br" + }; + if (defaults.extraHTTPHeaders) { + for (const { name, value } of defaults.extraHTTPHeaders) + setHeader(headers, name, value); + } + if (params.headers) { + for (const { name, value } of params.headers) + setHeader(headers, name, value); + } + const requestUrl = new URL(constructURLBasedOnBaseURL(defaults.baseURL, params.url)); + if (params.encodedParams) { + requestUrl.search = params.encodedParams; + } else if (params.params) { + for (const { name, value } of params.params) + requestUrl.searchParams.append(name, value); + } + const credentials = this._getHttpCredentials(requestUrl); + if ((credentials == null ? void 0 : credentials.send) === "always") + setBasicAuthorizationHeader(headers, credentials); + const method = ((_a2 = params.method) == null ? void 0 : _a2.toUpperCase()) || "GET"; + const proxy = defaults.proxy; + let agent2; + if ((proxy == null ? void 0 : proxy.server) !== "per-context") + agent2 = createProxyAgent(proxy, requestUrl); + let maxRedirects = params.maxRedirects ?? (defaults.maxRedirects ?? 20); + maxRedirects = maxRedirects === 0 ? -1 : maxRedirects; + const timeout = params.timeout; + const deadline = timeout && monotonicTime() + timeout; + const options2 = { + method, + headers, + agent: agent2, + maxRedirects, + timeout, + deadline, + ...getMatchingTLSOptionsForOrigin(this._defaultOptions().clientCertificates, requestUrl.origin), + __testHookLookup: params.__testHookLookup + }; + if (params.ignoreHTTPSErrors || defaults.ignoreHTTPSErrors) + options2.rejectUnauthorized = false; + const postData = serializePostData(params, headers); + if (postData) + setHeader(headers, "content-length", String(postData.byteLength)); + const controller = new ProgressController(metadata, this); + const fetchResponse = await controller.run((progress2) => { + return this._sendRequestWithRetries(progress2, requestUrl, options2, postData, params.maxRetries); + }); + const fetchUid = this._storeResponseBody(fetchResponse.body); + this.fetchLog.set(fetchUid, controller.metadata.log); + const failOnStatusCode = params.failOnStatusCode !== void 0 ? params.failOnStatusCode : !!defaults.failOnStatusCode; + if (failOnStatusCode && (fetchResponse.status < 200 || fetchResponse.status >= 400)) { + let responseText = ""; + if (fetchResponse.body.byteLength) { + let text = fetchResponse.body.toString("utf8"); + if (text.length > 1e3) + text = text.substring(0, 997) + "..."; + responseText = ` +Response text: +${text}`; + } + throw new Error(`${fetchResponse.status} ${fetchResponse.statusText}${responseText}`); + } + return { ...fetchResponse, fetchUid }; + } + _parseSetCookieHeader(responseUrl, setCookie) { + if (!setCookie) + return []; + const url2 = new URL(responseUrl); + const defaultPath = "/" + url2.pathname.substr(1).split("/").slice(0, -1).join("/"); + const cookies = []; + for (const header of setCookie) { + const cookie = parseCookie(header); + if (!cookie) + continue; + if (!cookie.domain) + cookie.domain = url2.hostname; + else + assert(cookie.domain.startsWith(".") || !cookie.domain.includes(".")); + if (!domainMatches(url2.hostname, cookie.domain)) + continue; + if (!cookie.path || !cookie.path.startsWith("/")) + cookie.path = defaultPath; + cookies.push(cookie); + } + return cookies; + } + async _updateRequestCookieHeader(url2, headers) { + if (getHeader(headers, "cookie") !== void 0) + return; + const contextCookies = await this._cookies(url2); + const cookies = contextCookies.filter((c) => new Cookie(c).matches(url2)); + if (cookies.length) { + const valueArray = cookies.map((c) => `${c.name}=${c.value}`); + setHeader(headers, "cookie", valueArray.join("; ")); + } + } + async _sendRequestWithRetries(progress2, url2, options2, postData, maxRetries) { + maxRetries ?? (maxRetries = 0); + let backoff = 250; + for (let i = 0; i <= maxRetries; i++) { + try { + return await this._sendRequest(progress2, url2, options2, postData); + } catch (e) { + e = rewriteOpenSSLErrorIfNeeded(e); + if (maxRetries === 0) + throw e; + if (i === maxRetries || options2.deadline && monotonicTime() + backoff > options2.deadline) + throw new Error(`Failed after ${i + 1} attempt(s): ${e}`); + if (e.code !== "ECONNRESET") + throw e; + progress2.log(` Received ECONNRESET, will retry after ${backoff}ms.`); + await new Promise((f) => setTimeout(f, backoff)); + backoff *= 2; + } + } + throw new Error("Unreachable"); + } + async _sendRequest(progress2, url2, options2, postData) { + var _a2; + await this._updateRequestCookieHeader(url2, options2.headers); + const requestCookies = ((_a2 = getHeader(options2.headers, "cookie")) == null ? void 0 : _a2.split(";").map((p) => { + const [name, value] = p.split("=").map((v) => v.trim()); + return { name, value }; + })) || []; + const requestEvent = { + url: url2, + method: options2.method, + headers: options2.headers, + cookies: requestCookies, + postData + }; + this.emit(_f.Events.Request, requestEvent); + return new Promise((fulfill, reject) => { + const requestConstructor = (url2.protocol === "https:" ? https : http).request; + const agent2 = options2.agent || (url2.protocol === "https:" ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent); + const requestOptions = { ...options2, agent: agent2 }; + const startAt = monotonicTime(); + let reusedSocketAt; + let dnsLookupAt; + let tcpConnectionAt; + let tlsHandshakeAt; + let requestFinishAt; + let serverIPAddress; + let serverPort; + let securityDetails; + const listeners = []; + const request2 = requestConstructor(url2, requestOptions, async (response2) => { + const responseAt = monotonicTime(); + const notifyRequestFinished = (body2) => { + const endAt = monotonicTime(); + const connectEnd = tlsHandshakeAt ?? tcpConnectionAt; + const timings = { + send: requestFinishAt - startAt, + wait: responseAt - requestFinishAt, + receive: endAt - responseAt, + dns: dnsLookupAt ? dnsLookupAt - startAt : -1, + connect: connectEnd ? connectEnd - startAt : -1, + // "If [ssl] is defined then the time is also included in the connect field " + ssl: tlsHandshakeAt ? tlsHandshakeAt - tcpConnectionAt : -1, + blocked: reusedSocketAt ? reusedSocketAt - startAt : -1 + }; + const requestFinishedEvent = { + requestEvent, + httpVersion: response2.httpVersion, + statusCode: response2.statusCode || 0, + statusMessage: response2.statusMessage || "", + headers: response2.headers, + rawHeaders: response2.rawHeaders, + cookies, + body: body2, + timings, + serverIPAddress, + serverPort, + securityDetails + }; + this.emit(_f.Events.RequestFinished, requestFinishedEvent); + }; + progress2.log(`← ${response2.statusCode} ${response2.statusMessage}`); + for (const [name, value] of Object.entries(response2.headers)) + progress2.log(` ${name}: ${value}`); + const cookies = this._parseSetCookieHeader(response2.url || url2.toString(), response2.headers["set-cookie"]); + if (cookies.length) { + try { + await this._addCookies(cookies); + } catch (e) { + await Promise.all(cookies.map((c) => this._addCookies([c]).catch(() => { + }))); + } + } + if (redirectStatus$1.includes(response2.statusCode) && options2.maxRedirects >= 0) { + if (options2.maxRedirects === 0) { + reject(new Error("Max redirect count exceeded")); + request2.destroy(); + return; + } + const headers = { ...options2.headers }; + removeHeader(headers, `cookie`); + const status = response2.statusCode; + let method = options2.method; + if ((status === 301 || status === 302) && method === "POST" || status === 303 && !["GET", "HEAD"].includes(method)) { + method = "GET"; + postData = void 0; + removeHeader(headers, `content-encoding`); + removeHeader(headers, `content-language`); + removeHeader(headers, `content-length`); + removeHeader(headers, `content-location`); + removeHeader(headers, `content-type`); + } + const redirectOptions = { + method, + headers, + agent: options2.agent, + maxRedirects: options2.maxRedirects - 1, + timeout: options2.timeout, + deadline: options2.deadline, + ...getMatchingTLSOptionsForOrigin(this._defaultOptions().clientCertificates, url2.origin), + __testHookLookup: options2.__testHookLookup + }; + if (options2.rejectUnauthorized === false) + redirectOptions.rejectUnauthorized = false; + const locationHeaderValue = Buffer.from(response2.headers.location ?? "", "latin1").toString("utf8"); + if (locationHeaderValue) { + let locationURL; + try { + locationURL = new URL(locationHeaderValue, url2); + } catch (error2) { + reject(new Error(`uri requested responds with an invalid redirect URL: ${locationHeaderValue}`)); + request2.destroy(); + return; + } + if (headers["host"]) + headers["host"] = locationURL.host; + notifyRequestFinished(); + fulfill(this._sendRequest(progress2, locationURL, redirectOptions, postData)); + request2.destroy(); + return; + } + } + if (response2.statusCode === 401 && !getHeader(options2.headers, "authorization")) { + const auth = response2.headers["www-authenticate"]; + const credentials = this._getHttpCredentials(url2); + if ((auth == null ? void 0 : auth.trim().startsWith("Basic")) && credentials) { + setBasicAuthorizationHeader(options2.headers, credentials); + notifyRequestFinished(); + fulfill(this._sendRequest(progress2, url2, options2, postData)); + request2.destroy(); + return; + } + } + response2.on("aborted", () => reject(new Error("aborted"))); + const chunks = []; + const notifyBodyFinished = () => { + const body2 = Buffer.concat(chunks); + notifyRequestFinished(body2); + fulfill({ + url: response2.url || url2.toString(), + status: response2.statusCode || 0, + statusText: response2.statusMessage || "", + headers: toHeadersArray(response2.rawHeaders), + body: body2 + }); + }; + let body = response2; + let transform2; + const encoding2 = response2.headers["content-encoding"]; + if (encoding2 === "gzip" || encoding2 === "x-gzip") { + transform2 = libExports.createGunzip({ + flush: libExports.constants.Z_SYNC_FLUSH, + finishFlush: libExports.constants.Z_SYNC_FLUSH + }); + } else if (encoding2 === "br") { + transform2 = libExports.createBrotliDecompress({ + flush: libExports.constants.BROTLI_OPERATION_FLUSH, + finishFlush: libExports.constants.BROTLI_OPERATION_FLUSH + }); + } else if (encoding2 === "deflate") { + transform2 = libExports.createInflate(); + } + if (transform2) { + const emptyStreamTransform = new SafeEmptyStreamTransform(notifyBodyFinished); + body = browserExports.pipeline(response2, emptyStreamTransform, transform2, (e) => { + if (e) + reject(new Error(`failed to decompress '${encoding2}' encoding: ${e.message}`)); + }); + body.on("error", (e) => reject(new Error(`failed to decompress '${encoding2}' encoding: ${e}`))); + } else { + body.on("error", reject); + } + body.on("data", (chunk) => chunks.push(chunk)); + body.on("end", notifyBodyFinished); + }); + request2.on("error", reject); + listeners.push( + eventsHelper.addEventListener(this, _f.Events.Dispose, () => { + reject(new Error("Request context disposed.")); + request2.destroy(); + }) + ); + request2.on("close", () => eventsHelper.removeEventListeners(listeners)); + request2.on("socket", (socket) => { + if (request2.reusedSocket) { + reusedSocketAt = monotonicTime(); + return; + } + const happyEyeBallsTimings = timingForSocket(socket); + dnsLookupAt = happyEyeBallsTimings.dnsLookupAt; + tcpConnectionAt = happyEyeBallsTimings.tcpConnectionAt; + listeners.push( + eventsHelper.addEventListener(socket, "lookup", () => { + dnsLookupAt = monotonicTime(); + }), + eventsHelper.addEventListener(socket, "connect", () => { + tcpConnectionAt = monotonicTime(); + }), + eventsHelper.addEventListener(socket, "secureConnect", () => { + tlsHandshakeAt = monotonicTime(); + if (socket instanceof TLSSocket) { + const peerCertificate = socket.getPeerCertificate(); + securityDetails = { + protocol: socket.getProtocol() ?? void 0, + subjectName: peerCertificate.subject.CN, + validFrom: new Date(peerCertificate.valid_from).getTime() / 1e3, + validTo: new Date(peerCertificate.valid_to).getTime() / 1e3, + issuer: peerCertificate.issuer.CN + }; + } + }) + ); + serverIPAddress = socket.remoteAddress; + serverPort = socket.remotePort; + }); + request2.on("finish", () => { + requestFinishAt = monotonicTime(); + }); + progress2.log(`→ ${options2.method} ${url2.toString()}`); + if (options2.headers) { + for (const [name, value] of Object.entries(options2.headers)) + progress2.log(` ${name}: ${value}`); + } + if (options2.deadline) { + const rejectOnTimeout = () => { + reject(new Error(`Request timed out after ${options2.timeout}ms`)); + request2.destroy(); + }; + const remaining = options2.deadline - monotonicTime(); + if (remaining <= 0) { + rejectOnTimeout(); + return; + } + request2.setTimeout(remaining, rejectOnTimeout); + } + if (postData) + request2.write(postData); + request2.end(); + }); + } + _getHttpCredentials(url2) { + var _a2, _b2, _c2; + if (!((_a2 = this._defaultOptions().httpCredentials) == null ? void 0 : _a2.origin) || url2.origin.toLowerCase() === ((_c2 = (_b2 = this._defaultOptions().httpCredentials) == null ? void 0 : _b2.origin) == null ? void 0 : _c2.toLowerCase())) + return this._defaultOptions().httpCredentials; + return void 0; + } +}, _f.Events = { + Dispose: "dispose", + Request: "request", + RequestFinished: "requestfinished" +}, _f.allInstances = /* @__PURE__ */ new Set(), _f); +class SafeEmptyStreamTransform extends browserExports.Transform { + constructor(onEmptyStreamCallback) { + super(); + this._receivedSomeData = false; + this._onEmptyStreamCallback = onEmptyStreamCallback; + } + _transform(chunk, encoding2, callback) { + this._receivedSomeData = true; + callback(null, chunk); + } + _flush(callback) { + if (this._receivedSomeData) + callback(null); + else + this._onEmptyStreamCallback(); + } +} +class BrowserContextAPIRequestContext extends APIRequestContext$1 { + constructor(context) { + super(context); + this._context = context; + context.once(BrowserContext$1.Events.Close, () => this._disposeImpl()); + } + tracing() { + return this._context.tracing; + } + async dispose(options2) { + this._closeReason = options2.reason; + this.fetchResponses.clear(); + } + _defaultOptions() { + return { + userAgent: this._context._options.userAgent || this._context._browser.userAgent(), + extraHTTPHeaders: this._context._options.extraHTTPHeaders, + failOnStatusCode: void 0, + httpCredentials: this._context._options.httpCredentials, + proxy: this._context._options.proxy || this._context._browser.options.proxy, + ignoreHTTPSErrors: this._context._options.ignoreHTTPSErrors, + baseURL: this._context._options.baseURL, + clientCertificates: this._context._options.clientCertificates + }; + } + async _addCookies(cookies) { + await this._context.addCookies(cookies); + } + async _cookies(url2) { + return await this._context.cookies(url2.toString()); + } + async storageState(indexedDB2) { + return this._context.storageState(indexedDB2); + } +} +class GlobalAPIRequestContext extends APIRequestContext$1 { + constructor(playwright2, options2) { + var _a2; + super(playwright2); + this._cookieStore = new CookieStore(); + this.attribution.context = this; + if (options2.storageState) { + this._origins = (_a2 = options2.storageState.origins) == null ? void 0 : _a2.map((origin) => ({ indexedDB: [], ...origin })); + this._cookieStore.addCookies(options2.storageState.cookies || []); + } + verifyClientCertificates(options2.clientCertificates); + this._options = { + baseURL: options2.baseURL, + userAgent: options2.userAgent || getUserAgent(), + extraHTTPHeaders: options2.extraHTTPHeaders, + failOnStatusCode: !!options2.failOnStatusCode, + ignoreHTTPSErrors: !!options2.ignoreHTTPSErrors, + maxRedirects: options2.maxRedirects, + httpCredentials: options2.httpCredentials, + clientCertificates: options2.clientCertificates, + proxy: options2.proxy + }; + this._tracing = new Tracing$1(this, options2.tracesDir); + } + tracing() { + return this._tracing; + } + async dispose(options2) { + this._closeReason = options2.reason; + await this._tracing.flush(); + await this._tracing.deleteTmpTracesDir(); + this._disposeImpl(); + } + _defaultOptions() { + return this._options; + } + async _addCookies(cookies) { + this._cookieStore.addCookies(cookies); + } + async _cookies(url2) { + return this._cookieStore.cookies(url2); + } + async storageState(indexedDB2 = false) { + return { + cookies: this._cookieStore.allCookies(), + origins: (this._origins || []).map((origin) => ({ ...origin, indexedDB: indexedDB2 ? origin.indexedDB : [] })) + }; + } +} +function toHeadersArray(rawHeaders) { + const result = []; + for (let i = 0; i < rawHeaders.length; i += 2) + result.push({ name: rawHeaders[i], value: rawHeaders[i + 1] }); + return result; +} +const redirectStatus$1 = [301, 302, 303, 307, 308]; +function parseCookie(header) { + const raw = parseRawCookie(header); + if (!raw) + return null; + const cookie = { + domain: "", + path: "", + expires: -1, + httpOnly: false, + secure: false, + // From https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite + // The cookie-sending behavior if SameSite is not specified is SameSite=Lax. + sameSite: "Lax", + ...raw + }; + return cookie; +} +function serializePostData(params, headers) { + assert((params.postData ? 1 : 0) + (params.jsonData ? 1 : 0) + (params.formData ? 1 : 0) + (params.multipartData ? 1 : 0) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`); + if (params.jsonData !== void 0) { + setHeader(headers, "content-type", "application/json", true); + return Buffer.from(params.jsonData, "utf8"); + } else if (params.formData) { + const searchParams = new URLSearchParams(); + for (const { name, value } of params.formData) + searchParams.append(name, value); + setHeader(headers, "content-type", "application/x-www-form-urlencoded", true); + return Buffer.from(searchParams.toString(), "utf8"); + } else if (params.multipartData) { + const formData = new MultipartFormData(); + for (const field of params.multipartData) { + if (field.file) + formData.addFileField(field.name, field.file); + else if (field.value) + formData.addField(field.name, field.value); + } + setHeader(headers, "content-type", formData.contentTypeHeader(), true); + return formData.finish(); + } else if (params.postData !== void 0) { + setHeader(headers, "content-type", "application/octet-stream", true); + return params.postData; + } + return void 0; +} +function setHeader(headers, name, value, keepExisting = false) { + const existing = Object.entries(headers).find((pair) => pair[0].toLowerCase() === name.toLowerCase()); + if (!existing) + headers[name] = value; + else if (!keepExisting) + headers[existing[0]] = value; +} +function getHeader(headers, name) { + const existing = Object.entries(headers).find((pair) => pair[0].toLowerCase() === name.toLowerCase()); + return existing ? existing[1] : void 0; +} +function removeHeader(headers, name) { + delete headers[name]; +} +function setBasicAuthorizationHeader(headers, credentials) { + const { username, password } = credentials; + const encoded = Buffer.from(`${username || ""}:${password || ""}`).toString("base64"); + setHeader(headers, "authorization", `Basic ${encoded}`); +} +class StreamDispatcher extends Dispatcher { + constructor(scope, stream2) { + super(scope, { guid: "stream@" + createGuid(), stream: stream2 }, "Stream", {}); + this._type_Stream = true; + this._ended = false; + stream2.once("end", () => this._ended = true); + stream2.once("error", () => this._ended = true); + } + async read(params) { + const stream2 = this._object.stream; + if (this._ended) + return { binary: Buffer.from("") }; + if (!stream2.readableLength) { + const readyPromise = new ManualPromise(); + const done = () => readyPromise.resolve(); + stream2.on("readable", done); + stream2.on("end", done); + stream2.on("error", done); + await readyPromise; + stream2.off("readable", done); + stream2.off("end", done); + stream2.off("error", done); + } + const buffer2 = stream2.read(Math.min(stream2.readableLength, params.size || stream2.readableLength)); + return { binary: buffer2 || Buffer.from("") }; + } + async close() { + this._object.stream.destroy(); + } +} +class ArtifactDispatcher extends Dispatcher { + constructor(scope, artifact) { + super(scope, artifact, "Artifact", { + absolutePath: artifact.localPath() + }); + this._type_Artifact = true; + } + static from(parentScope, artifact) { + return ArtifactDispatcher.fromNullable(parentScope, artifact); + } + static fromNullable(parentScope, artifact) { + if (!artifact) + return void 0; + const result = parentScope.connection.existingDispatcher(artifact); + return result || new ArtifactDispatcher(parentScope, artifact); + } + async pathAfterFinished() { + const path2 = await this._object.localPathAfterFinished(); + return { value: path2 }; + } + async saveAs(params) { + return await new Promise((resolve, reject) => { + this._object.saveAs(async (localPath, error2) => { + if (error2) { + reject(error2); + return; + } + try { + await mkdirIfNeeded$1(params.path); + await fs.promises.copyFile(localPath, params.path); + resolve(); + } catch (e) { + reject(e); + } + }); + }); + } + async saveAsStream() { + return await new Promise((resolve, reject) => { + this._object.saveAs(async (localPath, error2) => { + if (error2) { + reject(error2); + return; + } + try { + const readable2 = fs.createReadStream(localPath, { highWaterMark: 1024 * 1024 }); + const stream2 = new StreamDispatcher(this, readable2); + resolve({ stream: stream2 }); + await new Promise((resolve2) => { + readable2.on("close", resolve2); + readable2.on("end", resolve2); + readable2.on("error", resolve2); + }); + } catch (e) { + reject(e); + } + }); + }); + } + async stream() { + const fileName = await this._object.localPathAfterFinished(); + const readable2 = fs.createReadStream(fileName, { highWaterMark: 1024 * 1024 }); + return { stream: new StreamDispatcher(this, readable2) }; + } + async failure() { + const error2 = await this._object.failureError(); + return { error: error2 || void 0 }; + } + async cancel() { + await this._object.cancel(); + } + async delete(_, metadata) { + metadata.potentiallyClosesScope = true; + await this._object.delete(); + this._dispose(); + } +} +const ConnectionEvents$1 = { + Disconnected: Symbol("ConnectionEvents.Disconnected") +}; +const kBrowserCloseMessageId$3 = -9999; +class CRConnection extends eventsExports.EventEmitter { + constructor(transport, protocolLogger, browserLogsCollector) { + super(); + this._lastId = 0; + this._sessions = /* @__PURE__ */ new Map(); + this._closed = false; + this.setMaxListeners(0); + this._transport = transport; + this._protocolLogger = protocolLogger; + this._browserLogsCollector = browserLogsCollector; + this.rootSession = new CRSession(this, null, ""); + this._sessions.set("", this.rootSession); + this._transport.onmessage = this._onMessage.bind(this); + this._transport.onclose = this._onClose.bind(this); + } + _rawSend(sessionId, method, params) { + const id = ++this._lastId; + const message = { id, method, params }; + if (sessionId) + message.sessionId = sessionId; + this._protocolLogger("send", message); + this._transport.send(message); + return id; + } + async _onMessage(message) { + this._protocolLogger("receive", message); + if (message.id === kBrowserCloseMessageId$3) + return; + const session = this._sessions.get(message.sessionId || ""); + if (session) + session._onMessage(message); + } + _onClose(reason) { + this._closed = true; + this._transport.onmessage = void 0; + this._transport.onclose = void 0; + this._browserDisconnectedLogs = helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason); + this.rootSession.dispose(); + Promise.resolve().then(() => this.emit(ConnectionEvents$1.Disconnected)); + } + close() { + if (!this._closed) + this._transport.close(); + } + async createBrowserSession() { + const { sessionId } = await this.rootSession.send("Target.attachToBrowserTarget"); + return new CDPSession$1(this.rootSession, sessionId); + } +} +class CRSession extends eventsExports.EventEmitter { + constructor(connection, parentSession, sessionId, eventListener) { + super(); + this._callbacks = /* @__PURE__ */ new Map(); + this._crashed = false; + this._closed = false; + this.setMaxListeners(0); + this._connection = connection; + this._parentSession = parentSession; + this._sessionId = sessionId; + this._eventListener = eventListener; + this.on = super.on; + this.addListener = super.addListener; + this.off = super.removeListener; + this.removeListener = super.removeListener; + this.once = super.once; + } + _markAsCrashed() { + this._crashed = true; + } + createChildSession(sessionId, eventListener) { + const session = new CRSession(this._connection, this, sessionId, eventListener); + this._connection._sessions.set(sessionId, session); + return session; + } + async send(method, params) { + if (this._crashed || this._closed || this._connection._closed || this._connection._browserDisconnectedLogs) + throw new ProtocolError(this._crashed ? "crashed" : "closed", void 0, this._connection._browserDisconnectedLogs); + const id = this._connection._rawSend(this._sessionId, method, params); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + _sendMayFail(method, params) { + return this.send(method, params).catch((error2) => debugLogger.log("error", error2)); + } + _onMessage(object) { + var _a2, _b2; + if (object.id && this._callbacks.has(object.id)) { + const callback = this._callbacks.get(object.id); + this._callbacks.delete(object.id); + if (object.error) { + callback.error.setMessage(object.error.message); + callback.reject(callback.error); + } else { + callback.resolve(object.result); + } + } else if (object.id && ((_a2 = object.error) == null ? void 0 : _a2.code) === -32001) ; + else { + assert(!object.id, ((_b2 = object == null ? void 0 : object.error) == null ? void 0 : _b2.message) || void 0); + Promise.resolve().then(() => { + if (this._eventListener) + this._eventListener(object.method, object.params); + this.emit(object.method, object.params); + }); + } + } + async detach() { + if (this._closed) + throw new Error(`Session already detached. Most likely the page has been closed.`); + if (!this._parentSession) + throw new Error("Root session cannot be closed"); + await this._sendMayFail("Runtime.runIfWaitingForDebugger"); + await this._parentSession.send("Target.detachFromTarget", { sessionId: this._sessionId }); + this.dispose(); + } + dispose() { + this._closed = true; + this._connection._sessions.delete(this._sessionId); + for (const callback of this._callbacks.values()) { + callback.error.setMessage(`Internal server error, session closed.`); + callback.error.type = this._crashed ? "crashed" : "closed"; + callback.error.logs = this._connection._browserDisconnectedLogs; + callback.reject(callback.error); + } + this._callbacks.clear(); + } +} +let CDPSession$1 = (_g = class extends eventsExports.EventEmitter { + constructor(parentSession, sessionId) { + super(); + this._listeners = []; + this.guid = `cdp-session@${sessionId}`; + this._session = parentSession.createChildSession(sessionId, (method, params) => this.emit(_g.Events.Event, { method, params })); + this._listeners = [eventsHelper.addEventListener(parentSession, "Target.detachedFromTarget", (event) => { + if (event.sessionId === sessionId) + this._onClose(); + })]; + } + async send(method, params) { + return await this._session.send(method, params); + } + async detach() { + return await this._session.detach(); + } + async attachToTarget(targetId) { + const { sessionId } = await this.send("Target.attachToTarget", { targetId, flatten: true }); + return new _g(this._session, sessionId); + } + _onClose() { + eventsHelper.removeEventListeners(this._listeners); + this._session.dispose(); + this.emit(_g.Events.Closed); + } +}, _g.Events = { + Event: "event", + Closed: "close" +}, _g); +class CDPSessionDispatcher extends Dispatcher { + constructor(scope, cdpSession) { + super(scope, cdpSession, "CDPSession", {}); + this._type_CDPSession = true; + this.addObjectListener(CDPSession$1.Events.Event, ({ method, params }) => this._dispatchEvent("event", { method, params })); + this.addObjectListener(CDPSession$1.Events.Closed, () => this._dispose()); + } + async send(params) { + return { result: await this._object.send(params.method, params.params) }; + } + async detach(_, metadata) { + metadata.potentiallyClosesScope = true; + await this._object.detach(); + } +} +class JSHandleDispatcher extends Dispatcher { + constructor(scope, jsHandle) { + super(scope, jsHandle, jsHandle.asElement() ? "ElementHandle" : "JSHandle", { + preview: jsHandle.toString() + }); + this._type_JSHandle = true; + jsHandle._setPreviewCallback((preview) => this._dispatchEvent("previewUpdated", { preview })); + } + static fromJSHandle(scope, handle) { + return scope.connection.existingDispatcher(handle) || new JSHandleDispatcher(scope, handle); + } + async evaluateExpression(params) { + return { value: serializeResult(await this._object.evaluateExpression(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) }; + } + async evaluateExpressionHandle(params) { + const jsHandle = await this._object.evaluateExpressionHandle(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg)); + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this.parentScope(), jsHandle) }; + } + async getProperty(params) { + const jsHandle = await this._object.getProperty(params.name); + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this.parentScope(), jsHandle) }; + } + async getPropertyList() { + const map2 = await this._object.getProperties(); + const properties = []; + for (const [name, value] of map2) { + properties.push({ name, value: ElementHandleDispatcher.fromJSOrElementHandle(this.parentScope(), value) }); + } + return { properties }; + } + async jsonValue() { + return { value: serializeResult(await this._object.jsonValue()) }; + } + async dispose(_, metadata) { + metadata.potentiallyClosesScope = true; + this._object.dispose(); + this._dispose(); + } +} +function parseArgument(arg) { + return parseSerializedValue(arg.value, arg.handles.map((a) => a._object)); +} +function serializeResult(arg) { + return serializeValue(arg, (value) => ({ fallThrough: value })); +} +class TracingDispatcher extends Dispatcher { + constructor(scope, tracing) { + super(scope, tracing, "Tracing", {}); + this._type_Tracing = true; + } + static from(scope, tracing) { + const result = scope.connection.existingDispatcher(tracing); + return result || new TracingDispatcher(scope, tracing); + } + async tracingStart(params) { + await this._object.start(params); + } + async tracingStartChunk(params) { + return await this._object.startChunk(params); + } + async tracingGroup(params, metadata) { + const { name, location: location2 } = params; + await this._object.group(name, location2, metadata); + } + async tracingGroupEnd(params) { + await this._object.groupEnd(); + } + async tracingStopChunk(params) { + const { artifact, entries } = await this._object.stopChunk(params); + return { artifact: artifact ? ArtifactDispatcher.from(this, artifact) : void 0, entries }; + } + async tracingStop(params) { + await this._object.stop(); + } +} +class RequestDispatcher extends Dispatcher { + static from(scope, request2) { + const result = scope.connection.existingDispatcher(request2); + return result || new RequestDispatcher(scope, request2); + } + static fromNullable(scope, request2) { + return request2 ? RequestDispatcher.from(scope, request2) : void 0; + } + constructor(scope, request2) { + var _a2; + const postData = request2.postDataBuffer(); + const frame = request2.frame(); + const page = (_a2 = request2.frame()) == null ? void 0 : _a2._page; + const pageDispatcher = page ? scope.connection.existingDispatcher(page) : null; + const frameDispatcher = frame ? FrameDispatcher.from(scope, frame) : null; + super(pageDispatcher || frameDispatcher || scope, request2, "Request", { + frame: FrameDispatcher.fromNullable(scope, request2.frame()), + serviceWorker: WorkerDispatcher.fromNullable(scope, request2.serviceWorker()), + url: request2.url(), + resourceType: request2.resourceType(), + method: request2.method(), + postData: postData === null ? void 0 : postData, + headers: request2.headers(), + isNavigationRequest: request2.isNavigationRequest(), + redirectedFrom: RequestDispatcher.fromNullable(scope, request2.redirectedFrom()) + }); + this._type_Request = true; + this._browserContextDispatcher = scope; + } + async rawRequestHeaders(params) { + return { headers: await this._object.rawRequestHeaders() }; + } + async response() { + return { response: ResponseDispatcher.fromNullable(this._browserContextDispatcher, await this._object.response()) }; + } +} +class ResponseDispatcher extends Dispatcher { + constructor(scope, response2) { + super(scope, response2, "Response", { + // TODO: responses in popups can point to non-reported requests. + request: scope, + url: response2.url(), + status: response2.status(), + statusText: response2.statusText(), + headers: response2.headers(), + timing: response2.timing(), + fromServiceWorker: response2.fromServiceWorker() + }); + this._type_Response = true; + } + static from(scope, response2) { + const result = scope.connection.existingDispatcher(response2); + const requestDispatcher = RequestDispatcher.from(scope, response2.request()); + return result || new ResponseDispatcher(requestDispatcher, response2); + } + static fromNullable(scope, response2) { + return response2 ? ResponseDispatcher.from(scope, response2) : void 0; + } + async body() { + return { binary: await this._object.body() }; + } + async securityDetails() { + return { value: await this._object.securityDetails() || void 0 }; + } + async serverAddr() { + return { value: await this._object.serverAddr() || void 0 }; + } + async rawResponseHeaders(params) { + return { headers: await this._object.rawResponseHeaders() }; + } + async sizes(params) { + return { sizes: await this._object.sizes() }; + } +} +class RouteDispatcher extends Dispatcher { + constructor(scope, route) { + super(scope, route, "Route", { + // Context route can point to a non-reported request, so we send the request in the initializer. + request: scope + }); + this._type_Route = true; + this._handled = false; + } + _checkNotHandled() { + if (this._handled) + throw new Error("Route is already handled!"); + this._handled = true; + } + async continue(params, metadata) { + this._checkNotHandled(); + await this._object.continue({ + url: params.url, + method: params.method, + headers: params.headers, + postData: params.postData, + isFallback: params.isFallback + }); + } + async fulfill(params, metadata) { + this._checkNotHandled(); + await this._object.fulfill(params); + } + async abort(params, metadata) { + this._checkNotHandled(); + await this._object.abort(params.errorCode || "failed"); + } + async redirectNavigationRequest(params) { + this._checkNotHandled(); + await this._object.redirectNavigationRequest(params.url); + } +} +class WebSocketDispatcher extends Dispatcher { + constructor(scope, webSocket) { + super(scope, webSocket, "WebSocket", { + url: webSocket.url() + }); + this._type_EventTarget = true; + this._type_WebSocket = true; + this.addObjectListener(WebSocket$1.Events.FrameSent, (event) => this._dispatchEvent("frameSent", event)); + this.addObjectListener(WebSocket$1.Events.FrameReceived, (event) => this._dispatchEvent("frameReceived", event)); + this.addObjectListener(WebSocket$1.Events.SocketError, (error2) => this._dispatchEvent("socketError", { error: error2 })); + this.addObjectListener(WebSocket$1.Events.Close, () => this._dispatchEvent("close", {})); + } +} +class APIRequestContextDispatcher extends Dispatcher { + constructor(parentScope, request2) { + const tracing = TracingDispatcher.from(parentScope, request2.tracing()); + super(parentScope, request2, "APIRequestContext", { + tracing + }); + this._type_APIRequestContext = true; + this.adopt(tracing); + } + static from(scope, request2) { + const result = scope.connection.existingDispatcher(request2); + return result || new APIRequestContextDispatcher(scope, request2); + } + static fromNullable(scope, request2) { + return request2 ? APIRequestContextDispatcher.from(scope, request2) : void 0; + } + async storageState(params) { + return this._object.storageState(params.indexedDB); + } + async dispose(params, metadata) { + metadata.potentiallyClosesScope = true; + await this._object.dispose(params); + this._dispose(); + } + async fetch(params, metadata) { + const fetchResponse = await this._object.fetch(params, metadata); + return { + response: { + url: fetchResponse.url, + status: fetchResponse.status, + statusText: fetchResponse.statusText, + headers: fetchResponse.headers, + fetchUid: fetchResponse.fetchUid + } + }; + } + async fetchResponseBody(params) { + return { binary: this._object.fetchResponses.get(params.fetchUid) }; + } + async fetchLog(params) { + const log = this._object.fetchLog.get(params.fetchUid) || []; + return { log }; + } + async disposeAPIResponse(params) { + this._object.disposeResponse(params.fetchUid); + } +} +function parseAriaSnapshotUnsafe(yaml2, text) { + const result = parseAriaSnapshot(yaml2, text); + if (result.errors.length) + throw new Error(result.errors[0].message); + return result.fragment; +} +function parseAriaSnapshot(yaml2, text, options2 = {}) { + var _a2; + const lineCounter = new yaml2.LineCounter(); + const parseOptions2 = { + keepSourceTokens: true, + lineCounter, + ...options2 + }; + const yamlDoc = yaml2.parseDocument(text, parseOptions2); + const errors2 = []; + const convertRange = (range2) => { + return [lineCounter.linePos(range2[0]), lineCounter.linePos(range2[1])]; + }; + const addError = (error2) => { + errors2.push({ + message: error2.message, + range: [lineCounter.linePos(error2.pos[0]), lineCounter.linePos(error2.pos[1])] + }); + }; + const convertSeq = (container, seq2) => { + for (const item of seq2.items) { + const itemIsString = item instanceof yaml2.Scalar && typeof item.value === "string"; + if (itemIsString) { + const childNode = KeyParser.parse(item, parseOptions2, errors2); + if (childNode) { + container.children = container.children || []; + container.children.push(childNode); + } + continue; + } + const itemIsMap = item instanceof yaml2.YAMLMap; + if (itemIsMap) { + convertMap(container, item); + continue; + } + errors2.push({ + message: "Sequence items should be strings or maps", + range: convertRange(item.range || seq2.range) + }); + } + }; + const convertMap = (container, map2) => { + for (const entry of map2.items) { + container.children = container.children || []; + const keyIsString = entry.key instanceof yaml2.Scalar && typeof entry.key.value === "string"; + if (!keyIsString) { + errors2.push({ + message: "Only string keys are supported", + range: convertRange(entry.key.range || map2.range) + }); + continue; + } + const key2 = entry.key; + const value = entry.value; + if (key2.value === "text") { + const valueIsString = value instanceof yaml2.Scalar && typeof value.value === "string"; + if (!valueIsString) { + errors2.push({ + message: "Text value should be a string", + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.children.push({ + kind: "text", + text: valueOrRegex(value.value) + }); + continue; + } + if (key2.value === "/children") { + const valueIsString = value instanceof yaml2.Scalar && typeof value.value === "string"; + if (!valueIsString || value.value !== "contain" && value.value !== "equal" && value.value !== "deep-equal") { + errors2.push({ + message: 'Strict value should be "contain", "equal" or "deep-equal"', + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.containerMode = value.value; + continue; + } + if (key2.value.startsWith("/")) { + const valueIsString = value instanceof yaml2.Scalar && typeof value.value === "string"; + if (!valueIsString) { + errors2.push({ + message: "Property value should be a string", + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.props = container.props ?? {}; + container.props[key2.value.slice(1)] = valueOrRegex(value.value); + continue; + } + const childNode = KeyParser.parse(key2, parseOptions2, errors2); + if (!childNode) + continue; + const valueIsScalar = value instanceof yaml2.Scalar; + if (valueIsScalar) { + const type2 = typeof value.value; + if (type2 !== "string" && type2 !== "number" && type2 !== "boolean") { + errors2.push({ + message: "Node value should be a string or a sequence", + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.children.push({ + ...childNode, + children: [{ + kind: "text", + text: valueOrRegex(String(value.value)) + }] + }); + continue; + } + const valueIsSequence = value instanceof yaml2.YAMLSeq; + if (valueIsSequence) { + container.children.push(childNode); + convertSeq(childNode, value); + continue; + } + errors2.push({ + message: "Map values should be strings or sequences", + range: convertRange(entry.value.range || map2.range) + }); + } + }; + const fragment = { kind: "role", role: "fragment" }; + yamlDoc.errors.forEach(addError); + if (errors2.length) + return { errors: errors2, fragment }; + if (!(yamlDoc.contents instanceof yaml2.YAMLSeq)) { + errors2.push({ + message: 'Aria snapshot must be a YAML sequence, elements starting with " -"', + range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }] + }); + } + if (errors2.length) + return { errors: errors2, fragment }; + convertSeq(fragment, yamlDoc.contents); + if (errors2.length) + return { errors: errors2, fragment: emptyFragment }; + if (((_a2 = fragment.children) == null ? void 0 : _a2.length) === 1) + return { fragment: fragment.children[0], errors: errors2 }; + return { fragment, errors: errors2 }; +} +const emptyFragment = { kind: "role", role: "fragment" }; +function normalizeWhitespace(text) { + return text.replace(/[\u200b\u00ad]/g, "").replace(/[\r\n\s\t]+/g, " ").trim(); +} +function valueOrRegex(value) { + return value.startsWith("/") && value.endsWith("/") && value.length > 1 ? { pattern: value.slice(1, -1) } : normalizeWhitespace(value); +} +class KeyParser { + static parse(text, options2, errors2) { + try { + return new KeyParser(text.value)._parse(); + } catch (e) { + if (e instanceof ParserError$1) { + const message = options2.prettyErrors === false ? e.message : e.message + ":\n\n" + text.value + "\n" + " ".repeat(e.pos) + "^\n"; + errors2.push({ + message, + range: [options2.lineCounter.linePos(text.range[0]), options2.lineCounter.linePos(text.range[0] + e.pos)] + }); + return null; + } + throw e; + } + } + constructor(input) { + this._input = input; + this._pos = 0; + this._length = input.length; + } + _peek() { + return this._input[this._pos] || ""; + } + _next() { + if (this._pos < this._length) + return this._input[this._pos++]; + return null; + } + _eof() { + return this._pos >= this._length; + } + _isWhitespace() { + return !this._eof() && /\s/.test(this._peek()); + } + _skipWhitespace() { + while (this._isWhitespace()) + this._pos++; + } + _readIdentifier(type2) { + if (this._eof()) + this._throwError(`Unexpected end of input when expecting ${type2}`); + const start = this._pos; + while (!this._eof() && /[a-zA-Z]/.test(this._peek())) + this._pos++; + return this._input.slice(start, this._pos); + } + _readString() { + let result = ""; + let escaped2 = false; + while (!this._eof()) { + const ch = this._next(); + if (escaped2) { + result += ch; + escaped2 = false; + } else if (ch === "\\") { + escaped2 = true; + } else if (ch === '"') { + return result; + } else { + result += ch; + } + } + this._throwError("Unterminated string"); + } + _throwError(message, offset2 = 0) { + throw new ParserError$1(message, offset2 || this._pos); + } + _readRegex() { + let result = ""; + let escaped2 = false; + let insideClass = false; + while (!this._eof()) { + const ch = this._next(); + if (escaped2) { + result += ch; + escaped2 = false; + } else if (ch === "\\") { + escaped2 = true; + result += ch; + } else if (ch === "/" && !insideClass) { + return { pattern: result }; + } else if (ch === "[") { + insideClass = true; + result += ch; + } else if (ch === "]" && insideClass) { + result += ch; + insideClass = false; + } else { + result += ch; + } + } + this._throwError("Unterminated regex"); + } + _readStringOrRegex() { + const ch = this._peek(); + if (ch === '"') { + this._next(); + return normalizeWhitespace(this._readString()); + } + if (ch === "/") { + this._next(); + return this._readRegex(); + } + return null; + } + _readAttributes(result) { + let errorPos = this._pos; + while (true) { + this._skipWhitespace(); + if (this._peek() === "[") { + this._next(); + this._skipWhitespace(); + errorPos = this._pos; + const flagName = this._readIdentifier("attribute"); + this._skipWhitespace(); + let flagValue = ""; + if (this._peek() === "=") { + this._next(); + this._skipWhitespace(); + errorPos = this._pos; + while (this._peek() !== "]" && !this._isWhitespace() && !this._eof()) + flagValue += this._next(); + } + this._skipWhitespace(); + if (this._peek() !== "]") + this._throwError("Expected ]"); + this._next(); + this._applyAttribute(result, flagName, flagValue || "true", errorPos); + } else { + break; + } + } + } + _parse() { + this._skipWhitespace(); + const role = this._readIdentifier("role"); + this._skipWhitespace(); + const name = this._readStringOrRegex() || ""; + const result = { kind: "role", role, name }; + this._readAttributes(result); + this._skipWhitespace(); + if (!this._eof()) + this._throwError("Unexpected input"); + return result; + } + _applyAttribute(node2, key2, value, errorPos) { + if (key2 === "checked") { + this._assert(value === "true" || value === "false" || value === "mixed", 'Value of "checked" attribute must be a boolean or "mixed"', errorPos); + node2.checked = value === "true" ? true : value === "false" ? false : "mixed"; + return; + } + if (key2 === "disabled") { + this._assert(value === "true" || value === "false", 'Value of "disabled" attribute must be a boolean', errorPos); + node2.disabled = value === "true"; + return; + } + if (key2 === "expanded") { + this._assert(value === "true" || value === "false", 'Value of "expanded" attribute must be a boolean', errorPos); + node2.expanded = value === "true"; + return; + } + if (key2 === "level") { + this._assert(!isNaN(Number(value)), 'Value of "level" attribute must be a number', errorPos); + node2.level = Number(value); + return; + } + if (key2 === "pressed") { + this._assert(value === "true" || value === "false" || value === "mixed", 'Value of "pressed" attribute must be a boolean or "mixed"', errorPos); + node2.pressed = value === "true" ? true : value === "false" ? false : "mixed"; + return; + } + if (key2 === "selected") { + this._assert(value === "true" || value === "false", 'Value of "selected" attribute must be a boolean', errorPos); + node2.selected = value === "true"; + return; + } + this._assert(false, `Unsupported attribute [${key2}]`, errorPos); + } + _assert(value, message, valuePos) { + if (!value) + this._throwError(message || "Assertion error", valuePos); + } +} +let ParserError$1 = class ParserError extends Error { + constructor(message, pos) { + super(message); + this.pos = pos; + } +}; +class FrameDispatcher extends Dispatcher { + constructor(scope, frame) { + const gcBucket = frame._page.mainFrame() === frame ? "MainFrame" : "Frame"; + const pageDispatcher = scope.connection.existingDispatcher(frame._page); + super(pageDispatcher || scope, frame, "Frame", { + url: frame.url(), + name: frame.name(), + parentFrame: FrameDispatcher.fromNullable(scope, frame.parentFrame()), + loadStates: Array.from(frame._firedLifecycleEvents) + }, gcBucket); + this._type_Frame = true; + this._browserContextDispatcher = scope; + this._frame = frame; + this.addObjectListener(Frame$1.Events.AddLifecycle, (lifecycleEvent) => { + this._dispatchEvent("loadstate", { add: lifecycleEvent }); + }); + this.addObjectListener(Frame$1.Events.RemoveLifecycle, (lifecycleEvent) => { + this._dispatchEvent("loadstate", { remove: lifecycleEvent }); + }); + this.addObjectListener(Frame$1.Events.InternalNavigation, (event) => { + if (!event.isPublic) + return; + const params = { url: event.url, name: event.name, error: event.error ? event.error.message : void 0 }; + if (event.newDocument) + params.newDocument = { request: RequestDispatcher.fromNullable(this._browserContextDispatcher, event.newDocument.request || null) }; + this._dispatchEvent("navigated", params); + }); + } + static from(scope, frame) { + const result = scope.connection.existingDispatcher(frame); + return result || new FrameDispatcher(scope, frame); + } + static fromNullable(scope, frame) { + if (!frame) + return; + return FrameDispatcher.from(scope, frame); + } + async goto(params, metadata) { + return { response: ResponseDispatcher.fromNullable(this._browserContextDispatcher, await this._frame.goto(metadata, params.url, params)) }; + } + async frameElement() { + return { element: ElementHandleDispatcher.from(this, await this._frame.frameElement()) }; + } + async evaluateExpression(params, metadata) { + return { value: serializeResult(await this._frame.evaluateExpression(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) }; + } + async evaluateExpressionHandle(params, metadata) { + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this, await this._frame.evaluateExpressionHandle(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) }; + } + async waitForSelector(params, metadata) { + return { element: ElementHandleDispatcher.fromNullable(this, await this._frame.waitForSelector(metadata, params.selector, params)) }; + } + async dispatchEvent(params, metadata) { + return this._frame.dispatchEvent(metadata, params.selector, params.type, parseArgument(params.eventInit), params); + } + async evalOnSelector(params, metadata) { + return { value: serializeResult(await this._frame.evalOnSelector(params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg))) }; + } + async evalOnSelectorAll(params, metadata) { + return { value: serializeResult(await this._frame.evalOnSelectorAll(params.selector, params.expression, params.isFunction, parseArgument(params.arg))) }; + } + async querySelector(params, metadata) { + return { element: ElementHandleDispatcher.fromNullable(this, await this._frame.querySelector(params.selector, params)) }; + } + async querySelectorAll(params, metadata) { + const elements = await this._frame.querySelectorAll(params.selector); + return { elements: elements.map((e) => ElementHandleDispatcher.from(this, e)) }; + } + async queryCount(params) { + return { value: await this._frame.queryCount(params.selector) }; + } + async content() { + return { value: await this._frame.content() }; + } + async setContent(params, metadata) { + return await this._frame.setContent(metadata, params.html, params); + } + async addScriptTag(params, metadata) { + return { element: ElementHandleDispatcher.from(this, await this._frame.addScriptTag(params)) }; + } + async addStyleTag(params, metadata) { + return { element: ElementHandleDispatcher.from(this, await this._frame.addStyleTag(params)) }; + } + async click(params, metadata) { + metadata.potentiallyClosesScope = true; + return await this._frame.click(metadata, params.selector, params); + } + async dblclick(params, metadata) { + return await this._frame.dblclick(metadata, params.selector, params); + } + async dragAndDrop(params, metadata) { + return await this._frame.dragAndDrop(metadata, params.source, params.target, params); + } + async tap(params, metadata) { + return await this._frame.tap(metadata, params.selector, params); + } + async fill(params, metadata) { + return await this._frame.fill(metadata, params.selector, params.value, params); + } + async focus(params, metadata) { + await this._frame.focus(metadata, params.selector, params); + } + async blur(params, metadata) { + await this._frame.blur(metadata, params.selector, params); + } + async textContent(params, metadata) { + const value = await this._frame.textContent(metadata, params.selector, params); + return { value: value === null ? void 0 : value }; + } + async innerText(params, metadata) { + return { value: await this._frame.innerText(metadata, params.selector, params) }; + } + async innerHTML(params, metadata) { + return { value: await this._frame.innerHTML(metadata, params.selector, params) }; + } + async getAttribute(params, metadata) { + const value = await this._frame.getAttribute(metadata, params.selector, params.name, params); + return { value: value === null ? void 0 : value }; + } + async inputValue(params, metadata) { + const value = await this._frame.inputValue(metadata, params.selector, params); + return { value }; + } + async isChecked(params, metadata) { + return { value: await this._frame.isChecked(metadata, params.selector, params) }; + } + async isDisabled(params, metadata) { + return { value: await this._frame.isDisabled(metadata, params.selector, params) }; + } + async isEditable(params, metadata) { + return { value: await this._frame.isEditable(metadata, params.selector, params) }; + } + async isEnabled(params, metadata) { + return { value: await this._frame.isEnabled(metadata, params.selector, params) }; + } + async isHidden(params, metadata) { + return { value: await this._frame.isHidden(metadata, params.selector, params) }; + } + async isVisible(params, metadata) { + return { value: await this._frame.isVisible(metadata, params.selector, params) }; + } + async hover(params, metadata) { + return await this._frame.hover(metadata, params.selector, params); + } + async selectOption(params, metadata) { + const elements = (params.elements || []).map((e) => e._elementHandle); + return { values: await this._frame.selectOption(metadata, params.selector, elements, params.options || [], params) }; + } + async setInputFiles(params, metadata) { + return await this._frame.setInputFiles(metadata, params.selector, params); + } + async type(params, metadata) { + return await this._frame.type(metadata, params.selector, params.text, params); + } + async press(params, metadata) { + return await this._frame.press(metadata, params.selector, params.key, params); + } + async check(params, metadata) { + return await this._frame.check(metadata, params.selector, params); + } + async uncheck(params, metadata) { + return await this._frame.uncheck(metadata, params.selector, params); + } + async waitForTimeout(params, metadata) { + return await this._frame.waitForTimeout(metadata, params.timeout); + } + async waitForFunction(params, metadata) { + return { handle: ElementHandleDispatcher.fromJSOrElementHandle(this, await this._frame._waitForFunctionExpression(metadata, params.expression, params.isFunction, parseArgument(params.arg), params)) }; + } + async title(params, metadata) { + return { value: await this._frame.title() }; + } + async highlight(params, metadata) { + return await this._frame.highlight(params.selector); + } + async expect(params, metadata) { + metadata.potentiallyClosesScope = true; + let expectedValue = params.expectedValue ? parseArgument(params.expectedValue) : void 0; + if (params.expression === "to.match.aria" && expectedValue) + expectedValue = parseAriaSnapshotUnsafe(yaml, expectedValue); + const result = await this._frame.expect(metadata, params.selector, { ...params, expectedValue }); + if (result.received !== void 0) + result.received = serializeResult(result.received); + return result; + } + async ariaSnapshot(params, metadata) { + return { snapshot: await this._frame.ariaSnapshot(metadata, params.selector, params) }; + } +} +class ElementHandleDispatcher extends JSHandleDispatcher { + constructor(scope, elementHandle) { + super(scope, elementHandle); + this._type_ElementHandle = true; + this._elementHandle = elementHandle; + } + static from(scope, handle) { + return scope.connection.existingDispatcher(handle) || new ElementHandleDispatcher(scope, handle); + } + static fromNullable(scope, handle) { + if (!handle) + return void 0; + return scope.connection.existingDispatcher(handle) || new ElementHandleDispatcher(scope, handle); + } + static fromJSOrElementHandle(scope, handle) { + const result = scope.connection.existingDispatcher(handle); + if (result) + return result; + const elementHandle = handle.asElement(); + if (!elementHandle) + return new JSHandleDispatcher(scope, handle); + return new ElementHandleDispatcher(scope, elementHandle); + } + async ownerFrame(params, metadata) { + const frame = await this._elementHandle.ownerFrame(); + return { frame: frame ? FrameDispatcher.from(this._browserContextDispatcher(), frame) : void 0 }; + } + async contentFrame(params, metadata) { + const frame = await this._elementHandle.contentFrame(); + return { frame: frame ? FrameDispatcher.from(this._browserContextDispatcher(), frame) : void 0 }; + } + async generateLocatorString(params, metadata) { + return { value: await this._elementHandle.generateLocatorString() }; + } + async getAttribute(params, metadata) { + const value = await this._elementHandle.getAttribute(metadata, params.name); + return { value: value === null ? void 0 : value }; + } + async inputValue(params, metadata) { + const value = await this._elementHandle.inputValue(metadata); + return { value }; + } + async textContent(params, metadata) { + const value = await this._elementHandle.textContent(metadata); + return { value: value === null ? void 0 : value }; + } + async innerText(params, metadata) { + return { value: await this._elementHandle.innerText(metadata) }; + } + async innerHTML(params, metadata) { + return { value: await this._elementHandle.innerHTML(metadata) }; + } + async isChecked(params, metadata) { + return { value: await this._elementHandle.isChecked(metadata) }; + } + async isDisabled(params, metadata) { + return { value: await this._elementHandle.isDisabled(metadata) }; + } + async isEditable(params, metadata) { + return { value: await this._elementHandle.isEditable(metadata) }; + } + async isEnabled(params, metadata) { + return { value: await this._elementHandle.isEnabled(metadata) }; + } + async isHidden(params, metadata) { + return { value: await this._elementHandle.isHidden(metadata) }; + } + async isVisible(params, metadata) { + return { value: await this._elementHandle.isVisible(metadata) }; + } + async dispatchEvent(params, metadata) { + await this._elementHandle.dispatchEvent(metadata, params.type, parseArgument(params.eventInit)); + } + async scrollIntoViewIfNeeded(params, metadata) { + await this._elementHandle.scrollIntoViewIfNeeded(metadata, params); + } + async hover(params, metadata) { + return await this._elementHandle.hover(metadata, params); + } + async click(params, metadata) { + return await this._elementHandle.click(metadata, params); + } + async dblclick(params, metadata) { + return await this._elementHandle.dblclick(metadata, params); + } + async tap(params, metadata) { + return await this._elementHandle.tap(metadata, params); + } + async selectOption(params, metadata) { + const elements = (params.elements || []).map((e) => e._elementHandle); + return { values: await this._elementHandle.selectOption(metadata, elements, params.options || [], params) }; + } + async fill(params, metadata) { + return await this._elementHandle.fill(metadata, params.value, params); + } + async selectText(params, metadata) { + await this._elementHandle.selectText(metadata, params); + } + async setInputFiles(params, metadata) { + return await this._elementHandle.setInputFiles(metadata, params); + } + async focus(params, metadata) { + await this._elementHandle.focus(metadata); + } + async type(params, metadata) { + return await this._elementHandle.type(metadata, params.text, params); + } + async press(params, metadata) { + return await this._elementHandle.press(metadata, params.key, params); + } + async check(params, metadata) { + return await this._elementHandle.check(metadata, params); + } + async uncheck(params, metadata) { + return await this._elementHandle.uncheck(metadata, params); + } + async boundingBox(params, metadata) { + const value = await this._elementHandle.boundingBox(); + return { value: value || void 0 }; + } + async screenshot(params, metadata) { + const mask = (params.mask || []).map(({ frame, selector }) => ({ + frame: frame._object, + selector + })); + return { binary: await this._elementHandle.screenshot(metadata, { ...params, mask }) }; + } + async querySelector(params, metadata) { + const handle = await this._elementHandle.querySelector(params.selector, params); + return { element: ElementHandleDispatcher.fromNullable(this.parentScope(), handle) }; + } + async querySelectorAll(params, metadata) { + const elements = await this._elementHandle.querySelectorAll(params.selector); + return { elements: elements.map((e) => ElementHandleDispatcher.from(this.parentScope(), e)) }; + } + async evalOnSelector(params, metadata) { + return { value: serializeResult(await this._elementHandle.evalOnSelector(params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg))) }; + } + async evalOnSelectorAll(params, metadata) { + return { value: serializeResult(await this._elementHandle.evalOnSelectorAll(params.selector, params.expression, params.isFunction, parseArgument(params.arg))) }; + } + async waitForElementState(params, metadata) { + await this._elementHandle.waitForElementState(metadata, params.state, params); + } + async waitForSelector(params, metadata) { + return { element: ElementHandleDispatcher.fromNullable(this.parentScope(), await this._elementHandle.waitForSelector(metadata, params.selector, params)) }; + } + _browserContextDispatcher() { + const parentScope = this.parentScope().parentScope(); + if (parentScope instanceof BrowserContextDispatcher) + return parentScope; + return parentScope.parentScope(); + } +} +const source = ` +var __commonJS = obj => { + let required = false; + let result; + return function __require() { + if (!required) { + required = true; + let fn; + for (const name in obj) { fn = obj[name]; break; } + const module = { exports: {} }; + fn(module.exports, module); + result = module.exports; + } + return result; + } +}; +var __export = (target, all) => {for (var name in all) target[name] = all[name];}; +var __toESM = mod => ({ ...mod, 'default': mod }); +var __toCommonJS = mod => ({ ...mod, __esModule: true }); + + +// packages/injected/src/webSocketMock.ts +var webSocketMock_exports = {}; +__export(webSocketMock_exports, { + inject: () => inject +}); +module.exports = __toCommonJS(webSocketMock_exports); +function inject(globalThis) { + if (globalThis.__pwWebSocketDispatch) + return; + function generateId() { + const bytes = new Uint8Array(32); + globalThis.crypto.getRandomValues(bytes); + const hex = "0123456789abcdef"; + return [...bytes].map((value) => { + const high = Math.floor(value / 16); + const low = value % 16; + return hex[high] + hex[low]; + }).join(""); + } + function bufferToData(b) { + let s = ""; + for (let i = 0; i < b.length; i++) + s += String.fromCharCode(b[i]); + return { data: globalThis.btoa(s), isBase64: true }; + } + function stringToBuffer(s) { + s = globalThis.atob(s); + const b = new Uint8Array(s.length); + for (let i = 0; i < s.length; i++) + b[i] = s.charCodeAt(i); + return b.buffer; + } + function messageToData(message, cb) { + if (message instanceof globalThis.Blob) + return message.arrayBuffer().then((buffer) => cb(bufferToData(new Uint8Array(buffer)))); + if (typeof message === "string") + return cb({ data: message, isBase64: false }); + if (ArrayBuffer.isView(message)) + return cb(bufferToData(new Uint8Array(message.buffer, message.byteOffset, message.byteLength))); + return cb(bufferToData(new Uint8Array(message))); + } + function dataToMessage(data, binaryType) { + if (!data.isBase64) + return data.data; + const buffer = stringToBuffer(data.data); + return binaryType === "arraybuffer" ? buffer : new Blob([buffer]); + } + const binding = globalThis.__pwWebSocketBinding; + const NativeWebSocket = globalThis.WebSocket; + const idToWebSocket = /* @__PURE__ */ new Map(); + globalThis.__pwWebSocketDispatch = (request) => { + const ws = idToWebSocket.get(request.id); + if (!ws) + return; + if (request.type === "connect") + ws._apiConnect(); + if (request.type === "passthrough") + ws._apiPassThrough(); + if (request.type === "ensureOpened") + ws._apiEnsureOpened(); + if (request.type === "sendToPage") + ws._apiSendToPage(dataToMessage(request.data, ws.binaryType)); + if (request.type === "closePage") + ws._apiClosePage(request.code, request.reason, request.wasClean); + if (request.type === "sendToServer") + ws._apiSendToServer(dataToMessage(request.data, ws.binaryType)); + if (request.type === "closeServer") + ws._apiCloseServer(request.code, request.reason, request.wasClean); + }; + const _WebSocketMock = class _WebSocketMock extends EventTarget { + constructor(url, protocols) { + var _a, _b; + super(); + // WebSocket.CLOSED + this.CONNECTING = 0; + // WebSocket.CONNECTING + this.OPEN = 1; + // WebSocket.OPEN + this.CLOSING = 2; + // WebSocket.CLOSING + this.CLOSED = 3; + // WebSocket.CLOSED + this._oncloseListener = null; + this._onerrorListener = null; + this._onmessageListener = null; + this._onopenListener = null; + this.bufferedAmount = 0; + this.extensions = ""; + this.protocol = ""; + this.readyState = 0; + this._origin = ""; + this._passthrough = false; + this._wsBufferedMessages = []; + this._binaryType = "blob"; + this.url = new URL(url, globalThis.window.document.baseURI).href.replace(/^http/, "ws"); + this._origin = (_b = (_a = URL.parse(this.url)) == null ? void 0 : _a.origin) != null ? _b : ""; + this._protocols = protocols; + this._id = generateId(); + idToWebSocket.set(this._id, this); + binding({ type: "onCreate", id: this._id, url: this.url }); + } + // --- native WebSocket implementation --- + get binaryType() { + return this._binaryType; + } + set binaryType(type) { + this._binaryType = type; + if (this._ws) + this._ws.binaryType = type; + } + get onclose() { + return this._oncloseListener; + } + set onclose(listener) { + if (this._oncloseListener) + this.removeEventListener("close", this._oncloseListener); + this._oncloseListener = listener; + if (this._oncloseListener) + this.addEventListener("close", this._oncloseListener); + } + get onerror() { + return this._onerrorListener; + } + set onerror(listener) { + if (this._onerrorListener) + this.removeEventListener("error", this._onerrorListener); + this._onerrorListener = listener; + if (this._onerrorListener) + this.addEventListener("error", this._onerrorListener); + } + get onopen() { + return this._onopenListener; + } + set onopen(listener) { + if (this._onopenListener) + this.removeEventListener("open", this._onopenListener); + this._onopenListener = listener; + if (this._onopenListener) + this.addEventListener("open", this._onopenListener); + } + get onmessage() { + return this._onmessageListener; + } + set onmessage(listener) { + if (this._onmessageListener) + this.removeEventListener("message", this._onmessageListener); + this._onmessageListener = listener; + if (this._onmessageListener) + this.addEventListener("message", this._onmessageListener); + } + send(message) { + if (this.readyState === _WebSocketMock.CONNECTING) + throw new DOMException(\`Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.\`); + if (this.readyState !== _WebSocketMock.OPEN) + throw new DOMException(\`WebSocket is already in CLOSING or CLOSED state.\`); + if (this._passthrough) { + if (this._ws) + this._apiSendToServer(message); + } else { + messageToData(message, (data) => binding({ type: "onMessageFromPage", id: this._id, data })); + } + } + close(code, reason) { + if (code !== void 0 && code !== 1e3 && (code < 3e3 || code > 4999)) + throw new DOMException(\`Failed to execute 'close' on 'WebSocket': The close code must be either 1000, or between 3000 and 4999. \${code} is neither.\`); + if (this.readyState === _WebSocketMock.OPEN || this.readyState === _WebSocketMock.CONNECTING) + this.readyState = _WebSocketMock.CLOSING; + if (this._passthrough) + this._apiCloseServer(code, reason, true); + else + binding({ type: "onClosePage", id: this._id, code, reason, wasClean: true }); + } + // --- methods called from the routing API --- + _apiEnsureOpened() { + if (!this._ws) + this._ensureOpened(); + } + _apiSendToPage(message) { + this._ensureOpened(); + if (this.readyState !== _WebSocketMock.OPEN) + throw new DOMException(\`WebSocket is already in CLOSING or CLOSED state.\`); + this.dispatchEvent(new MessageEvent("message", { data: message, origin: this._origin, cancelable: true })); + } + _apiSendToServer(message) { + if (!this._ws) + throw new Error("Cannot send a message before connecting to the server"); + if (this._ws.readyState === _WebSocketMock.CONNECTING) + this._wsBufferedMessages.push(message); + else + this._ws.send(message); + } + _apiConnect() { + if (this._ws) + throw new Error("Can only connect to the server once"); + this._ws = new NativeWebSocket(this.url, this._protocols); + this._ws.binaryType = this._binaryType; + this._ws.onopen = () => { + for (const message of this._wsBufferedMessages) + this._ws.send(message); + this._wsBufferedMessages = []; + this._ensureOpened(); + }; + this._ws.onclose = (event) => { + this._onWSClose(event.code, event.reason, event.wasClean); + }; + this._ws.onmessage = (event) => { + if (this._passthrough) + this._apiSendToPage(event.data); + else + messageToData(event.data, (data) => binding({ type: "onMessageFromServer", id: this._id, data })); + }; + this._ws.onerror = () => { + const event = new Event("error", { cancelable: true }); + this.dispatchEvent(event); + }; + } + // This method connects to the server, and passes all messages through, + // as if WebSocketMock was not engaged. + _apiPassThrough() { + this._passthrough = true; + this._apiConnect(); + } + _apiCloseServer(code, reason, wasClean) { + if (!this._ws) { + this._onWSClose(code, reason, wasClean); + return; + } + if (this._ws.readyState === _WebSocketMock.CONNECTING || this._ws.readyState === _WebSocketMock.OPEN) + this._ws.close(code, reason); + } + _apiClosePage(code, reason, wasClean) { + if (this.readyState === _WebSocketMock.CLOSED) + return; + this.readyState = _WebSocketMock.CLOSED; + this.dispatchEvent(new CloseEvent("close", { code, reason, wasClean, cancelable: true })); + this._maybeCleanup(); + if (this._passthrough) + this._apiCloseServer(code, reason, wasClean); + else + binding({ type: "onClosePage", id: this._id, code, reason, wasClean }); + } + // --- internals --- + _ensureOpened() { + var _a; + if (this.readyState !== _WebSocketMock.CONNECTING) + return; + this.extensions = ((_a = this._ws) == null ? void 0 : _a.extensions) || ""; + if (this._ws) + this.protocol = this._ws.protocol; + else if (Array.isArray(this._protocols)) + this.protocol = this._protocols[0] || ""; + else + this.protocol = this._protocols || ""; + this.readyState = _WebSocketMock.OPEN; + this.dispatchEvent(new Event("open", { cancelable: true })); + } + _onWSClose(code, reason, wasClean) { + if (this._passthrough) + this._apiClosePage(code, reason, wasClean); + else + binding({ type: "onCloseServer", id: this._id, code, reason, wasClean }); + if (this._ws) { + this._ws.onopen = null; + this._ws.onclose = null; + this._ws.onmessage = null; + this._ws.onerror = null; + this._ws = void 0; + this._wsBufferedMessages = []; + } + this._maybeCleanup(); + } + _maybeCleanup() { + if (this.readyState === _WebSocketMock.CLOSED && !this._ws) + idToWebSocket.delete(this._id); + } + }; + _WebSocketMock.CONNECTING = 0; + // WebSocket.CONNECTING + _WebSocketMock.OPEN = 1; + // WebSocket.OPEN + _WebSocketMock.CLOSING = 2; + // WebSocket.CLOSING + _WebSocketMock.CLOSED = 3; + let WebSocketMock = _WebSocketMock; + globalThis.WebSocket = class WebSocket extends WebSocketMock { + }; +} +`; +const _WebSocketRouteDispatcher = class _WebSocketRouteDispatcher2 extends Dispatcher { + constructor(scope, id, url2, frame) { + super(scope, { guid: "webSocketRoute@" + createGuid() }, "WebSocketRoute", { url: url2 }); + this._type_WebSocketRoute = true; + this._id = id; + this._frame = frame; + this._eventListeners.push( + // When the frame navigates or detaches, there will be no more communication + // from the mock websocket, so pretend like it was closed. + eventsHelper.addEventListener(frame._page, Page$1.Events.InternalFrameNavigatedToNewDocument, (frame2) => { + if (frame2 === this._frame) + this._executionContextGone(); + }), + eventsHelper.addEventListener(frame._page, Page$1.Events.FrameDetached, (frame2) => { + if (frame2 === this._frame) + this._executionContextGone(); + }), + eventsHelper.addEventListener(frame._page, Page$1.Events.Close, () => this._executionContextGone()), + eventsHelper.addEventListener(frame._page, Page$1.Events.Crash, () => this._executionContextGone()) + ); + _WebSocketRouteDispatcher2._idToDispatcher.set(this._id, this); + scope._dispatchEvent("webSocketRoute", { webSocketRoute: this }); + } + static async installIfNeeded(connection, target) { + const kBindingName2 = "__pwWebSocketBinding"; + const context = target instanceof Page$1 ? target.browserContext : target; + if (!context.hasBinding(kBindingName2)) { + await context.exposeBinding(kBindingName2, false, (source2, payload) => { + if (payload.type === "onCreate") { + const contextDispatcher = connection.existingDispatcher(context); + const pageDispatcher = contextDispatcher ? PageDispatcher.fromNullable(contextDispatcher, source2.page) : void 0; + let scope; + if (pageDispatcher && matchesPattern(pageDispatcher, context._options.baseURL, payload.url)) + scope = pageDispatcher; + else if (contextDispatcher && matchesPattern(contextDispatcher, context._options.baseURL, payload.url)) + scope = contextDispatcher; + if (scope) { + new _WebSocketRouteDispatcher2(scope, payload.id, payload.url, source2.frame); + } else { + const request2 = { id: payload.id, type: "passthrough" }; + source2.frame.evaluateExpression(`globalThis.__pwWebSocketDispatch(${JSON.stringify(request2)})`).catch(() => { + }); + } + return; + } + const dispatcher = _WebSocketRouteDispatcher2._idToDispatcher.get(payload.id); + if (payload.type === "onMessageFromPage") + dispatcher == null ? void 0 : dispatcher._dispatchEvent("messageFromPage", { message: payload.data.data, isBase64: payload.data.isBase64 }); + if (payload.type === "onMessageFromServer") + dispatcher == null ? void 0 : dispatcher._dispatchEvent("messageFromServer", { message: payload.data.data, isBase64: payload.data.isBase64 }); + if (payload.type === "onClosePage") + dispatcher == null ? void 0 : dispatcher._dispatchEvent("closePage", { code: payload.code, reason: payload.reason, wasClean: payload.wasClean }); + if (payload.type === "onCloseServer") + dispatcher == null ? void 0 : dispatcher._dispatchEvent("closeServer", { code: payload.code, reason: payload.reason, wasClean: payload.wasClean }); + }); + } + const kInitScriptName = "webSocketMockSource"; + if (!target.initScripts.find((s) => s.name === kInitScriptName)) { + await target.addInitScript(` + (() => { + const module = {}; + ${source} + (module.exports.inject())(globalThis); + })(); + `, kInitScriptName); + } + } + async connect(params) { + await this._evaluateAPIRequest({ id: this._id, type: "connect" }); + } + async ensureOpened(params) { + await this._evaluateAPIRequest({ id: this._id, type: "ensureOpened" }); + } + async sendToPage(params) { + await this._evaluateAPIRequest({ id: this._id, type: "sendToPage", data: { data: params.message, isBase64: params.isBase64 } }); + } + async sendToServer(params) { + await this._evaluateAPIRequest({ id: this._id, type: "sendToServer", data: { data: params.message, isBase64: params.isBase64 } }); + } + async closePage(params) { + await this._evaluateAPIRequest({ id: this._id, type: "closePage", code: params.code, reason: params.reason, wasClean: params.wasClean }); + } + async closeServer(params) { + await this._evaluateAPIRequest({ id: this._id, type: "closeServer", code: params.code, reason: params.reason, wasClean: params.wasClean }); + } + async _evaluateAPIRequest(request2) { + await this._frame.evaluateExpression(`globalThis.__pwWebSocketDispatch(${JSON.stringify(request2)})`).catch(() => { + }); + } + _onDispose() { + _WebSocketRouteDispatcher2._idToDispatcher.delete(this._id); + } + _executionContextGone() { + if (!this._disposed) { + this._dispatchEvent("closePage", { wasClean: true }); + this._dispatchEvent("closeServer", { wasClean: true }); + } + } +}; +_WebSocketRouteDispatcher._idToDispatcher = /* @__PURE__ */ new Map(); +let WebSocketRouteDispatcher = _WebSocketRouteDispatcher; +function matchesPattern(dispatcher, baseURL, url2) { + for (const pattern of dispatcher._webSocketInterceptionPatterns || []) { + const urlMatch = pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags) : pattern.glob; + if (urlMatches(baseURL, url2, urlMatch, true)) + return true; + } + return false; +} +class PageDispatcher extends Dispatcher { + constructor(parentScope, page) { + var _a2; + const mainFrame = FrameDispatcher.from(parentScope, page.mainFrame()); + super(parentScope, page, "Page", { + mainFrame, + viewportSize: (_a2 = page.emulatedSize()) == null ? void 0 : _a2.viewport, + isClosed: page.isClosed(), + opener: PageDispatcher.fromNullable(parentScope, page.opener()) + }); + this._type_EventTarget = true; + this._type_Page = true; + this._subscriptions = /* @__PURE__ */ new Set(); + this._webSocketInterceptionPatterns = []; + this._bindings = []; + this._initScripts = []; + this._interceptionUrlMatchers = []; + this._locatorHandlers = /* @__PURE__ */ new Set(); + this._jsCoverageActive = false; + this._cssCoverageActive = false; + this.adopt(mainFrame); + this._page = page; + this._requestInterceptor = (route, request2) => { + const matchesSome = this._interceptionUrlMatchers.some((urlMatch) => urlMatches(this._page.browserContext._options.baseURL, request2.url(), urlMatch)); + if (!matchesSome) { + route.continue({ isFallback: true }).catch(() => { + }); + return; + } + this._dispatchEvent("route", { route: new RouteDispatcher(RequestDispatcher.from(this.parentScope(), request2), route) }); + }; + this.addObjectListener(Page$1.Events.Close, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + this.addObjectListener(Page$1.Events.Crash, () => this._dispatchEvent("crash")); + this.addObjectListener(Page$1.Events.Download, (download) => { + this._dispatchEvent("download", { url: download.url, suggestedFilename: download.suggestedFilename(), artifact: ArtifactDispatcher.from(parentScope, download.artifact) }); + }); + this.addObjectListener(Page$1.Events.EmulatedSizeChanged, () => { + var _a3; + return this._dispatchEvent("viewportSizeChanged", { viewportSize: (_a3 = page.emulatedSize()) == null ? void 0 : _a3.viewport }); + }); + this.addObjectListener(Page$1.Events.FileChooser, (fileChooser) => this._dispatchEvent("fileChooser", { + element: ElementHandleDispatcher.from(mainFrame, fileChooser.element()), + isMultiple: fileChooser.isMultiple() + })); + this.addObjectListener(Page$1.Events.FrameAttached, (frame) => this._onFrameAttached(frame)); + this.addObjectListener(Page$1.Events.FrameDetached, (frame) => this._onFrameDetached(frame)); + this.addObjectListener(Page$1.Events.LocatorHandlerTriggered, (uid) => this._dispatchEvent("locatorHandlerTriggered", { uid })); + this.addObjectListener(Page$1.Events.WebSocket, (webSocket) => this._dispatchEvent("webSocket", { webSocket: new WebSocketDispatcher(this, webSocket) })); + this.addObjectListener(Page$1.Events.Worker, (worker) => this._dispatchEvent("worker", { worker: new WorkerDispatcher(this, worker) })); + this.addObjectListener(Page$1.Events.Video, (artifact) => this._dispatchEvent("video", { artifact: ArtifactDispatcher.from(parentScope, artifact) })); + if (page.video) + this._dispatchEvent("video", { artifact: ArtifactDispatcher.from(this.parentScope(), page.video) }); + const frames = page.frameManager.frames(); + for (let i = 1; i < frames.length; i++) + this._onFrameAttached(frames[i]); + } + static from(parentScope, page) { + return PageDispatcher.fromNullable(parentScope, page); + } + static fromNullable(parentScope, page) { + if (!page) + return void 0; + const result = parentScope.connection.existingDispatcher(page); + return result || new PageDispatcher(parentScope, page); + } + page() { + return this._page; + } + async exposeBinding(params, metadata) { + const binding2 = await this._page.exposeBinding(params.name, !!params.needsHandle, (source2, ...args) => { + if (this._disposed) + return; + const binding22 = new BindingCallDispatcher(this, params.name, !!params.needsHandle, source2, args); + this._dispatchEvent("bindingCall", { binding: binding22 }); + return binding22.promise(); + }); + this._bindings.push(binding2); + } + async setExtraHTTPHeaders(params, metadata) { + await this._page.setExtraHTTPHeaders(params.headers); + } + async reload(params, metadata) { + return { response: ResponseDispatcher.fromNullable(this.parentScope(), await this._page.reload(metadata, params)) }; + } + async goBack(params, metadata) { + return { response: ResponseDispatcher.fromNullable(this.parentScope(), await this._page.goBack(metadata, params)) }; + } + async goForward(params, metadata) { + return { response: ResponseDispatcher.fromNullable(this.parentScope(), await this._page.goForward(metadata, params)) }; + } + async requestGC(params, metadata) { + await this._page.requestGC(); + } + async registerLocatorHandler(params, metadata) { + const uid = this._page.registerLocatorHandler(params.selector, params.noWaitAfter); + this._locatorHandlers.add(uid); + return { uid }; + } + async resolveLocatorHandlerNoReply(params, metadata) { + this._page.resolveLocatorHandler(params.uid, params.remove); + } + async unregisterLocatorHandler(params, metadata) { + this._page.unregisterLocatorHandler(params.uid); + this._locatorHandlers.delete(params.uid); + } + async emulateMedia(params, metadata) { + await this._page.emulateMedia({ + media: params.media, + colorScheme: params.colorScheme, + reducedMotion: params.reducedMotion, + forcedColors: params.forcedColors, + contrast: params.contrast + }); + } + async setViewportSize(params, metadata) { + await this._page.setViewportSize(params.viewportSize); + } + async addInitScript(params, metadata) { + this._initScripts.push(await this._page.addInitScript(params.source)); + } + async setNetworkInterceptionPatterns(params, metadata) { + const hadMatchers = this._interceptionUrlMatchers.length > 0; + if (!params.patterns.length) { + if (hadMatchers) + await this._page.removeRequestInterceptor(this._requestInterceptor); + this._interceptionUrlMatchers = []; + } else { + this._interceptionUrlMatchers = params.patterns.map((pattern) => pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags) : pattern.glob); + if (!hadMatchers) + await this._page.addRequestInterceptor(this._requestInterceptor); + } + } + async setWebSocketInterceptionPatterns(params, metadata) { + this._webSocketInterceptionPatterns = params.patterns; + if (params.patterns.length) + await WebSocketRouteDispatcher.installIfNeeded(this.connection, this._page); + } + async expectScreenshot(params, metadata) { + const mask = (params.mask || []).map(({ frame, selector }) => ({ + frame: frame._object, + selector + })); + const locator = params.locator ? { + frame: params.locator.frame._object, + selector: params.locator.selector + } : void 0; + return await this._page.expectScreenshot(metadata, { + ...params, + locator, + mask + }); + } + async screenshot(params, metadata) { + const mask = (params.mask || []).map(({ frame, selector }) => ({ + frame: frame._object, + selector + })); + return { binary: await this._page.screenshot(metadata, { ...params, mask }) }; + } + async close(params, metadata) { + if (!params.runBeforeUnload) + metadata.potentiallyClosesScope = true; + await this._page.close(metadata, params); + } + async updateSubscription(params) { + if (params.event === "fileChooser") + await this._page.setFileChooserInterceptedBy(params.enabled, this); + if (params.enabled) + this._subscriptions.add(params.event); + else + this._subscriptions.delete(params.event); + } + async keyboardDown(params, metadata) { + await this._page.keyboard.down(params.key); + } + async keyboardUp(params, metadata) { + await this._page.keyboard.up(params.key); + } + async keyboardInsertText(params, metadata) { + await this._page.keyboard.insertText(params.text); + } + async keyboardType(params, metadata) { + await this._page.keyboard.type(params.text, params); + } + async keyboardPress(params, metadata) { + await this._page.keyboard.press(params.key, params); + } + async mouseMove(params, metadata) { + await this._page.mouse.move(params.x, params.y, params, metadata); + } + async mouseDown(params, metadata) { + await this._page.mouse.down(params, metadata); + } + async mouseUp(params, metadata) { + await this._page.mouse.up(params, metadata); + } + async mouseClick(params, metadata) { + await this._page.mouse.click(params.x, params.y, params, metadata); + } + async mouseWheel(params, metadata) { + await this._page.mouse.wheel(params.deltaX, params.deltaY); + } + async touchscreenTap(params, metadata) { + await this._page.touchscreen.tap(params.x, params.y, metadata); + } + async accessibilitySnapshot(params, metadata) { + const rootAXNode = await this._page.accessibility.snapshot({ + interestingOnly: params.interestingOnly, + root: params.root ? params.root._elementHandle : void 0 + }); + return { rootAXNode: rootAXNode || void 0 }; + } + async pdf(params, metadata) { + if (!this._page.pdf) + throw new Error("PDF generation is only supported for Headless Chromium"); + const buffer2 = await this._page.pdf(params); + return { pdf: buffer2 }; + } + async snapshotForAI(params, metadata) { + return { snapshot: await this._page.snapshotForAI(metadata) }; + } + async bringToFront(params, metadata) { + await this._page.bringToFront(); + } + async startJSCoverage(params, metadata) { + this._jsCoverageActive = true; + const coverage = this._page.coverage; + await coverage.startJSCoverage(params); + } + async stopJSCoverage(params, metadata) { + const coverage = this._page.coverage; + const result = await coverage.stopJSCoverage(); + this._jsCoverageActive = false; + return result; + } + async startCSSCoverage(params, metadata) { + this._cssCoverageActive = true; + const coverage = this._page.coverage; + await coverage.startCSSCoverage(params); + } + async stopCSSCoverage(params, metadata) { + const coverage = this._page.coverage; + const result = await coverage.stopCSSCoverage(); + this._cssCoverageActive = false; + return result; + } + _onFrameAttached(frame) { + this._dispatchEvent("frameAttached", { frame: FrameDispatcher.from(this.parentScope(), frame) }); + } + _onFrameDetached(frame) { + this._dispatchEvent("frameDetached", { frame: FrameDispatcher.from(this.parentScope(), frame) }); + } + _onDispose() { + if (this._page.isClosedOrClosingOrCrashed()) + return; + this._interceptionUrlMatchers = []; + this._page.removeRequestInterceptor(this._requestInterceptor).catch(() => { + }); + this._page.removeExposedBindings(this._bindings).catch(() => { + }); + this._bindings = []; + this._page.removeInitScripts(this._initScripts).catch(() => { + }); + this._initScripts = []; + for (const uid of this._locatorHandlers) + this._page.unregisterLocatorHandler(uid); + this._locatorHandlers.clear(); + this._page.setFileChooserInterceptedBy(false, this).catch(() => { + }); + if (this._jsCoverageActive) + this._page.coverage.stopJSCoverage().catch(() => { + }); + this._jsCoverageActive = false; + if (this._cssCoverageActive) + this._page.coverage.stopCSSCoverage().catch(() => { + }); + this._cssCoverageActive = false; + } +} +class WorkerDispatcher extends Dispatcher { + constructor(scope, worker) { + super(scope, worker, "Worker", { + url: worker.url + }); + this._type_Worker = true; + this.addObjectListener(Worker$1.Events.Close, () => this._dispatchEvent("close")); + } + static fromNullable(scope, worker) { + if (!worker) + return void 0; + const result = scope.connection.existingDispatcher(worker); + return result || new WorkerDispatcher(scope, worker); + } + async evaluateExpression(params, metadata) { + return { value: serializeResult(await this._object.evaluateExpression(params.expression, params.isFunction, parseArgument(params.arg))) }; + } + async evaluateExpressionHandle(params, metadata) { + return { handle: JSHandleDispatcher.fromJSHandle(this, await this._object.evaluateExpressionHandle(params.expression, params.isFunction, parseArgument(params.arg))) }; + } +} +class BindingCallDispatcher extends Dispatcher { + constructor(scope, name, needsHandle, source2, args) { + const frameDispatcher = FrameDispatcher.from(scope.parentScope(), source2.frame); + super(scope, { guid: "bindingCall@" + createGuid() }, "BindingCall", { + frame: frameDispatcher, + name, + args: needsHandle ? void 0 : args.map(serializeResult), + handle: needsHandle ? ElementHandleDispatcher.fromJSOrElementHandle(frameDispatcher, args[0]) : void 0 + }); + this._type_BindingCall = true; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + promise() { + return this._promise; + } + async resolve(params, metadata) { + this._resolve(parseArgument(params.result)); + this._dispose(); + } + async reject(params, metadata) { + this._reject(parseError$1(params.error)); + this._dispose(); + } +} +class DialogDispatcher extends Dispatcher { + constructor(scope, dialog) { + const page = PageDispatcher.fromNullable(scope, dialog.page().initializedOrUndefined()); + super(page || scope, dialog, "Dialog", { + page, + type: dialog.type(), + message: dialog.message(), + defaultValue: dialog.defaultValue() + }); + this._type_Dialog = true; + } + async accept(params) { + await this._object.accept(params.promptText); + } + async dismiss() { + await this._object.dismiss(); + } +} +let Download$1 = class Download { + constructor(page, downloadsPath, uuid, url2, suggestedFilename) { + const unaccessibleErrorMessage = page.browserContext._options.acceptDownloads === "deny" ? "Pass { acceptDownloads: true } when you are creating your browser context." : void 0; + this.artifact = new Artifact$1(page, path.join(downloadsPath, uuid), unaccessibleErrorMessage, () => { + return this._page.browserContext.cancelDownload(uuid); + }); + this._page = page; + this.url = url2; + this._suggestedFilename = suggestedFilename; + page.browserContext._downloads.add(this); + if (suggestedFilename !== void 0) + this._fireDownloadEvent(); + } + page() { + return this._page; + } + _filenameSuggested(suggestedFilename) { + assert(this._suggestedFilename === void 0); + this._suggestedFilename = suggestedFilename; + this._fireDownloadEvent(); + } + suggestedFilename() { + return this._suggestedFilename; + } + _fireDownloadEvent() { + this._page.instrumentation.onDownload(this._page, this); + this._page.emit(Page$1.Events.Download, this); + } +}; +let Browser$1 = (_h = class extends SdkObject { + constructor(parent, options2) { + super(parent, "browser"); + this._downloads = /* @__PURE__ */ new Map(); + this._defaultContext = null; + this._startedClosing = false; + this._idToVideo = /* @__PURE__ */ new Map(); + this._isCollocatedWithServer = true; + this.attribution.browser = this; + this.options = options2; + this.instrumentation.onBrowserOpen(this); + } + async newContext(metadata, options2) { + var _a2; + validateBrowserContextOptions(options2, this.options); + let clientCertificatesProxy; + if ((_a2 = options2.clientCertificates) == null ? void 0 : _a2.length) { + clientCertificatesProxy = new ClientCertificatesProxy(options2); + options2 = { ...options2 }; + options2.proxyOverride = await clientCertificatesProxy.listen(); + options2.internalIgnoreHTTPSErrors = true; + } + let context; + try { + context = await this.doCreateNewContext(options2); + } catch (error2) { + await (clientCertificatesProxy == null ? void 0 : clientCertificatesProxy.close()); + throw error2; + } + context._clientCertificatesProxy = clientCertificatesProxy; + if (options2.storageState) + await context.setStorageState(metadata, options2.storageState); + this.emit(_h.Events.Context, context); + return context; + } + async newContextForReuse(params, metadata) { + const hash2 = BrowserContext$1.reusableContextHash(params); + if (!this._contextForReuse || hash2 !== this._contextForReuse.hash || !this._contextForReuse.context.canResetForReuse()) { + if (this._contextForReuse) + await this._contextForReuse.context.close({ reason: "Context reused" }); + this._contextForReuse = { context: await this.newContext(metadata, params), hash: hash2 }; + return { context: this._contextForReuse.context, needsReset: false }; + } + await this._contextForReuse.context.stopPendingOperations("Context recreated"); + return { context: this._contextForReuse.context, needsReset: true }; + } + async stopPendingOperations(reason) { + var _a2, _b2; + await ((_b2 = (_a2 = this._contextForReuse) == null ? void 0 : _a2.context) == null ? void 0 : _b2.stopPendingOperations(reason)); + } + _downloadCreated(page, uuid, url2, suggestedFilename) { + const download = new Download$1(page, this.options.downloadsPath || "", uuid, url2, suggestedFilename); + this._downloads.set(uuid, download); + } + _downloadFilenameSuggested(uuid, suggestedFilename) { + const download = this._downloads.get(uuid); + if (!download) + return; + download._filenameSuggested(suggestedFilename); + } + _downloadFinished(uuid, error2) { + const download = this._downloads.get(uuid); + if (!download) + return; + download.artifact.reportFinished(error2 ? new Error(error2) : void 0); + this._downloads.delete(uuid); + } + _videoStarted(context, videoId, path2, pageOrError) { + const artifact = new Artifact$1(context, path2); + this._idToVideo.set(videoId, { context, artifact }); + pageOrError.then((page) => { + if (page instanceof Page$1) { + page.video = artifact; + page.emitOnContext(BrowserContext$1.Events.VideoStarted, artifact); + page.emit(Page$1.Events.Video, artifact); + } + }); + } + _takeVideo(videoId) { + const video = this._idToVideo.get(videoId); + this._idToVideo.delete(videoId); + return video == null ? void 0 : video.artifact; + } + _didClose() { + for (const context of this.contexts()) + context._browserClosed(); + if (this._defaultContext) + this._defaultContext._browserClosed(); + this.emit(_h.Events.Disconnected); + this.instrumentation.onBrowserClose(this); + } + async close(options2) { + if (!this._startedClosing) { + if (options2.reason) + this._closeReason = options2.reason; + this._startedClosing = true; + await this.options.browserProcess.close(); + } + if (this.isConnected()) + await new Promise((x) => this.once(_h.Events.Disconnected, x)); + } + async killForTests() { + await this.options.browserProcess.kill(); + } +}, _h.Events = { + Context: "context", + Disconnected: "disconnected" +}, _h); +async function getAccessibilityTree$2(client, needle) { + const { nodes } = await client.send("Accessibility.getFullAXTree"); + const tree = CRAXNode.createTree(client, nodes); + return { + tree, + needle: needle ? await tree._findElement(needle) : null + }; +} +class CRAXNode { + constructor(client, payload) { + this._children = []; + this._richlyEditable = false; + this._editable = false; + this._focusable = false; + this._expanded = false; + this._hidden = false; + this._client = client; + this._payload = payload; + this._name = this._payload.name ? this._payload.name.value : ""; + this._role = this._payload.role ? this._payload.role.value : "Unknown"; + for (const property of this._payload.properties || []) { + if (property.name === "editable") { + this._richlyEditable = property.value.value === "richtext"; + this._editable = true; + } + if (property.name === "focusable") + this._focusable = property.value.value; + if (property.name === "expanded") + this._expanded = property.value.value; + if (property.name === "hidden") + this._hidden = property.value.value; + } + } + _isPlainTextField() { + if (this._richlyEditable) + return false; + if (this._editable) + return true; + return this._role === "textbox" || this._role === "ComboBox" || this._role === "searchbox"; + } + _isTextOnlyObject() { + const role = this._role; + return role === "LineBreak" || role === "text" || role === "InlineTextBox" || role === "StaticText"; + } + _hasFocusableChild() { + if (this._cachedHasFocusableChild === void 0) { + this._cachedHasFocusableChild = false; + for (const child of this._children) { + if (child._focusable || child._hasFocusableChild()) { + this._cachedHasFocusableChild = true; + break; + } + } + } + return this._cachedHasFocusableChild; + } + children() { + return this._children; + } + async _findElement(element) { + const objectId = element._objectId; + const { node: { backendNodeId } } = await this._client.send("DOM.describeNode", { objectId }); + const needle = this.find((node2) => node2._payload.backendDOMNodeId === backendNodeId); + return needle || null; + } + find(predicate) { + if (predicate(this)) + return this; + for (const child of this._children) { + const result = child.find(predicate); + if (result) + return result; + } + return null; + } + isLeafNode() { + if (!this._children.length) + return true; + if (this._isPlainTextField() || this._isTextOnlyObject()) + return true; + switch (this._role) { + case "doc-cover": + case "graphics-symbol": + case "img": + case "Meter": + case "scrollbar": + case "slider": + case "separator": + case "progressbar": + return true; + } + if (this._hasFocusableChild()) + return false; + if (this._focusable && this._role !== "WebArea" && this._role !== "RootWebArea" && this._name) + return true; + if (this._role === "heading" && this._name) + return true; + return false; + } + isControl() { + switch (this._role) { + case "button": + case "checkbox": + case "ColorWell": + case "combobox": + case "DisclosureTriangle": + case "listbox": + case "menu": + case "menubar": + case "menuitem": + case "menuitemcheckbox": + case "menuitemradio": + case "radio": + case "scrollbar": + case "searchbox": + case "slider": + case "spinbutton": + case "switch": + case "tab": + case "textbox": + case "tree": + return true; + default: + return false; + } + } + isInteresting(insideControl) { + const role = this._role; + if (role === "Ignored" || this._hidden) + return false; + if (this._focusable || this._richlyEditable) + return true; + if (this.isControl()) + return true; + if (insideControl) + return false; + return this.isLeafNode() && !!this._name; + } + normalizedRole() { + switch (this._role) { + case "RootWebArea": + return "WebArea"; + case "StaticText": + return "text"; + default: + return this._role; + } + } + serialize() { + const properties = /* @__PURE__ */ new Map(); + for (const property of this._payload.properties || []) + properties.set(property.name.toLowerCase(), property.value.value); + if (this._payload.description) + properties.set("description", this._payload.description.value); + const node2 = { + role: this.normalizedRole(), + name: this._payload.name ? this._payload.name.value || "" : "" + }; + const userStringProperties = [ + "description", + "keyshortcuts", + "roledescription", + "valuetext" + ]; + for (const userStringProperty of userStringProperties) { + if (!properties.has(userStringProperty)) + continue; + node2[userStringProperty] = properties.get(userStringProperty); + } + const booleanProperties = [ + "disabled", + "expanded", + "focused", + "modal", + "multiline", + "multiselectable", + "readonly", + "required", + "selected" + ]; + for (const booleanProperty of booleanProperties) { + if (booleanProperty === "focused" && (this._role === "WebArea" || this._role === "RootWebArea")) + continue; + const value = properties.get(booleanProperty); + if (!value) + continue; + node2[booleanProperty] = value; + } + const numericalProperties = [ + "level", + "valuemax", + "valuemin" + ]; + for (const numericalProperty of numericalProperties) { + if (!properties.has(numericalProperty)) + continue; + node2[numericalProperty] = properties.get(numericalProperty); + } + const tokenProperties = [ + "autocomplete", + "haspopup", + "invalid", + "orientation" + ]; + for (const tokenProperty of tokenProperties) { + const value = properties.get(tokenProperty); + if (!value || value === "false") + continue; + node2[tokenProperty] = value; + } + const axNode = node2; + if (this._payload.value) { + if (typeof this._payload.value.value === "string") + axNode.valueString = this._payload.value.value; + if (typeof this._payload.value.value === "number") + axNode.valueNumber = this._payload.value.value; + } + if (properties.has("checked")) + axNode.checked = properties.get("checked") === "true" ? "checked" : properties.get("checked") === "false" ? "unchecked" : "mixed"; + if (properties.has("pressed")) + axNode.pressed = properties.get("pressed") === "true" ? "pressed" : properties.get("pressed") === "false" ? "released" : "mixed"; + return axNode; + } + static createTree(client, payloads) { + const nodeById = /* @__PURE__ */ new Map(); + for (const payload of payloads) + nodeById.set(payload.nodeId, new CRAXNode(client, payload)); + for (const node2 of nodeById.values()) { + for (const childId of node2._payload.childIds || []) + node2._children.push(nodeById.get(childId)); + } + return nodeById.values().next().value; + } +} +class CRCoverage { + constructor(client) { + this._jsCoverage = new JSCoverage(client); + this._cssCoverage = new CSSCoverage(client); + } + async startJSCoverage(options2) { + return await this._jsCoverage.start(options2); + } + async stopJSCoverage() { + return await this._jsCoverage.stop(); + } + async startCSSCoverage(options2) { + return await this._cssCoverage.start(options2); + } + async stopCSSCoverage() { + return await this._cssCoverage.stop(); + } +} +class JSCoverage { + constructor(client) { + this._reportAnonymousScripts = false; + this._client = client; + this._enabled = false; + this._scriptIds = /* @__PURE__ */ new Set(); + this._scriptSources = /* @__PURE__ */ new Map(); + this._eventListeners = []; + this._resetOnNavigation = false; + } + async start(options2) { + assert(!this._enabled, "JSCoverage is already enabled"); + const { + resetOnNavigation = true, + reportAnonymousScripts = false + } = options2; + this._resetOnNavigation = resetOnNavigation; + this._reportAnonymousScripts = reportAnonymousScripts; + this._enabled = true; + this._scriptIds.clear(); + this._scriptSources.clear(); + this._eventListeners = [ + eventsHelper.addEventListener(this._client, "Debugger.scriptParsed", this._onScriptParsed.bind(this)), + eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", this._onExecutionContextsCleared.bind(this)), + eventsHelper.addEventListener(this._client, "Debugger.paused", this._onDebuggerPaused.bind(this)) + ]; + await Promise.all([ + this._client.send("Profiler.enable"), + this._client.send("Profiler.startPreciseCoverage", { callCount: true, detailed: true }), + this._client.send("Debugger.enable"), + this._client.send("Debugger.setSkipAllPauses", { skip: true }) + ]); + } + _onDebuggerPaused() { + this._client.send("Debugger.resume"); + } + _onExecutionContextsCleared() { + if (!this._resetOnNavigation) + return; + this._scriptIds.clear(); + this._scriptSources.clear(); + } + async _onScriptParsed(event) { + this._scriptIds.add(event.scriptId); + if (!event.url && !this._reportAnonymousScripts) + return; + const response2 = await this._client._sendMayFail("Debugger.getScriptSource", { scriptId: event.scriptId }); + if (response2) + this._scriptSources.set(event.scriptId, response2.scriptSource); + } + async stop() { + if (!this._enabled) + return { entries: [] }; + const [profileResponse] = await Promise.all([ + this._client.send("Profiler.takePreciseCoverage"), + this._client.send("Profiler.stopPreciseCoverage"), + this._client.send("Profiler.disable"), + this._client.send("Debugger.disable") + ]); + eventsHelper.removeEventListeners(this._eventListeners); + this._enabled = false; + const coverage = { entries: [] }; + for (const entry of profileResponse.result) { + if (!this._scriptIds.has(entry.scriptId)) + continue; + if (!entry.url && !this._reportAnonymousScripts) + continue; + const source2 = this._scriptSources.get(entry.scriptId); + if (source2) + coverage.entries.push({ ...entry, source: source2 }); + else + coverage.entries.push(entry); + } + return coverage; + } +} +class CSSCoverage { + constructor(client) { + this._client = client; + this._enabled = false; + this._stylesheetURLs = /* @__PURE__ */ new Map(); + this._stylesheetSources = /* @__PURE__ */ new Map(); + this._eventListeners = []; + this._resetOnNavigation = false; + } + async start(options2) { + assert(!this._enabled, "CSSCoverage is already enabled"); + const { resetOnNavigation = true } = options2; + this._resetOnNavigation = resetOnNavigation; + this._enabled = true; + this._stylesheetURLs.clear(); + this._stylesheetSources.clear(); + this._eventListeners = [ + eventsHelper.addEventListener(this._client, "CSS.styleSheetAdded", this._onStyleSheet.bind(this)), + eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", this._onExecutionContextsCleared.bind(this)) + ]; + await Promise.all([ + this._client.send("DOM.enable"), + this._client.send("CSS.enable"), + this._client.send("CSS.startRuleUsageTracking") + ]); + } + _onExecutionContextsCleared() { + if (!this._resetOnNavigation) + return; + this._stylesheetURLs.clear(); + this._stylesheetSources.clear(); + } + async _onStyleSheet(event) { + const header = event.header; + if (!header.sourceURL) + return; + const response2 = await this._client._sendMayFail("CSS.getStyleSheetText", { styleSheetId: header.styleSheetId }); + if (response2) { + this._stylesheetURLs.set(header.styleSheetId, header.sourceURL); + this._stylesheetSources.set(header.styleSheetId, response2.text); + } + } + async stop() { + if (!this._enabled) + return { entries: [] }; + const ruleTrackingResponse = await this._client.send("CSS.stopRuleUsageTracking"); + await Promise.all([ + this._client.send("CSS.disable"), + this._client.send("DOM.disable") + ]); + eventsHelper.removeEventListeners(this._eventListeners); + this._enabled = false; + const styleSheetIdToCoverage = /* @__PURE__ */ new Map(); + for (const entry of ruleTrackingResponse.ruleUsage) { + let ranges = styleSheetIdToCoverage.get(entry.styleSheetId); + if (!ranges) { + ranges = []; + styleSheetIdToCoverage.set(entry.styleSheetId, ranges); + } + ranges.push({ + startOffset: entry.startOffset, + endOffset: entry.endOffset, + count: entry.used ? 1 : 0 + }); + } + const coverage = { entries: [] }; + for (const styleSheetId of this._stylesheetURLs.keys()) { + const url2 = this._stylesheetURLs.get(styleSheetId); + const text = this._stylesheetSources.get(styleSheetId); + const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []); + coverage.entries.push({ url: url2, ranges, text }); + } + return coverage; + } +} +function convertToDisjointRanges(nestedRanges) { + const points = []; + for (const range2 of nestedRanges) { + points.push({ offset: range2.startOffset, type: 0, range: range2 }); + points.push({ offset: range2.endOffset, type: 1, range: range2 }); + } + points.sort((a, b) => { + if (a.offset !== b.offset) + return a.offset - b.offset; + if (a.type !== b.type) + return b.type - a.type; + const aLength = a.range.endOffset - a.range.startOffset; + const bLength = b.range.endOffset - b.range.startOffset; + if (a.type === 0) + return bLength - aLength; + return aLength - bLength; + }); + const hitCountStack = []; + const results = []; + let lastOffset = 0; + for (const point of points) { + if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) { + const lastResult = results.length ? results[results.length - 1] : null; + if (lastResult && lastResult.end === lastOffset) + lastResult.end = point.offset; + else + results.push({ start: lastOffset, end: point.offset }); + } + lastOffset = point.offset; + if (point.type === 0) + hitCountStack.push(point.range.count); + else + hitCountStack.pop(); + } + return results.filter((range2) => range2.end - range2.start > 1); +} +function getExceptionMessage(exceptionDetails) { + if (exceptionDetails.exception) + return exceptionDetails.exception.description || String(exceptionDetails.exception.value); + let message = exceptionDetails.text; + if (exceptionDetails.stackTrace) { + for (const callframe of exceptionDetails.stackTrace.callFrames) { + const location2 = callframe.url + ":" + callframe.lineNumber + ":" + callframe.columnNumber; + const functionName = callframe.functionName || ""; + message += ` + at ${functionName} (${location2})`; + } + } + return message; +} +async function releaseObject(client, objectId) { + await client.send("Runtime.releaseObject", { objectId }).catch((error2) => { + }); +} +async function saveProtocolStream(client, handle, path2) { + let eof = false; + await mkdirIfNeeded$1(path2); + const fd = await fs.promises.open(path2, "w"); + while (!eof) { + const response2 = await client.send("IO.read", { handle }); + eof = response2.eof; + const buf = Buffer.from(response2.data, response2.base64Encoded ? "base64" : void 0); + await fd.write(buf); + } + await fd.close(); + await client.send("IO.close", { handle }); +} +async function readProtocolStream(client, handle) { + let eof = false; + const chunks = []; + while (!eof) { + const response2 = await client.send("IO.read", { handle }); + eof = response2.eof; + const buf = Buffer.from(response2.data, response2.base64Encoded ? "base64" : void 0); + chunks.push(buf); + } + await client.send("IO.close", { handle }); + return Buffer.concat(chunks); +} +function toConsoleMessageLocation(stackTrace) { + return stackTrace && stackTrace.callFrames.length ? { + url: stackTrace.callFrames[0].url, + lineNumber: stackTrace.callFrames[0].lineNumber, + columnNumber: stackTrace.callFrames[0].columnNumber + } : { url: "", lineNumber: 0, columnNumber: 0 }; +} +function exceptionToError(exceptionDetails) { + var _a2, _b2; + const messageWithStack = getExceptionMessage(exceptionDetails); + const lines = messageWithStack.split("\n"); + const firstStackTraceLine = lines.findIndex((line) => line.startsWith(" at")); + let messageWithName = ""; + let stack = ""; + if (firstStackTraceLine === -1) { + messageWithName = messageWithStack; + } else { + messageWithName = lines.slice(0, firstStackTraceLine).join("\n"); + stack = messageWithStack; + } + const { name, message } = splitErrorMessage(messageWithName); + const err = new Error(message); + err.stack = stack; + const nameOverride = (_b2 = (_a2 = exceptionDetails.exception) == null ? void 0 : _a2.preview) == null ? void 0 : _b2.properties.find((o) => o.name === "name"); + err.name = nameOverride ? nameOverride.value ?? "Error" : name; + return err; +} +function toModifiersMask$2(modifiers) { + let mask = 0; + if (modifiers.has("Alt")) + mask |= 1; + if (modifiers.has("Control")) + mask |= 2; + if (modifiers.has("Meta")) + mask |= 4; + if (modifiers.has("Shift")) + mask |= 8; + return mask; +} +function toButtonsMask$2(buttons) { + let mask = 0; + if (buttons.has("left")) + mask |= 1; + if (buttons.has("right")) + mask |= 2; + if (buttons.has("middle")) + mask |= 4; + return mask; +} +class DragManager { + constructor(page) { + this._dragState = null; + this._lastPosition = { x: 0, y: 0 }; + this._crPage = page; + } + async cancelDrag() { + if (!this._dragState) + return false; + await this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "dragCancel", + x: this._lastPosition.x, + y: this._lastPosition.y, + data: { + items: [], + dragOperationsMask: 65535 + } + }); + this._dragState = null; + return true; + } + async interceptDragCausedByMove(x, y, button, buttons, modifiers, moveCallback) { + this._lastPosition = { x, y }; + if (this._dragState) { + await this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "dragOver", + x, + y, + data: this._dragState, + modifiers: toModifiersMask$2(modifiers) + }); + return; + } + if (button !== "left") + return moveCallback(); + const client = this._crPage._mainFrameSession._client; + let onDragIntercepted; + const dragInterceptedPromise = new Promise((x2) => onDragIntercepted = x2); + function setupDragListeners() { + let didStartDrag = Promise.resolve(false); + let dragEvent = null; + const dragListener = (event) => dragEvent = event; + const mouseListener = () => { + didStartDrag = new Promise((callback) => { + window.addEventListener("dragstart", dragListener, { once: true, capture: true }); + setTimeout(() => callback(dragEvent ? !dragEvent.defaultPrevented : false), 0); + }); + }; + window.addEventListener("mousemove", mouseListener, { once: true, capture: true }); + window.__cleanupDrag = async () => { + const val = await didStartDrag; + window.removeEventListener("mousemove", mouseListener, { capture: true }); + window.removeEventListener("dragstart", dragListener, { capture: true }); + delete window.__cleanupDrag; + return val; + }; + } + await this._crPage._page.safeNonStallingEvaluateInAllFrames(`(${setupDragListeners.toString()})()`, "utility"); + client.on("Input.dragIntercepted", onDragIntercepted); + try { + await client.send("Input.setInterceptDrags", { enabled: true }); + } catch { + client.off("Input.dragIntercepted", onDragIntercepted); + return moveCallback(); + } + await moveCallback(); + const expectingDrag = (await Promise.all(this._crPage._page.frames().map(async (frame) => { + return frame.nonStallingEvaluateInExistingContext("window.__cleanupDrag && window.__cleanupDrag()", "utility").catch(() => false); + }))).some((x2) => x2); + this._dragState = expectingDrag ? (await dragInterceptedPromise).data : null; + client.off("Input.dragIntercepted", onDragIntercepted); + await client.send("Input.setInterceptDrags", { enabled: false }); + if (this._dragState) { + await this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "dragEnter", + x, + y, + data: this._dragState, + modifiers: toModifiersMask$2(modifiers) + }); + } + } + isDragging() { + return !!this._dragState; + } + async drop(x, y, modifiers) { + assert(this._dragState, "missing drag state"); + await this._crPage._mainFrameSession._client.send("Input.dispatchDragEvent", { + type: "drop", + x, + y, + data: this._dragState, + modifiers: toModifiersMask$2(modifiers) + }); + this._dragState = null; + } +} +class CRExecutionContext { + constructor(client, contextPayload) { + this._client = client; + this._contextId = contextPayload.id; + } + async rawEvaluateJSON(expression) { + const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.evaluate", { + expression, + contextId: this._contextId, + returnByValue: true + }).catch(rewriteError$2); + if (exceptionDetails) + throw new JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); + return remoteObject.value; + } + async rawEvaluateHandle(context, expression) { + const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.evaluate", { + expression, + contextId: this._contextId + }).catch(rewriteError$2); + if (exceptionDetails) + throw new JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); + return createHandle$3(context, remoteObject); + } + async evaluateWithArguments(expression, returnByValue, utilityScript, values, handles) { + const { exceptionDetails, result: remoteObject } = await this._client.send("Runtime.callFunctionOn", { + functionDeclaration: expression, + objectId: utilityScript._objectId, + arguments: [ + { objectId: utilityScript._objectId }, + ...values.map((value) => ({ value })), + ...handles.map((handle) => ({ objectId: handle._objectId })) + ], + returnByValue, + awaitPromise: true, + userGesture: true + }).catch(rewriteError$2); + if (exceptionDetails) + throw new JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); + return returnByValue ? parseEvaluationResultValue(remoteObject.value) : createHandle$3(utilityScript._context, remoteObject); + } + async getProperties(object) { + const response2 = await this._client.send("Runtime.getProperties", { + objectId: object._objectId, + ownProperties: true + }); + const result = /* @__PURE__ */ new Map(); + for (const property of response2.result) { + if (!property.enumerable || !property.value) + continue; + result.set(property.name, createHandle$3(object._context, property.value)); + } + return result; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await releaseObject(this._client, handle._objectId); + } +} +function rewriteError$2(error2) { + if (error2.message.includes("Object reference chain is too long")) + throw new Error("Cannot serialize result: object reference chain is too long."); + if (error2.message.includes("Object couldn't be returned by value")) + return { result: { type: "undefined" } }; + if (error2 instanceof TypeError && error2.message.startsWith("Converting circular structure to JSON")) + rewriteErrorMessage(error2, error2.message + " Are you passing a nested JSHandle?"); + if (!isJavaScriptErrorInEvaluate(error2) && !isSessionClosedError(error2)) + throw new Error("Execution context was destroyed, most likely because of a navigation."); + throw error2; +} +function potentiallyUnserializableValue$2(remoteObject) { + const value = remoteObject.value; + const unserializableValue = remoteObject.unserializableValue; + return unserializableValue ? parseUnserializableValue(unserializableValue) : value; +} +function renderPreview$3(object) { + if (object.type === "undefined") + return "undefined"; + if ("value" in object) + return String(object.value); + if (object.unserializableValue) + return String(object.unserializableValue); + if (object.description === "Object" && object.preview) { + const tokens = []; + for (const { name, value } of object.preview.properties) + tokens.push(`${name}: ${value}`); + return `{${tokens.join(", ")}}`; + } + if (object.subtype === "array" && object.preview) + return sparseArrayToString(object.preview.properties); + return object.description; +} +function createHandle$3(context, remoteObject) { + if (remoteObject.subtype === "node") { + assert(context instanceof FrameExecutionContext); + return new ElementHandle$1(context, remoteObject.objectId); + } + return new JSHandle$1(context, remoteObject.subtype || remoteObject.type, renderPreview$3(remoteObject), remoteObject.objectId, potentiallyUnserializableValue$2(remoteObject)); +} +const macEditingCommands = { + "Backspace": "deleteBackward:", + "Enter": "insertNewline:", + "NumpadEnter": "insertNewline:", + "Escape": "cancelOperation:", + "ArrowUp": "moveUp:", + "ArrowDown": "moveDown:", + "ArrowLeft": "moveLeft:", + "ArrowRight": "moveRight:", + "F5": "complete:", + "Delete": "deleteForward:", + "Home": "scrollToBeginningOfDocument:", + "End": "scrollToEndOfDocument:", + "PageUp": "scrollPageUp:", + "PageDown": "scrollPageDown:", + "Shift+Backspace": "deleteBackward:", + "Shift+Enter": "insertNewline:", + "Shift+NumpadEnter": "insertNewline:", + "Shift+Escape": "cancelOperation:", + "Shift+ArrowUp": "moveUpAndModifySelection:", + "Shift+ArrowDown": "moveDownAndModifySelection:", + "Shift+ArrowLeft": "moveLeftAndModifySelection:", + "Shift+ArrowRight": "moveRightAndModifySelection:", + "Shift+F5": "complete:", + "Shift+Delete": "deleteForward:", + "Shift+Home": "moveToBeginningOfDocumentAndModifySelection:", + "Shift+End": "moveToEndOfDocumentAndModifySelection:", + "Shift+PageUp": "pageUpAndModifySelection:", + "Shift+PageDown": "pageDownAndModifySelection:", + "Shift+Numpad5": "delete:", + "Control+Tab": "selectNextKeyView:", + "Control+Enter": "insertLineBreak:", + "Control+NumpadEnter": "insertLineBreak:", + "Control+Quote": "insertSingleQuoteIgnoringSubstitution:", + "Control+KeyA": "moveToBeginningOfParagraph:", + "Control+KeyB": "moveBackward:", + "Control+KeyD": "deleteForward:", + "Control+KeyE": "moveToEndOfParagraph:", + "Control+KeyF": "moveForward:", + "Control+KeyH": "deleteBackward:", + "Control+KeyK": "deleteToEndOfParagraph:", + "Control+KeyL": "centerSelectionInVisibleArea:", + "Control+KeyN": "moveDown:", + "Control+KeyO": ["insertNewlineIgnoringFieldEditor:", "moveBackward:"], + "Control+KeyP": "moveUp:", + "Control+KeyT": "transpose:", + "Control+KeyV": "pageDown:", + "Control+KeyY": "yank:", + "Control+Backspace": "deleteBackwardByDecomposingPreviousCharacter:", + "Control+ArrowUp": "scrollPageUp:", + "Control+ArrowDown": "scrollPageDown:", + "Control+ArrowLeft": "moveToLeftEndOfLine:", + "Control+ArrowRight": "moveToRightEndOfLine:", + "Shift+Control+Enter": "insertLineBreak:", + "Shift+Control+NumpadEnter": "insertLineBreak:", + "Shift+Control+Tab": "selectPreviousKeyView:", + "Shift+Control+Quote": "insertDoubleQuoteIgnoringSubstitution:", + "Shift+Control+KeyA": "moveToBeginningOfParagraphAndModifySelection:", + "Shift+Control+KeyB": "moveBackwardAndModifySelection:", + "Shift+Control+KeyE": "moveToEndOfParagraphAndModifySelection:", + "Shift+Control+KeyF": "moveForwardAndModifySelection:", + "Shift+Control+KeyN": "moveDownAndModifySelection:", + "Shift+Control+KeyP": "moveUpAndModifySelection:", + "Shift+Control+KeyV": "pageDownAndModifySelection:", + "Shift+Control+Backspace": "deleteBackwardByDecomposingPreviousCharacter:", + "Shift+Control+ArrowUp": "scrollPageUp:", + "Shift+Control+ArrowDown": "scrollPageDown:", + "Shift+Control+ArrowLeft": "moveToLeftEndOfLineAndModifySelection:", + "Shift+Control+ArrowRight": "moveToRightEndOfLineAndModifySelection:", + "Alt+Backspace": "deleteWordBackward:", + "Alt+Enter": "insertNewlineIgnoringFieldEditor:", + "Alt+NumpadEnter": "insertNewlineIgnoringFieldEditor:", + "Alt+Escape": "complete:", + "Alt+ArrowUp": ["moveBackward:", "moveToBeginningOfParagraph:"], + "Alt+ArrowDown": ["moveForward:", "moveToEndOfParagraph:"], + "Alt+ArrowLeft": "moveWordLeft:", + "Alt+ArrowRight": "moveWordRight:", + "Alt+Delete": "deleteWordForward:", + "Alt+PageUp": "pageUp:", + "Alt+PageDown": "pageDown:", + "Shift+Alt+Backspace": "deleteWordBackward:", + "Shift+Alt+Enter": "insertNewlineIgnoringFieldEditor:", + "Shift+Alt+NumpadEnter": "insertNewlineIgnoringFieldEditor:", + "Shift+Alt+Escape": "complete:", + "Shift+Alt+ArrowUp": "moveParagraphBackwardAndModifySelection:", + "Shift+Alt+ArrowDown": "moveParagraphForwardAndModifySelection:", + "Shift+Alt+ArrowLeft": "moveWordLeftAndModifySelection:", + "Shift+Alt+ArrowRight": "moveWordRightAndModifySelection:", + "Shift+Alt+Delete": "deleteWordForward:", + "Shift+Alt+PageUp": "pageUp:", + "Shift+Alt+PageDown": "pageDown:", + "Control+Alt+KeyB": "moveWordBackward:", + "Control+Alt+KeyF": "moveWordForward:", + "Control+Alt+Backspace": "deleteWordBackward:", + "Shift+Control+Alt+KeyB": "moveWordBackwardAndModifySelection:", + "Shift+Control+Alt+KeyF": "moveWordForwardAndModifySelection:", + "Shift+Control+Alt+Backspace": "deleteWordBackward:", + "Meta+NumpadSubtract": "cancel:", + "Meta+Backspace": "deleteToBeginningOfLine:", + "Meta+ArrowUp": "moveToBeginningOfDocument:", + "Meta+ArrowDown": "moveToEndOfDocument:", + "Meta+ArrowLeft": "moveToLeftEndOfLine:", + "Meta+ArrowRight": "moveToRightEndOfLine:", + "Shift+Meta+NumpadSubtract": "cancel:", + "Shift+Meta+Backspace": "deleteToBeginningOfLine:", + "Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection:", + "Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection:", + "Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection:", + "Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection:", + "Meta+KeyA": "selectAll:", + "Meta+KeyC": "copy:", + "Meta+KeyX": "cut:", + "Meta+KeyV": "paste:", + "Meta+KeyZ": "undo:", + "Shift+Meta+KeyZ": "redo:" +}; +let RawKeyboardImpl$3 = class RawKeyboardImpl { + constructor(_client, _isMac, _dragManger) { + this._client = _client; + this._isMac = _isMac; + this._dragManger = _dragManger; + } + _commandsForCode(code, modifiers) { + if (!this._isMac) + return []; + const parts = []; + for (const modifier of ["Shift", "Control", "Alt", "Meta"]) { + if (modifiers.has(modifier)) + parts.push(modifier); + } + parts.push(code); + const shortcut = parts.join("+"); + let commands = macEditingCommands[shortcut] || []; + if (isString(commands)) + commands = [commands]; + commands = commands.filter((x) => !x.startsWith("insert")); + return commands.map((c) => c.substring(0, c.length - 1)); + } + async keydown(modifiers, keyName, description, autoRepeat) { + const { code, key: key2, location: location2, text } = description; + if (code === "Escape" && await this._dragManger.cancelDrag()) + return; + const commands = this._commandsForCode(code, modifiers); + await this._client.send("Input.dispatchKeyEvent", { + type: text ? "keyDown" : "rawKeyDown", + modifiers: toModifiersMask$2(modifiers), + windowsVirtualKeyCode: description.keyCodeWithoutLocation, + code, + commands, + key: key2, + text, + unmodifiedText: text, + autoRepeat, + location: location2, + isKeypad: location2 === keypadLocation + }); + } + async keyup(modifiers, keyName, description) { + const { code, key: key2, location: location2 } = description; + await this._client.send("Input.dispatchKeyEvent", { + type: "keyUp", + modifiers: toModifiersMask$2(modifiers), + key: key2, + windowsVirtualKeyCode: description.keyCodeWithoutLocation, + code, + location: location2 + }); + } + async sendText(text) { + await this._client.send("Input.insertText", { text }); + } +}; +let RawMouseImpl$3 = class RawMouseImpl { + constructor(page, client, dragManager) { + this._page = page; + this._client = client; + this._dragManager = dragManager; + } + async move(x, y, button, buttons, modifiers, forClick) { + const actualMove = async () => { + await this._client.send("Input.dispatchMouseEvent", { + type: "mouseMoved", + button, + buttons: toButtonsMask$2(buttons), + x, + y, + modifiers: toModifiersMask$2(modifiers), + force: buttons.size > 0 ? 0.5 : 0 + }); + }; + if (forClick) { + return actualMove(); + } + await this._dragManager.interceptDragCausedByMove(x, y, button, buttons, modifiers, actualMove); + } + async down(x, y, button, buttons, modifiers, clickCount) { + if (this._dragManager.isDragging()) + return; + await this._client.send("Input.dispatchMouseEvent", { + type: "mousePressed", + button, + buttons: toButtonsMask$2(buttons), + x, + y, + modifiers: toModifiersMask$2(modifiers), + clickCount, + force: buttons.size > 0 ? 0.5 : 0 + }); + } + async up(x, y, button, buttons, modifiers, clickCount) { + if (this._dragManager.isDragging()) { + await this._dragManager.drop(x, y, modifiers); + return; + } + await this._client.send("Input.dispatchMouseEvent", { + type: "mouseReleased", + button, + buttons: toButtonsMask$2(buttons), + x, + y, + modifiers: toModifiersMask$2(modifiers), + clickCount + }); + } + async wheel(x, y, buttons, modifiers, deltaX, deltaY) { + await this._client.send("Input.dispatchMouseEvent", { + type: "mouseWheel", + x, + y, + modifiers: toModifiersMask$2(modifiers), + deltaX, + deltaY + }); + } +}; +let RawTouchscreenImpl$3 = class RawTouchscreenImpl { + constructor(client) { + this._client = client; + } + async tap(x, y, modifiers) { + await Promise.all([ + this._client.send("Input.dispatchTouchEvent", { + type: "touchStart", + modifiers: toModifiersMask$2(modifiers), + touchPoints: [{ + x, + y + }] + }), + this._client.send("Input.dispatchTouchEvent", { + type: "touchEnd", + modifiers: toModifiersMask$2(modifiers), + touchPoints: [] + }) + ]); + } +}; +class CRNetworkManager { + constructor(page, serviceWorker) { + this._requestIdToRequest = /* @__PURE__ */ new Map(); + this._requestIdToRequestWillBeSentEvent = /* @__PURE__ */ new Map(); + this._credentials = null; + this._attemptedAuthentications = /* @__PURE__ */ new Set(); + this._userRequestInterceptionEnabled = false; + this._protocolRequestInterceptionEnabled = false; + this._offline = false; + this._extraHTTPHeaders = []; + this._requestIdToRequestPausedEvent = /* @__PURE__ */ new Map(); + this._responseExtraInfoTracker = new ResponseExtraInfoTracker(); + this._sessions = /* @__PURE__ */ new Map(); + this._page = page; + this._serviceWorker = serviceWorker; + } + async addSession(session, workerFrame, isMain) { + const sessionInfo = { session, isMain, workerFrame, eventListeners: [] }; + sessionInfo.eventListeners = [ + eventsHelper.addEventListener(session, "Fetch.requestPaused", this._onRequestPaused.bind(this, sessionInfo)), + eventsHelper.addEventListener(session, "Fetch.authRequired", this._onAuthRequired.bind(this, sessionInfo)), + eventsHelper.addEventListener(session, "Network.requestWillBeSent", this._onRequestWillBeSent.bind(this, sessionInfo)), + eventsHelper.addEventListener(session, "Network.requestWillBeSentExtraInfo", this._onRequestWillBeSentExtraInfo.bind(this)), + eventsHelper.addEventListener(session, "Network.requestServedFromCache", this._onRequestServedFromCache.bind(this)), + eventsHelper.addEventListener(session, "Network.responseReceived", this._onResponseReceived.bind(this, sessionInfo)), + eventsHelper.addEventListener(session, "Network.responseReceivedExtraInfo", this._onResponseReceivedExtraInfo.bind(this)), + eventsHelper.addEventListener(session, "Network.loadingFinished", this._onLoadingFinished.bind(this, sessionInfo)), + eventsHelper.addEventListener(session, "Network.loadingFailed", this._onLoadingFailed.bind(this, sessionInfo)) + ]; + if (this._page) { + sessionInfo.eventListeners.push(...[ + eventsHelper.addEventListener(session, "Network.webSocketCreated", (e) => this._page.frameManager.onWebSocketCreated(e.requestId, e.url)), + eventsHelper.addEventListener(session, "Network.webSocketWillSendHandshakeRequest", (e) => this._page.frameManager.onWebSocketRequest(e.requestId)), + eventsHelper.addEventListener(session, "Network.webSocketHandshakeResponseReceived", (e) => this._page.frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), + eventsHelper.addEventListener(session, "Network.webSocketFrameSent", (e) => e.response.payloadData && this._page.frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), + eventsHelper.addEventListener(session, "Network.webSocketFrameReceived", (e) => e.response.payloadData && this._page.frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), + eventsHelper.addEventListener(session, "Network.webSocketClosed", (e) => this._page.frameManager.webSocketClosed(e.requestId)), + eventsHelper.addEventListener(session, "Network.webSocketFrameError", (e) => this._page.frameManager.webSocketError(e.requestId, e.errorMessage)) + ]); + } + this._sessions.set(session, sessionInfo); + await Promise.all([ + session.send("Network.enable"), + this._updateProtocolRequestInterceptionForSession( + sessionInfo, + true + /* initial */ + ), + this._setOfflineForSession( + sessionInfo, + true + /* initial */ + ), + this._setExtraHTTPHeadersForSession( + sessionInfo, + true + /* initial */ + ) + ]); + } + removeSession(session) { + const info = this._sessions.get(session); + if (info) + eventsHelper.removeEventListeners(info.eventListeners); + this._sessions.delete(session); + } + async _forEachSession(cb) { + await Promise.all([...this._sessions.values()].map((info) => { + if (info.isMain) + return cb(info); + return cb(info).catch((e) => { + if (isSessionClosedError(e)) + return; + throw e; + }); + })); + } + async authenticate(credentials) { + this._credentials = credentials; + await this._updateProtocolRequestInterception(); + } + async setOffline(offline) { + if (offline === this._offline) + return; + this._offline = offline; + await this._forEachSession((info) => this._setOfflineForSession(info)); + } + async _setOfflineForSession(info, initial) { + if (initial && !this._offline) + return; + if (info.workerFrame) + return; + await info.session.send("Network.emulateNetworkConditions", { + offline: this._offline, + // values of 0 remove any active throttling. crbug.com/456324#c9 + latency: 0, + downloadThroughput: -1, + uploadThroughput: -1 + }); + } + async setRequestInterception(value) { + this._userRequestInterceptionEnabled = value; + await this._updateProtocolRequestInterception(); + } + async _updateProtocolRequestInterception() { + const enabled = this._userRequestInterceptionEnabled || !!this._credentials; + if (enabled === this._protocolRequestInterceptionEnabled) + return; + this._protocolRequestInterceptionEnabled = enabled; + await this._forEachSession((info) => this._updateProtocolRequestInterceptionForSession(info)); + } + async _updateProtocolRequestInterceptionForSession(info, initial) { + const enabled = this._protocolRequestInterceptionEnabled; + if (initial && !enabled) + return; + const cachePromise = info.session.send("Network.setCacheDisabled", { cacheDisabled: enabled }); + let fetchPromise = Promise.resolve(void 0); + if (!info.workerFrame) { + if (enabled) + fetchPromise = info.session.send("Fetch.enable", { handleAuthRequests: true, patterns: [{ urlPattern: "*", requestStage: "Request" }] }); + else + fetchPromise = info.session.send("Fetch.disable"); + } + await Promise.all([cachePromise, fetchPromise]); + } + async setExtraHTTPHeaders(extraHTTPHeaders) { + if (!this._extraHTTPHeaders.length && !extraHTTPHeaders.length) + return; + this._extraHTTPHeaders = extraHTTPHeaders; + await this._forEachSession((info) => this._setExtraHTTPHeadersForSession(info)); + } + async _setExtraHTTPHeadersForSession(info, initial) { + if (initial && !this._extraHTTPHeaders.length) + return; + await info.session.send("Network.setExtraHTTPHeaders", { headers: headersArrayToObject( + this._extraHTTPHeaders, + false + /* lowerCase */ + ) }); + } + async clearCache() { + await this._forEachSession(async (info) => { + await info.session.send("Network.setCacheDisabled", { cacheDisabled: true }); + if (!this._protocolRequestInterceptionEnabled) + await info.session.send("Network.setCacheDisabled", { cacheDisabled: false }); + if (!info.workerFrame) + await info.session.send("Network.clearBrowserCache"); + }); + } + _onRequestWillBeSent(sessionInfo, event) { + if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith("data:")) { + const requestId = event.requestId; + const requestPausedEvent = this._requestIdToRequestPausedEvent.get(requestId); + if (requestPausedEvent) { + this._onRequest(sessionInfo, event, requestPausedEvent.sessionInfo, requestPausedEvent.event); + this._requestIdToRequestPausedEvent.delete(requestId); + } else { + this._requestIdToRequestWillBeSentEvent.set(event.requestId, { sessionInfo, event }); + } + } else { + this._onRequest(sessionInfo, event, void 0, void 0); + } + } + _onRequestServedFromCache(event) { + this._responseExtraInfoTracker.requestServedFromCache(event); + } + _onRequestWillBeSentExtraInfo(event) { + this._responseExtraInfoTracker.requestWillBeSentExtraInfo(event); + } + _onAuthRequired(sessionInfo, event) { + let response2 = "Default"; + const shouldProvideCredentials = this._shouldProvideCredentials(event.request.url); + if (this._attemptedAuthentications.has(event.requestId)) { + response2 = "CancelAuth"; + } else if (shouldProvideCredentials) { + response2 = "ProvideCredentials"; + this._attemptedAuthentications.add(event.requestId); + } + const { username, password } = shouldProvideCredentials && this._credentials ? this._credentials : { username: void 0, password: void 0 }; + sessionInfo.session._sendMayFail("Fetch.continueWithAuth", { + requestId: event.requestId, + authChallengeResponse: { response: response2, username, password } + }); + } + _shouldProvideCredentials(url2) { + if (!this._credentials) + return false; + return !this._credentials.origin || new URL(url2).origin.toLowerCase() === this._credentials.origin.toLowerCase(); + } + _onRequestPaused(sessionInfo, event) { + var _a2; + if (!event.networkId) { + sessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: event.requestId }); + return; + } + if (event.request.url.startsWith("data:")) + return; + const requestId = event.networkId; + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId); + if (requestWillBeSentEvent) { + this._onRequest(requestWillBeSentEvent.sessionInfo, requestWillBeSentEvent.event, sessionInfo, event); + this._requestIdToRequestWillBeSentEvent.delete(requestId); + } else { + const existingRequest = this._requestIdToRequest.get(requestId); + const alreadyContinuedParams = (_a2 = existingRequest == null ? void 0 : existingRequest._route) == null ? void 0 : _a2._alreadyContinuedParams; + if (alreadyContinuedParams && !event.redirectedRequestId) { + sessionInfo.session._sendMayFail("Fetch.continueRequest", { + ...alreadyContinuedParams, + requestId: event.requestId + }); + return; + } + this._requestIdToRequestPausedEvent.set(requestId, { sessionInfo, event }); + } + } + _onRequest(requestWillBeSentSessionInfo, requestWillBeSentEvent, requestPausedSessionInfo, requestPausedEvent) { + var _a2, _b2, _c2, _d2, _e2; + if (requestWillBeSentEvent.request.url.startsWith("data:")) + return; + let redirectedFrom = null; + if (requestWillBeSentEvent.redirectResponse) { + const request22 = this._requestIdToRequest.get(requestWillBeSentEvent.requestId); + if (request22) { + this._handleRequestRedirect(request22, requestWillBeSentEvent.redirectResponse, requestWillBeSentEvent.timestamp, requestWillBeSentEvent.redirectHasExtraInfo); + redirectedFrom = request22; + } + } + let frame = requestWillBeSentEvent.frameId ? (_a2 = this._page) == null ? void 0 : _a2.frameManager.frame(requestWillBeSentEvent.frameId) : requestWillBeSentSessionInfo.workerFrame; + if (!frame && this._page && requestPausedEvent && requestPausedEvent.frameId) + frame = this._page.frameManager.frame(requestPausedEvent.frameId); + if (!frame && this._page && requestWillBeSentEvent.frameId === ((_b2 = this._page) == null ? void 0 : _b2.delegate)._targetId) { + frame = this._page.frameManager.frameAttached(requestWillBeSentEvent.frameId, null); + } + const isInterceptedOptionsPreflight = !!requestPausedEvent && requestPausedEvent.request.method === "OPTIONS" && requestWillBeSentEvent.initiator.type === "preflight"; + if (isInterceptedOptionsPreflight && (this._page || this._serviceWorker).needsRequestInterception()) { + const requestHeaders = requestPausedEvent.request.headers; + const responseHeaders = [ + { name: "Access-Control-Allow-Origin", value: requestHeaders["Origin"] || "*" }, + { name: "Access-Control-Allow-Methods", value: requestHeaders["Access-Control-Request-Method"] || "GET, POST, OPTIONS, DELETE" }, + { name: "Access-Control-Allow-Credentials", value: "true" } + ]; + if (requestHeaders["Access-Control-Request-Headers"]) + responseHeaders.push({ name: "Access-Control-Allow-Headers", value: requestHeaders["Access-Control-Request-Headers"] }); + requestPausedSessionInfo.session._sendMayFail("Fetch.fulfillRequest", { + requestId: requestPausedEvent.requestId, + responseCode: 204, + responsePhrase: statusText(204), + responseHeaders, + body: "" + }); + return; + } + if (!frame && !this._serviceWorker) { + if (requestPausedEvent) + requestPausedSessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: requestPausedEvent.requestId }); + return; + } + let route = null; + let headersOverride; + if (requestPausedEvent) { + if (redirectedFrom || !this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) { + headersOverride = (_d2 = (_c2 = redirectedFrom == null ? void 0 : redirectedFrom._originalRequestRoute) == null ? void 0 : _c2._alreadyContinuedParams) == null ? void 0 : _d2.headers; + requestPausedSessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: requestPausedEvent.requestId, headers: headersOverride }); + } else { + route = new RouteImpl(requestPausedSessionInfo.session, requestPausedEvent.requestId); + } + } + const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === "Document"; + const documentId = isNavigationRequest ? requestWillBeSentEvent.loaderId : void 0; + const request2 = new InterceptableRequest$1({ + session: requestWillBeSentSessionInfo.session, + context: (this._page || this._serviceWorker).browserContext, + frame: frame || null, + serviceWorker: this._serviceWorker || null, + documentId, + route, + requestWillBeSentEvent, + requestPausedEvent, + redirectedFrom, + headersOverride: headersOverride || null + }); + this._requestIdToRequest.set(requestWillBeSentEvent.requestId, request2); + if (route) { + request2.request.setRawRequestHeaders(headersObjectToArray(requestPausedEvent.request.headers, "\n")); + } + (((_e2 = this._page) == null ? void 0 : _e2.frameManager) || this._serviceWorker).requestStarted(request2.request, route || void 0); + } + _createResponse(request2, responsePayload, hasExtraInfo) { + var _a2, _b2, _c2, _d2, _e2; + const getResponseBody = async () => { + var _a3; + const contentLengthHeader = Object.entries(responsePayload.headers).find((header) => header[0].toLowerCase() === "content-length"); + const expectedLength = contentLengthHeader ? +contentLengthHeader[1] : void 0; + const session = request2.session; + const response22 = await session.send("Network.getResponseBody", { requestId: request2._requestId }); + if (response22.body || !expectedLength) + return Buffer.from(response22.body, response22.base64Encoded ? "base64" : "utf8"); + if ((_a3 = request2._route) == null ? void 0 : _a3._fulfilled) + return Buffer.from(""); + const resource = await session.send("Network.loadNetworkResource", { url: request2.request.url(), frameId: this._serviceWorker ? void 0 : request2.request.frame()._id, options: { disableCache: false, includeCredentials: true } }); + const chunks = []; + while (resource.resource.stream) { + const chunk = await session.send("IO.read", { handle: resource.resource.stream }); + chunks.push(Buffer.from(chunk.data, chunk.base64Encoded ? "base64" : "utf-8")); + if (chunk.eof) { + await session.send("IO.close", { handle: resource.resource.stream }); + break; + } + } + return Buffer.concat(chunks); + }; + const timingPayload = responsePayload.timing; + let timing; + if (timingPayload && !this._responseExtraInfoTracker.servedFromCache(request2._requestId)) { + timing = { + startTime: (timingPayload.requestTime - request2._timestamp + request2._wallTime) * 1e3, + domainLookupStart: timingPayload.dnsStart, + domainLookupEnd: timingPayload.dnsEnd, + connectStart: timingPayload.connectStart, + secureConnectionStart: timingPayload.sslStart, + connectEnd: timingPayload.connectEnd, + requestStart: timingPayload.sendStart, + responseStart: timingPayload.receiveHeadersEnd + }; + } else { + timing = { + startTime: request2._wallTime * 1e3, + domainLookupStart: -1, + domainLookupEnd: -1, + connectStart: -1, + secureConnectionStart: -1, + connectEnd: -1, + requestStart: -1, + responseStart: -1 + }; + } + const response2 = new Response$1(request2.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers), timing, getResponseBody, !!responsePayload.fromServiceWorker, responsePayload.protocol); + if ((responsePayload == null ? void 0 : responsePayload.remoteIPAddress) && typeof (responsePayload == null ? void 0 : responsePayload.remotePort) === "number") { + response2._serverAddrFinished({ + ipAddress: responsePayload.remoteIPAddress, + port: responsePayload.remotePort + }); + } else { + response2._serverAddrFinished(); + } + response2._securityDetailsFinished({ + protocol: (_a2 = responsePayload == null ? void 0 : responsePayload.securityDetails) == null ? void 0 : _a2.protocol, + subjectName: (_b2 = responsePayload == null ? void 0 : responsePayload.securityDetails) == null ? void 0 : _b2.subjectName, + issuer: (_c2 = responsePayload == null ? void 0 : responsePayload.securityDetails) == null ? void 0 : _c2.issuer, + validFrom: (_d2 = responsePayload == null ? void 0 : responsePayload.securityDetails) == null ? void 0 : _d2.validFrom, + validTo: (_e2 = responsePayload == null ? void 0 : responsePayload.securityDetails) == null ? void 0 : _e2.validTo + }); + this._responseExtraInfoTracker.processResponse(request2._requestId, response2, hasExtraInfo); + return response2; + } + _deleteRequest(request2) { + this._requestIdToRequest.delete(request2._requestId); + if (request2._interceptionId) + this._attemptedAuthentications.delete(request2._interceptionId); + } + _handleRequestRedirect(request2, responsePayload, timestamp2, hasExtraInfo) { + var _a2, _b2; + const response2 = this._createResponse(request2, responsePayload, hasExtraInfo); + response2.setTransferSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished((timestamp2 - request2._timestamp) * 1e3); + this._deleteRequest(request2); + (((_a2 = this._page) == null ? void 0 : _a2.frameManager) || this._serviceWorker).requestReceivedResponse(response2); + (((_b2 = this._page) == null ? void 0 : _b2.frameManager) || this._serviceWorker).reportRequestFinished(request2.request, response2); + } + _onResponseReceivedExtraInfo(event) { + this._responseExtraInfoTracker.responseReceivedExtraInfo(event); + } + _onResponseReceived(sessionInfo, event) { + var _a2; + let request2 = this._requestIdToRequest.get(event.requestId); + if (!request2 && event.response.fromServiceWorker) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (requestWillBeSentEvent) { + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(sessionInfo, requestWillBeSentEvent.event, void 0, void 0); + request2 = this._requestIdToRequest.get(event.requestId); + } + } + if (!request2) + return; + const response2 = this._createResponse(request2, event.response, event.hasExtraInfo); + (((_a2 = this._page) == null ? void 0 : _a2.frameManager) || this._serviceWorker).requestReceivedResponse(response2); + } + _onLoadingFinished(sessionInfo, event) { + var _a2; + this._responseExtraInfoTracker.loadingFinished(event); + const request2 = this._requestIdToRequest.get(event.requestId); + if (!request2) + return; + this._maybeUpdateRequestSession(sessionInfo, request2); + const response2 = request2.request._existingResponse(); + if (response2) { + response2.setTransferSize(event.encodedDataLength); + response2.responseHeadersSize().then((size) => response2.setEncodedBodySize(event.encodedDataLength - size)); + response2._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request2._timestamp)); + } + this._deleteRequest(request2); + (((_a2 = this._page) == null ? void 0 : _a2.frameManager) || this._serviceWorker).reportRequestFinished(request2.request, response2); + } + _onLoadingFailed(sessionInfo, event) { + var _a2; + this._responseExtraInfoTracker.loadingFailed(event); + let request2 = this._requestIdToRequest.get(event.requestId); + if (!request2) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (requestWillBeSentEvent) { + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(sessionInfo, requestWillBeSentEvent.event, void 0, void 0); + request2 = this._requestIdToRequest.get(event.requestId); + } + } + if (!request2) + return; + this._maybeUpdateRequestSession(sessionInfo, request2); + const response2 = request2.request._existingResponse(); + if (response2) { + response2.setTransferSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request2._timestamp)); + } else { + request2.request.setRawRequestHeaders(null); + } + this._deleteRequest(request2); + request2.request._setFailureText(event.errorText || event.blockedReason || ""); + (((_a2 = this._page) == null ? void 0 : _a2.frameManager) || this._serviceWorker).requestFailed(request2.request, !!event.canceled); + } + _maybeUpdateRequestSession(sessionInfo, request2) { + if (request2.session !== sessionInfo.session && !sessionInfo.isMain && (request2._documentId === request2._requestId || sessionInfo.workerFrame)) + request2.session = sessionInfo.session; + } +} +let InterceptableRequest$1 = class InterceptableRequest { + constructor(options2) { + const { session, context, frame, documentId, route, requestWillBeSentEvent, requestPausedEvent, redirectedFrom, serviceWorker, headersOverride } = options2; + this.session = session; + this._timestamp = requestWillBeSentEvent.timestamp; + this._wallTime = requestWillBeSentEvent.wallTime; + this._requestId = requestWillBeSentEvent.requestId; + this._interceptionId = requestPausedEvent && requestPausedEvent.requestId; + this._documentId = documentId; + this._route = route; + this._originalRequestRoute = route ?? (redirectedFrom == null ? void 0 : redirectedFrom._originalRequestRoute); + const { + headers, + method, + url: url2, + postDataEntries = null + } = requestPausedEvent ? requestPausedEvent.request : requestWillBeSentEvent.request; + const type2 = (requestWillBeSentEvent.type || "").toLowerCase(); + let postDataBuffer = null; + const entries = postDataEntries == null ? void 0 : postDataEntries.filter((entry) => entry.bytes); + if (entries && entries.length) + postDataBuffer = Buffer.concat(entries.map((entry) => Buffer.from(entry.bytes, "base64"))); + this.request = new Request$1(context, frame, serviceWorker, (redirectedFrom == null ? void 0 : redirectedFrom.request) || null, documentId, url2, type2, method, postDataBuffer, headersOverride || headersObjectToArray(headers)); + } +}; +class RouteImpl { + constructor(session, interceptionId) { + this._fulfilled = false; + this._session = session; + this._interceptionId = interceptionId; + } + async continue(overrides) { + this._alreadyContinuedParams = { + requestId: this._interceptionId, + url: overrides.url, + headers: overrides.headers, + method: overrides.method, + postData: overrides.postData ? overrides.postData.toString("base64") : void 0 + }; + await catchDisallowedErrors(async () => { + await this._session.send("Fetch.continueRequest", this._alreadyContinuedParams); + }); + } + async fulfill(response2) { + this._fulfilled = true; + const body = response2.isBase64 ? response2.body : Buffer.from(response2.body).toString("base64"); + const responseHeaders = splitSetCookieHeader(response2.headers); + await catchDisallowedErrors(async () => { + await this._session.send("Fetch.fulfillRequest", { + requestId: this._interceptionId, + responseCode: response2.status, + responsePhrase: statusText(response2.status), + responseHeaders, + body + }); + }); + } + async abort(errorCode = "failed") { + const errorReason = errorReasons$1[errorCode]; + assert(errorReason, "Unknown error code: " + errorCode); + await catchDisallowedErrors(async () => { + await this._session.send("Fetch.failRequest", { + requestId: this._interceptionId, + errorReason + }); + }); + } +} +async function catchDisallowedErrors(callback) { + try { + return await callback(); + } catch (e) { + if (isProtocolError(e) && e.message.includes("Invalid http status code or phrase")) + throw e; + if (isProtocolError(e) && e.message.includes("Unsafe header")) + throw e; + } +} +function splitSetCookieHeader(headers) { + const index2 = headers.findIndex(({ name }) => name.toLowerCase() === "set-cookie"); + if (index2 === -1) + return headers; + const header = headers[index2]; + const values = header.value.split("\n"); + if (values.length === 1) + return headers; + const result = headers.slice(); + result.splice(index2, 1, ...values.map((value) => ({ name: header.name, value }))); + return result; +} +const errorReasons$1 = { + "aborted": "Aborted", + "accessdenied": "AccessDenied", + "addressunreachable": "AddressUnreachable", + "blockedbyclient": "BlockedByClient", + "blockedbyresponse": "BlockedByResponse", + "connectionaborted": "ConnectionAborted", + "connectionclosed": "ConnectionClosed", + "connectionfailed": "ConnectionFailed", + "connectionrefused": "ConnectionRefused", + "connectionreset": "ConnectionReset", + "internetdisconnected": "InternetDisconnected", + "namenotresolved": "NameNotResolved", + "timedout": "TimedOut", + "failed": "Failed" +}; +class ResponseExtraInfoTracker { + constructor() { + this._requests = /* @__PURE__ */ new Map(); + } + requestWillBeSentExtraInfo(event) { + const info = this._getOrCreateEntry(event.requestId); + info.requestWillBeSentExtraInfo.push(event); + this._patchHeaders(info, info.requestWillBeSentExtraInfo.length - 1); + this._checkFinished(info); + } + requestServedFromCache(event) { + const info = this._getOrCreateEntry(event.requestId); + info.servedFromCache = true; + } + servedFromCache(requestId) { + const info = this._requests.get(requestId); + return !!(info == null ? void 0 : info.servedFromCache); + } + responseReceivedExtraInfo(event) { + const info = this._getOrCreateEntry(event.requestId); + info.responseReceivedExtraInfo.push(event); + this._patchHeaders(info, info.responseReceivedExtraInfo.length - 1); + this._checkFinished(info); + } + processResponse(requestId, response2, hasExtraInfo) { + let info = this._requests.get(requestId); + if (!hasExtraInfo || (info == null ? void 0 : info.servedFromCache)) { + response2.request().setRawRequestHeaders(null); + response2.setResponseHeadersSize(null); + response2.setRawResponseHeaders(null); + return; + } + info = this._getOrCreateEntry(requestId); + info.responses.push(response2); + this._patchHeaders(info, info.responses.length - 1); + } + loadingFinished(event) { + const info = this._requests.get(event.requestId); + if (!info) + return; + info.loadingFinished = event; + this._checkFinished(info); + } + loadingFailed(event) { + const info = this._requests.get(event.requestId); + if (!info) + return; + info.loadingFailed = event; + this._checkFinished(info); + } + _getOrCreateEntry(requestId) { + let info = this._requests.get(requestId); + if (!info) { + info = { + requestId, + requestWillBeSentExtraInfo: [], + responseReceivedExtraInfo: [], + responses: [] + }; + this._requests.set(requestId, info); + } + return info; + } + _patchHeaders(info, index2) { + var _a2; + const response2 = info.responses[index2]; + const requestExtraInfo = info.requestWillBeSentExtraInfo[index2]; + if (response2 && requestExtraInfo) { + response2.request().setRawRequestHeaders(headersObjectToArray(requestExtraInfo.headers, "\n")); + info.requestWillBeSentExtraInfo[index2] = void 0; + } + const responseExtraInfo = info.responseReceivedExtraInfo[index2]; + if (response2 && responseExtraInfo) { + response2.setResponseHeadersSize(((_a2 = responseExtraInfo.headersText) == null ? void 0 : _a2.length) || 0); + response2.setRawResponseHeaders(headersObjectToArray(responseExtraInfo.headers, "\n")); + info.responseReceivedExtraInfo[index2] = void 0; + } + } + _checkFinished(info) { + if (!info.loadingFinished && !info.loadingFailed) + return; + if (info.responses.length <= info.responseReceivedExtraInfo.length) { + this._stopTracking(info.requestId); + return; + } + } + _stopTracking(requestId) { + this._requests.delete(requestId); + } +} +const PagePaperFormats$1 = { + letter: { width: 8.5, height: 11 }, + legal: { width: 8.5, height: 14 }, + tabloid: { width: 11, height: 17 }, + ledger: { width: 17, height: 11 }, + a0: { width: 33.1, height: 46.8 }, + a1: { width: 23.4, height: 33.1 }, + a2: { width: 16.54, height: 23.4 }, + a3: { width: 11.7, height: 16.54 }, + a4: { width: 8.27, height: 11.7 }, + a5: { width: 5.83, height: 8.27 }, + a6: { width: 4.13, height: 5.83 } +}; +const unitToPixels$1 = { + "px": 1, + "in": 96, + "cm": 37.8, + "mm": 3.78 +}; +function convertPrintParameterToInches$1(text) { + if (text === void 0) + return void 0; + let unit = text.substring(text.length - 2).toLowerCase(); + let valueText = ""; + if (unitToPixels$1.hasOwnProperty(unit)) { + valueText = text.substring(0, text.length - 2); + } else { + unit = "px"; + valueText = text; + } + const value = Number(valueText); + assert(!isNaN(value), "Failed to parse parameter value: " + text); + const pixels = value * unitToPixels$1[unit]; + return pixels / 96; +} +class CRPDF { + constructor(client) { + this._client = client; + } + async generate(options2) { + const { + scale = 1, + displayHeaderFooter = false, + headerTemplate = "", + footerTemplate = "", + printBackground = false, + landscape = false, + pageRanges = "", + preferCSSPageSize = false, + margin = {}, + tagged = false, + outline = false + } = options2; + let paperWidth = 8.5; + let paperHeight = 11; + if (options2.format) { + const format = PagePaperFormats$1[options2.format.toLowerCase()]; + assert(format, "Unknown paper format: " + options2.format); + paperWidth = format.width; + paperHeight = format.height; + } else { + paperWidth = convertPrintParameterToInches$1(options2.width) || paperWidth; + paperHeight = convertPrintParameterToInches$1(options2.height) || paperHeight; + } + const marginTop = convertPrintParameterToInches$1(margin.top) || 0; + const marginLeft = convertPrintParameterToInches$1(margin.left) || 0; + const marginBottom = convertPrintParameterToInches$1(margin.bottom) || 0; + const marginRight = convertPrintParameterToInches$1(margin.right) || 0; + const generateDocumentOutline = outline; + const generateTaggedPDF = tagged; + const result = await this._client.send("Page.printToPDF", { + transferMode: "ReturnAsStream", + landscape, + displayHeaderFooter, + headerTemplate, + footerTemplate, + printBackground, + scale, + paperWidth, + paperHeight, + marginTop, + marginBottom, + marginLeft, + marginRight, + pageRanges, + preferCSSPageSize, + generateTaggedPDF, + generateDocumentOutline + }); + return await readProtocolStream(this._client, result.stream); + } +} +const platformToFontFamilies = { + "linux": { + "fontFamilies": { + "standard": "Times New Roman", + "fixed": "Monospace", + "serif": "Times New Roman", + "sansSerif": "Arial", + "cursive": "Comic Sans MS", + "fantasy": "Impact" + } + }, + "mac": { + "fontFamilies": { + "standard": "Times", + "fixed": "Courier", + "serif": "Times", + "sansSerif": "Helvetica", + "cursive": "Apple Chancery", + "fantasy": "Papyrus" + }, + "forScripts": [ + { + "script": "jpan", + "fontFamilies": { + "standard": "Hiragino Kaku Gothic ProN", + "fixed": "Osaka-Mono", + "serif": "Hiragino Mincho ProN", + "sansSerif": "Hiragino Kaku Gothic ProN" + } + }, + { + "script": "hang", + "fontFamilies": { + "standard": "Apple SD Gothic Neo", + "serif": "AppleMyungjo", + "sansSerif": "Apple SD Gothic Neo" + } + }, + { + "script": "hans", + "fontFamilies": { + "standard": ",PingFang SC,STHeiti", + "serif": "Songti SC", + "sansSerif": ",PingFang SC,STHeiti", + "cursive": "Kaiti SC" + } + }, + { + "script": "hant", + "fontFamilies": { + "standard": ",PingFang TC,Heiti TC", + "serif": "Songti TC", + "sansSerif": ",PingFang TC,Heiti TC", + "cursive": "Kaiti TC" + } + } + ] + }, + "win": { + "fontFamilies": { + "standard": "Times New Roman", + "fixed": "Consolas", + "serif": "Times New Roman", + "sansSerif": "Arial", + "cursive": "Comic Sans MS", + "fantasy": "Impact" + }, + "forScripts": [ + { + "script": "cyrl", + "fontFamilies": { + "standard": "Times New Roman", + "fixed": "Courier New", + "serif": "Times New Roman", + "sansSerif": "Arial" + } + }, + { + "script": "arab", + "fontFamilies": { + "fixed": "Courier New", + "sansSerif": "Segoe UI" + } + }, + { + "script": "grek", + "fontFamilies": { + "standard": "Times New Roman", + "fixed": "Courier New", + "serif": "Times New Roman", + "sansSerif": "Arial" + } + }, + { + "script": "jpan", + "fontFamilies": { + "standard": ",Meiryo,Yu Gothic", + "fixed": "MS Gothic", + "serif": ",Yu Mincho,MS PMincho", + "sansSerif": ",Meiryo,Yu Gothic" + } + }, + { + "script": "hang", + "fontFamilies": { + "standard": "Malgun Gothic", + "fixed": "Gulimche", + "serif": "Batang", + "sansSerif": "Malgun Gothic", + "cursive": "Gungsuh" + } + }, + { + "script": "hans", + "fontFamilies": { + "standard": "Microsoft YaHei", + "fixed": "NSimsun", + "serif": "Simsun", + "sansSerif": "Microsoft YaHei", + "cursive": "KaiTi" + } + }, + { + "script": "hant", + "fontFamilies": { + "standard": "Microsoft JhengHei", + "fixed": "MingLiU", + "serif": "PMingLiU", + "sansSerif": "Microsoft JhengHei", + "cursive": "DFKai-SB" + } + } + ] + } +}; +const fps = 25; +class VideoRecorder { + constructor(page, ffmpegPath, progress2) { + this._process = null; + this._gracefullyClose = null; + this._lastWritePromise = Promise.resolve(); + this._lastFrameTimestamp = 0; + this._lastFrameBuffer = null; + this._lastWriteTimestamp = 0; + this._frameQueue = []; + this._isStopped = false; + this._progress = progress2; + this._ffmpegPath = ffmpegPath; + page.on(Page$1.Events.ScreencastFrame, (frame) => this.writeFrame(frame.buffer, frame.frameSwapWallTime / 1e3)); + } + static async launch(page, ffmpegPath, options2) { + if (!options2.outputFile.endsWith(".webm")) + throw new Error("File must have .webm extension"); + const controller = new ProgressController(serverSideCallMetadata(), page); + controller.setLogName("browser"); + return await controller.run(async (progress2) => { + const recorder = new VideoRecorder(page, ffmpegPath, progress2); + await recorder._launch(options2); + return recorder; + }); + } + async _launch(options2) { + const w = options2.width; + const h = options2.height; + const args = `-loglevel error -f image2pipe -avioflags direct -fpsprobesize 0 -probesize 32 -analyzeduration 0 -c:v mjpeg -i pipe:0 -y -an -r ${fps} -c:v vp8 -qmin 0 -qmax 50 -crf 8 -deadline realtime -speed 8 -b:v 1M -threads 1 -vf pad=${w}:${h}:0:0:gray,crop=${w}:${h}:0:0`.split(" "); + args.push(options2.outputFile); + const progress2 = this._progress; + const { launchedProcess, gracefullyClose } = await launchProcess({ + command: this._ffmpegPath, + args, + stdio: "stdin", + log: (message) => progress2.log(message), + tempDirectories: [], + attemptToGracefullyClose: async () => { + progress2.log("Closing stdin..."); + launchedProcess.stdin.end(); + }, + onExit: (exitCode, signal) => { + progress2.log(`ffmpeg onkill exitCode=${exitCode} signal=${signal}`); + } + }); + launchedProcess.stdin.on("finish", () => { + progress2.log("ffmpeg finished input."); + }); + launchedProcess.stdin.on("error", () => { + progress2.log("ffmpeg error."); + }); + this._process = launchedProcess; + this._gracefullyClose = gracefullyClose; + } + writeFrame(frame, timestamp2) { + assert(this._process); + if (this._isStopped) + return; + if (this._lastFrameBuffer) { + const durationSec = timestamp2 - this._lastFrameTimestamp; + const repeatCount = Math.max(1, Math.round(fps * durationSec)); + for (let i = 0; i < repeatCount; ++i) + this._frameQueue.push(this._lastFrameBuffer); + this._lastWritePromise = this._lastWritePromise.then(() => this._sendFrames()); + } + this._lastFrameBuffer = frame; + this._lastFrameTimestamp = timestamp2; + this._lastWriteTimestamp = monotonicTime(); + } + async _sendFrames() { + while (this._frameQueue.length) + await this._sendFrame(this._frameQueue.shift()); + } + async _sendFrame(frame) { + return new Promise((f) => this._process.stdin.write(frame, f)).then((error2) => { + if (error2) + this._progress.log(`ffmpeg failed to write: ${String(error2)}`); + }); + } + async stop() { + if (this._isStopped) + return; + this.writeFrame(Buffer.from([]), this._lastFrameTimestamp + (monotonicTime() - this._lastWriteTimestamp) / 1e3); + this._isStopped = true; + await this._lastWritePromise; + await this._gracefullyClose(); + } +} +class CRPage { + constructor(client, targetId, browserContext, opener, bits) { + this._sessions = /* @__PURE__ */ new Map(); + this._nextWindowOpenPopupFeatures = []; + this._targetId = targetId; + this._opener = opener; + this._isBackgroundPage = bits.isBackgroundPage; + const dragManager = new DragManager(this); + this.rawKeyboard = new RawKeyboardImpl$3(client, browserContext._browser._platform() === "mac", dragManager); + this.rawMouse = new RawMouseImpl$3(this, client, dragManager); + this.rawTouchscreen = new RawTouchscreenImpl$3(client); + this._pdf = new CRPDF(client); + this._coverage = new CRCoverage(client); + this._browserContext = browserContext; + this._page = new Page$1(this, browserContext); + this.utilityWorldName = `__playwright_utility_world_${this._page.guid}`; + this._networkManager = new CRNetworkManager(this._page, null); + this.updateOffline(); + this.updateExtraHTTPHeaders(); + this.updateHttpCredentials(); + this.updateRequestInterception(); + this._mainFrameSession = new FrameSession(this, client, targetId, null); + this._sessions.set(targetId, this._mainFrameSession); + if (opener && !browserContext._options.noDefaultViewport) { + const features = opener._nextWindowOpenPopupFeatures.shift() || []; + const viewportSize = helper.getViewportSizeFromWindowFeatures(features); + if (viewportSize) + this._page.setEmulatedSizeFromWindowOpen({ viewport: viewportSize, screen: viewportSize }); + } + const createdEvent = this._isBackgroundPage ? CRBrowserContext.CREvents.BackgroundPage : BrowserContext$1.Events.Page; + this._mainFrameSession._initialize(bits.hasUIWindow).then( + () => { + var _a2; + return this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page, void 0, createdEvent); + }, + (error2) => { + var _a2; + return this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page, error2, createdEvent); + } + ); + } + static mainFrameSession(page) { + const crPage = page.delegate; + return crPage._mainFrameSession; + } + async _forAllFrameSessions(cb) { + const frameSessions = Array.from(this._sessions.values()); + await Promise.all(frameSessions.map((frameSession) => { + if (frameSession._isMainFrame()) + return cb(frameSession); + return cb(frameSession).catch((e) => { + if (isSessionClosedError(e)) + return; + throw e; + }); + })); + } + _sessionForFrame(frame) { + while (!this._sessions.has(frame._id)) { + const parent = frame.parentFrame(); + if (!parent) + throw new Error(`Frame has been detached.`); + frame = parent; + } + return this._sessions.get(frame._id); + } + _sessionForHandle(handle) { + const frame = handle._context.frame; + return this._sessionForFrame(frame); + } + willBeginDownload() { + this._mainFrameSession._willBeginDownload(); + } + didClose() { + for (const session of this._sessions.values()) + session.dispose(); + this._page._didClose(); + } + async navigateFrame(frame, url2, referrer) { + return this._sessionForFrame(frame)._navigate(frame, url2, referrer); + } + async updateExtraHTTPHeaders() { + const headers = mergeHeaders([ + this._browserContext._options.extraHTTPHeaders, + this._page.extraHTTPHeaders() + ]); + await this._networkManager.setExtraHTTPHeaders(headers); + } + async updateGeolocation() { + await this._forAllFrameSessions((frame) => frame._updateGeolocation(false)); + } + async updateOffline() { + await this._networkManager.setOffline(!!this._browserContext._options.offline); + } + async updateHttpCredentials() { + await this._networkManager.authenticate(this._browserContext._options.httpCredentials || null); + } + async updateEmulatedViewportSize(preserveWindowBoundaries) { + await this._mainFrameSession._updateViewport(preserveWindowBoundaries); + } + async bringToFront() { + await this._mainFrameSession._client.send("Page.bringToFront"); + } + async updateEmulateMedia() { + await this._forAllFrameSessions((frame) => frame._updateEmulateMedia()); + } + async updateUserAgent() { + await this._forAllFrameSessions((frame) => frame._updateUserAgent()); + } + async updateRequestInterception() { + await this._networkManager.setRequestInterception(this._page.needsRequestInterception()); + } + async updateFileChooserInterception() { + await this._forAllFrameSessions((frame) => frame._updateFileChooserInterception(false)); + } + async reload() { + await this._mainFrameSession._client.send("Page.reload"); + } + async _go(delta) { + const history = await this._mainFrameSession._client.send("Page.getNavigationHistory"); + const entry = history.entries[history.currentIndex + delta]; + if (!entry) + return false; + await this._mainFrameSession._client.send("Page.navigateToHistoryEntry", { entryId: entry.id }); + return true; + } + goBack() { + return this._go(-1); + } + goForward() { + return this._go(1); + } + async requestGC() { + await this._mainFrameSession._client.send("HeapProfiler.collectGarbage"); + } + async addInitScript(initScript, world = "main") { + await this._forAllFrameSessions((frame) => frame._evaluateOnNewDocument(initScript, world)); + } + async exposePlaywrightBinding() { + await this._forAllFrameSessions((frame) => frame.exposePlaywrightBinding()); + } + async removeInitScripts(initScripts) { + await this._forAllFrameSessions((frame) => frame._removeEvaluatesOnNewDocument(initScripts)); + } + async closePage(runBeforeUnload) { + if (runBeforeUnload) + await this._mainFrameSession._client.send("Page.close"); + else + await this._browserContext._browser._closePage(this); + } + async setBackgroundColor(color) { + await this._mainFrameSession._client.send("Emulation.setDefaultBackgroundColorOverride", { color }); + } + async takeScreenshot(progress2, format, documentRect, viewportRect, quality, fitsViewport, scale) { + const { visualViewport } = await this._mainFrameSession._client.send("Page.getLayoutMetrics"); + if (!documentRect) { + documentRect = { + x: visualViewport.pageX + viewportRect.x, + y: visualViewport.pageY + viewportRect.y, + ...helper.enclosingIntSize({ + width: viewportRect.width / visualViewport.scale, + height: viewportRect.height / visualViewport.scale + }) + }; + } + const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 }; + if (scale === "css") { + const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1; + clip.scale /= deviceScaleFactor; + } + progress2.throwIfAborted(); + const result = await this._mainFrameSession._client.send("Page.captureScreenshot", { format, quality, clip, captureBeyondViewport: !fitsViewport }); + return Buffer.from(result.data, "base64"); + } + async getContentFrame(handle) { + return this._sessionForHandle(handle)._getContentFrame(handle); + } + async getOwnerFrame(handle) { + return this._sessionForHandle(handle)._getOwnerFrame(handle); + } + async getBoundingBox(handle) { + return this._sessionForHandle(handle)._getBoundingBox(handle); + } + async scrollRectIntoViewIfNeeded(handle, rect) { + return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect); + } + async setScreencastOptions(options2) { + if (options2) { + await this._mainFrameSession._startScreencast(this, { + format: "jpeg", + quality: options2.quality, + maxWidth: options2.width, + maxHeight: options2.height + }); + } else { + await this._mainFrameSession._stopScreencast(this); + } + } + rafCountForStablePosition() { + return 1; + } + async getContentQuads(handle) { + return this._sessionForHandle(handle)._getContentQuads(handle); + } + async setInputFilePaths(handle, files) { + const frame = await handle.ownerFrame(); + if (!frame) + throw new Error("Cannot set input files to detached input element"); + const parentSession = this._sessionForFrame(frame); + await parentSession._client.send("DOM.setFileInputFiles", { + objectId: handle._objectId, + files + }); + } + async adoptElementHandle(handle, to) { + return this._sessionForHandle(handle)._adoptElementHandle(handle, to); + } + async getAccessibilityTree(needle) { + return getAccessibilityTree$2(this._mainFrameSession._client, needle); + } + async inputActionEpilogue() { + await this._mainFrameSession._client.send("Page.enable").catch((e) => { + }); + } + async resetForReuse() { + await this.rawMouse.move(-1, -1, "none", /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), true); + } + async pdf(options2) { + return this._pdf.generate(options2); + } + coverage() { + return this._coverage; + } + async getFrameElement(frame) { + let parent = frame.parentFrame(); + if (!parent) + throw new Error("Frame has been detached."); + const parentSession = this._sessionForFrame(parent); + const { backendNodeId } = await parentSession._client.send("DOM.getFrameOwner", { frameId: frame._id }).catch((e) => { + if (e instanceof Error && e.message.includes("Frame with the given id was not found.")) + rewriteErrorMessage(e, "Frame has been detached."); + throw e; + }); + parent = frame.parentFrame(); + if (!parent) + throw new Error("Frame has been detached."); + return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext()); + } + shouldToggleStyleSheetToSyncAnimations() { + return false; + } +} +class FrameSession { + constructor(crPage, client, targetId, parentSession) { + this._childSessions = /* @__PURE__ */ new Set(); + this._contextIdToContext = /* @__PURE__ */ new Map(); + this._eventListeners = []; + this._firstNonInitialNavigationCommittedFulfill = () => { + }; + this._firstNonInitialNavigationCommittedReject = (e) => { + }; + this._swappedIn = false; + this._videoRecorder = null; + this._screencastId = null; + this._screencastClients = /* @__PURE__ */ new Set(); + this._workerSessions = /* @__PURE__ */ new Map(); + this._initScriptIds = /* @__PURE__ */ new Map(); + this._client = client; + this._crPage = crPage; + this._page = crPage._page; + this._targetId = targetId; + this._parentSession = parentSession; + if (parentSession) + parentSession._childSessions.add(this); + this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => { + this._firstNonInitialNavigationCommittedFulfill = f; + this._firstNonInitialNavigationCommittedReject = r; + }); + this._firstNonInitialNavigationCommittedPromise.catch(() => { + }); + } + _isMainFrame() { + return this._targetId === this._crPage._targetId; + } + _addRendererListeners() { + this._eventListeners.push(...[ + eventsHelper.addEventListener(this._client, "Log.entryAdded", (event) => this._onLogEntryAdded(event)), + eventsHelper.addEventListener(this._client, "Page.fileChooserOpened", (event) => this._onFileChooserOpened(event)), + eventsHelper.addEventListener(this._client, "Page.frameAttached", (event) => this._onFrameAttached(event.frameId, event.parentFrameId)), + eventsHelper.addEventListener(this._client, "Page.frameDetached", (event) => this._onFrameDetached(event.frameId, event.reason)), + eventsHelper.addEventListener(this._client, "Page.frameNavigated", (event) => this._onFrameNavigated(event.frame, false)), + eventsHelper.addEventListener(this._client, "Page.frameRequestedNavigation", (event) => this._onFrameRequestedNavigation(event)), + eventsHelper.addEventListener(this._client, "Page.javascriptDialogOpening", (event) => this._onDialog(event)), + eventsHelper.addEventListener(this._client, "Page.navigatedWithinDocument", (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), + eventsHelper.addEventListener(this._client, "Runtime.bindingCalled", (event) => this._onBindingCalled(event)), + eventsHelper.addEventListener(this._client, "Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)), + eventsHelper.addEventListener(this._client, "Runtime.exceptionThrown", (exception) => this._handleException(exception.exceptionDetails)), + eventsHelper.addEventListener(this._client, "Runtime.executionContextCreated", (event) => this._onExecutionContextCreated(event.context)), + eventsHelper.addEventListener(this._client, "Runtime.executionContextDestroyed", (event) => this._onExecutionContextDestroyed(event.executionContextId)), + eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", (event) => this._onExecutionContextsCleared()), + eventsHelper.addEventListener(this._client, "Target.attachedToTarget", (event) => this._onAttachedToTarget(event)), + eventsHelper.addEventListener(this._client, "Target.detachedFromTarget", (event) => this._onDetachedFromTarget(event)) + ]); + } + _addBrowserListeners() { + this._eventListeners.push(...[ + eventsHelper.addEventListener(this._client, "Inspector.targetCrashed", (event) => this._onTargetCrashed()), + eventsHelper.addEventListener(this._client, "Page.screencastFrame", (event) => this._onScreencastFrame(event)), + eventsHelper.addEventListener(this._client, "Page.windowOpen", (event) => this._onWindowOpen(event)) + ]); + } + async _initialize(hasUIWindow) { + const isSettingStorageState = this._page.browserContext.isSettingStorageState(); + if (!isSettingStorageState && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) { + const { windowId } = await this._client.send("Browser.getWindowForTarget"); + this._windowId = windowId; + } + let screencastOptions; + if (!isSettingStorageState && this._isMainFrame() && this._crPage._browserContext._options.recordVideo && hasUIWindow) { + const screencastId = createGuid(); + const outputFile = path.join(this._crPage._browserContext._options.recordVideo.dir, screencastId + ".webm"); + screencastOptions = { + // validateBrowserContextOptions ensures correct video size. + ...this._crPage._browserContext._options.recordVideo.size, + outputFile + }; + await this._crPage._browserContext._ensureVideosPath(); + await this._createVideoRecorder(screencastId, screencastOptions); + this._crPage._page.waitForInitializedOrError().then((p) => { + if (p instanceof Error) + this._stopVideoRecording().catch(() => { + }); + }); + } + let lifecycleEventsEnabled; + if (!this._isMainFrame()) + this._addRendererListeners(); + this._addBrowserListeners(); + const promises2 = [ + this._client.send("Page.enable"), + this._client.send("Page.getFrameTree").then(({ frameTree }) => { + if (this._isMainFrame()) { + this._handleFrameTree(frameTree); + this._addRendererListeners(); + } + const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)]; + for (const frame of localFrames) { + this._client._sendMayFail("Page.createIsolatedWorld", { + frameId: frame._id, + grantUniveralAccess: true, + worldName: this._crPage.utilityWorldName + }); + } + const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ":"; + if (isInitialEmptyPage) { + lifecycleEventsEnabled.catch((e) => { + }).then(() => { + this._eventListeners.push(eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event))); + }); + } else { + this._firstNonInitialNavigationCommittedFulfill(); + this._eventListeners.push(eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event))); + } + }), + this._client.send("Log.enable", {}), + lifecycleEventsEnabled = this._client.send("Page.setLifecycleEventsEnabled", { enabled: true }), + this._client.send("Runtime.enable", {}), + this._client.send("Page.addScriptToEvaluateOnNewDocument", { + source: "", + worldName: this._crPage.utilityWorldName + }), + this._crPage._networkManager.addSession(this._client, void 0, this._isMainFrame()), + this._client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }) + ]; + if (!isSettingStorageState) { + if (this._crPage._browserContext.needsPlaywrightBinding()) + promises2.push(this.exposePlaywrightBinding()); + if (this._isMainFrame()) + promises2.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true })); + const options2 = this._crPage._browserContext._options; + if (options2.bypassCSP) + promises2.push(this._client.send("Page.setBypassCSP", { enabled: true })); + if (options2.ignoreHTTPSErrors || options2.internalIgnoreHTTPSErrors) + promises2.push(this._client.send("Security.setIgnoreCertificateErrors", { ignore: true })); + if (this._isMainFrame()) + promises2.push(this._updateViewport()); + if (options2.hasTouch) + promises2.push(this._client.send("Emulation.setTouchEmulationEnabled", { enabled: true })); + if (options2.javaScriptEnabled === false) + promises2.push(this._client.send("Emulation.setScriptExecutionDisabled", { value: true })); + if (options2.userAgent || options2.locale) + promises2.push(this._updateUserAgent()); + if (options2.locale) + promises2.push(emulateLocale(this._client, options2.locale)); + if (options2.timezoneId) + promises2.push(emulateTimezone(this._client, options2.timezoneId)); + if (!this._crPage._browserContext._browser.options.headful) + promises2.push(this._setDefaultFontFamilies(this._client)); + promises2.push(this._updateGeolocation(true)); + promises2.push(this._updateEmulateMedia()); + promises2.push(this._updateFileChooserInterception(true)); + for (const initScript of this._crPage._page.allInitScripts()) + promises2.push(this._evaluateOnNewDocument( + initScript, + "main", + true + /* runImmediately */ + )); + if (screencastOptions) + promises2.push(this._startVideoRecording(screencastOptions)); + } + promises2.push(this._client.send("Runtime.runIfWaitingForDebugger")); + promises2.push(this._firstNonInitialNavigationCommittedPromise); + await Promise.all(promises2); + } + dispose() { + this._firstNonInitialNavigationCommittedReject(new TargetClosedError$1()); + for (const childSession of this._childSessions) + childSession.dispose(); + if (this._parentSession) + this._parentSession._childSessions.delete(this); + eventsHelper.removeEventListeners(this._eventListeners); + this._crPage._networkManager.removeSession(this._client); + this._crPage._sessions.delete(this._targetId); + this._client.dispose(); + } + async _navigate(frame, url2, referrer) { + const response2 = await this._client.send("Page.navigate", { url: url2, referrer, frameId: frame._id, referrerPolicy: "unsafeUrl" }); + if (response2.errorText) + throw new NavigationAbortedError(response2.loaderId, `${response2.errorText} at ${url2}`); + return { newDocumentId: response2.loaderId }; + } + _onLifecycleEvent(event) { + if (this._eventBelongsToStaleFrame(event.frameId)) + return; + if (event.name === "load") + this._page.frameManager.frameLifecycleEvent(event.frameId, "load"); + else if (event.name === "DOMContentLoaded") + this._page.frameManager.frameLifecycleEvent(event.frameId, "domcontentloaded"); + } + _handleFrameTree(frameTree) { + this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null); + this._onFrameNavigated(frameTree.frame, true); + if (!frameTree.childFrames) + return; + for (const child of frameTree.childFrames) + this._handleFrameTree(child); + } + _eventBelongsToStaleFrame(frameId) { + const frame = this._page.frameManager.frame(frameId); + if (!frame) + return true; + const session = this._crPage._sessionForFrame(frame); + return session && session !== this && !session._swappedIn; + } + _onFrameAttached(frameId, parentFrameId) { + const frameSession = this._crPage._sessions.get(frameId); + if (frameSession && frameId !== this._targetId) { + frameSession._swappedIn = true; + const frame = this._page.frameManager.frame(frameId); + if (frame) + this._page.frameManager.removeChildFramesRecursively(frame); + return; + } + if (parentFrameId && !this._page.frameManager.frame(parentFrameId)) { + return; + } + this._page.frameManager.frameAttached(frameId, parentFrameId); + } + _onFrameNavigated(framePayload, initial) { + if (this._eventBelongsToStaleFrame(framePayload.id)) + return; + this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ""), framePayload.name || "", framePayload.loaderId, initial); + if (!initial) + this._firstNonInitialNavigationCommittedFulfill(); + } + _onFrameRequestedNavigation(payload) { + if (this._eventBelongsToStaleFrame(payload.frameId)) + return; + if (payload.disposition === "currentTab") + this._page.frameManager.frameRequestedNavigation(payload.frameId); + } + _onFrameNavigatedWithinDocument(frameId, url2) { + if (this._eventBelongsToStaleFrame(frameId)) + return; + this._page.frameManager.frameCommittedSameDocumentNavigation(frameId, url2); + } + _onFrameDetached(frameId, reason) { + if (this._crPage._sessions.has(frameId)) { + return; + } + if (reason === "swap") { + const frame = this._page.frameManager.frame(frameId); + if (frame) + this._page.frameManager.removeChildFramesRecursively(frame); + return; + } + this._page.frameManager.frameDetached(frameId); + } + _onExecutionContextCreated(contextPayload) { + const frame = contextPayload.auxData ? this._page.frameManager.frame(contextPayload.auxData.frameId) : null; + if (!frame || this._eventBelongsToStaleFrame(frame._id)) + return; + const delegate = new CRExecutionContext(this._client, contextPayload); + let worldName = null; + if (contextPayload.auxData && !!contextPayload.auxData.isDefault) + worldName = "main"; + else if (contextPayload.name === this._crPage.utilityWorldName) + worldName = "utility"; + const context = new FrameExecutionContext(delegate, frame, worldName); + if (worldName) + frame._contextCreated(worldName, context); + this._contextIdToContext.set(contextPayload.id, context); + } + _onExecutionContextDestroyed(executionContextId) { + const context = this._contextIdToContext.get(executionContextId); + if (!context) + return; + this._contextIdToContext.delete(executionContextId); + context.frame._contextDestroyed(context); + } + _onExecutionContextsCleared() { + for (const contextId of Array.from(this._contextIdToContext.keys())) + this._onExecutionContextDestroyed(contextId); + } + _onAttachedToTarget(event) { + const session = this._client.createChildSession(event.sessionId); + if (event.targetInfo.type === "iframe") { + const targetId = event.targetInfo.targetId; + const frame = this._page.frameManager.frame(targetId); + if (!frame) + return; + this._page.frameManager.removeChildFramesRecursively(frame); + for (const [contextId, context] of this._contextIdToContext) { + if (context.frame === frame) + this._onExecutionContextDestroyed(contextId); + } + const frameSession = new FrameSession(this._crPage, session, targetId, this); + this._crPage._sessions.set(targetId, frameSession); + frameSession._initialize(false).catch((e) => e); + return; + } + if (event.targetInfo.type !== "worker") { + session.detach().catch(() => { + }); + return; + } + const url2 = event.targetInfo.url; + const worker = new Worker$1(this._page, url2); + this._page.addWorker(event.sessionId, worker); + this._workerSessions.set(event.sessionId, session); + session.once("Runtime.executionContextCreated", async (event2) => { + worker.createExecutionContext(new CRExecutionContext(session, event2.context)); + }); + session._sendMayFail("Runtime.enable"); + this._crPage._networkManager.addSession(session, this._page.frameManager.frame(this._targetId) ?? void 0).catch(() => { + }); + session._sendMayFail("Runtime.runIfWaitingForDebugger"); + session._sendMayFail("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }); + session.on("Target.attachedToTarget", (event2) => this._onAttachedToTarget(event2)); + session.on("Target.detachedFromTarget", (event2) => this._onDetachedFromTarget(event2)); + session.on("Runtime.consoleAPICalled", (event2) => { + const args = event2.args.map((o) => createHandle$3(worker.existingExecutionContext, o)); + this._page.addConsoleMessage(event2.type, args, toConsoleMessageLocation(event2.stackTrace)); + }); + session.on("Runtime.exceptionThrown", (exception) => this._page.emitOnContextOnceInitialized(BrowserContext$1.Events.PageError, exceptionToError(exception.exceptionDetails), this._page)); + } + _onDetachedFromTarget(event) { + const workerSession = this._workerSessions.get(event.sessionId); + if (workerSession) { + workerSession.dispose(); + this._page.removeWorker(event.sessionId); + return; + } + const childFrameSession = this._crPage._sessions.get(event.targetId); + if (!childFrameSession) + return; + if (childFrameSession._swappedIn) { + childFrameSession.dispose(); + return; + } + this._client.send("Page.enable").catch((e) => null).then(() => { + if (!childFrameSession._swappedIn) + this._page.frameManager.frameDetached(event.targetId); + childFrameSession.dispose(); + }); + } + _onWindowOpen(event) { + this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures); + } + async _onConsoleAPI(event) { + if (event.executionContextId === 0) { + return; + } + const context = this._contextIdToContext.get(event.executionContextId); + if (!context) + return; + const values = event.args.map((arg) => createHandle$3(context, arg)); + this._page.addConsoleMessage(event.type, values, toConsoleMessageLocation(event.stackTrace)); + } + async _onBindingCalled(event) { + const pageOrError = await this._crPage._page.waitForInitializedOrError(); + if (!(pageOrError instanceof Error)) { + const context = this._contextIdToContext.get(event.executionContextId); + if (context) + await this._page.onBindingCalled(event.payload, context); + } + } + _onDialog(event) { + if (!this._page.frameManager.frame(this._targetId)) + return; + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog$1( + this._page, + event.type, + event.message, + async (accept, promptText) => { + if (this._isMainFrame() && event.type === "beforeunload" && !accept) + this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, "navigation cancelled by beforeunload dialog"); + await this._client.send("Page.handleJavaScriptDialog", { accept, promptText }); + }, + event.defaultPrompt + )); + } + _handleException(exceptionDetails) { + this._page.emitOnContextOnceInitialized(BrowserContext$1.Events.PageError, exceptionToError(exceptionDetails), this._page); + } + async _onTargetCrashed() { + this._client._markAsCrashed(); + this._page._didCrash(); + } + _onLogEntryAdded(event) { + const { level, text, args, source: source2, url: url2, lineNumber } = event.entry; + if (args) + args.map((arg) => releaseObject(this._client, arg.objectId)); + if (source2 !== "worker") { + const location2 = { + url: url2 || "", + lineNumber: lineNumber || 0, + columnNumber: 0 + }; + this._page.addConsoleMessage(level, [], location2, text); + } + } + async _onFileChooserOpened(event) { + if (!event.backendNodeId) + return; + const frame = this._page.frameManager.frame(event.frameId); + if (!frame) + return; + let handle; + try { + const utilityContext = await frame._utilityContext(); + handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext); + } catch (e) { + return; + } + await this._page._onFileChooserOpened(handle); + } + _willBeginDownload() { + if (!this._crPage._page.initializedOrUndefined()) { + this._firstNonInitialNavigationCommittedReject(new Error("Starting new page download")); + } + } + _onScreencastFrame(payload) { + this._page.throttleScreencastFrameAck(() => { + this._client.send("Page.screencastFrameAck", { sessionId: payload.sessionId }).catch(() => { + }); + }); + const buffer2 = Buffer.from(payload.data, "base64"); + this._page.emit(Page$1.Events.ScreencastFrame, { + buffer: buffer2, + frameSwapWallTime: payload.metadata.timestamp ? payload.metadata.timestamp * 1e3 : void 0, + width: payload.metadata.deviceWidth, + height: payload.metadata.deviceHeight + }); + } + async _createVideoRecorder(screencastId, options2) { + assert(!this._screencastId); + const ffmpegPath = registry.findExecutable("ffmpeg").executablePathOrDie(this._page.attribution.playwright.options.sdkLanguage); + this._videoRecorder = await VideoRecorder.launch(this._crPage._page, ffmpegPath, options2); + this._screencastId = screencastId; + } + async _startVideoRecording(options2) { + const screencastId = this._screencastId; + assert(screencastId); + this._page.once(Page$1.Events.Close, () => this._stopVideoRecording().catch(() => { + })); + const gotFirstFrame = new Promise((f) => this._client.once("Page.screencastFrame", f)); + await this._startScreencast(this._videoRecorder, { + format: "jpeg", + quality: 90, + maxWidth: options2.width, + maxHeight: options2.height + }); + gotFirstFrame.then(() => { + this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options2.outputFile, this._crPage._page.waitForInitializedOrError()); + }); + } + async _stopVideoRecording() { + if (!this._screencastId) + return; + const screencastId = this._screencastId; + this._screencastId = null; + const recorder = this._videoRecorder; + this._videoRecorder = null; + await this._stopScreencast(recorder); + await recorder.stop().catch(() => { + }); + const video = this._crPage._browserContext._browser._takeVideo(screencastId); + video == null ? void 0 : video.reportFinished(); + } + async _startScreencast(client, options2 = {}) { + this._screencastClients.add(client); + if (this._screencastClients.size === 1) + await this._client.send("Page.startScreencast", options2); + } + async _stopScreencast(client) { + this._screencastClients.delete(client); + if (!this._screencastClients.size) + await this._client._sendMayFail("Page.stopScreencast"); + } + async _updateGeolocation(initial) { + const geolocation = this._crPage._browserContext._options.geolocation; + if (!initial || geolocation) + await this._client.send("Emulation.setGeolocationOverride", geolocation || {}); + } + async _updateViewport(preserveWindowBoundaries) { + if (this._crPage._browserContext._browser.isClank()) + return; + assert(this._isMainFrame()); + const options2 = this._crPage._browserContext._options; + const emulatedSize = this._page.emulatedSize(); + if (!emulatedSize) + return; + const viewportSize = emulatedSize.viewport; + const screenSize = emulatedSize.screen; + const isLandscape = screenSize.width > screenSize.height; + const metricsOverride = { + mobile: !!options2.isMobile, + width: viewportSize.width, + height: viewportSize.height, + screenWidth: screenSize.width, + screenHeight: screenSize.height, + deviceScaleFactor: options2.deviceScaleFactor || 1, + screenOrientation: !!options2.isMobile ? isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" } : { angle: 0, type: "landscapePrimary" }, + dontSetVisibleSize: preserveWindowBoundaries + }; + if (JSON.stringify(this._metricsOverride) === JSON.stringify(metricsOverride)) + return; + const promises2 = []; + if (!preserveWindowBoundaries && this._windowId) { + let insets = { width: 0, height: 0 }; + if (this._crPage._browserContext._browser.options.headful) { + insets = { width: 24, height: 88 }; + if (process.platform === "win32") + insets = { width: 16, height: 88 }; + else if (process.platform === "linux") + insets = { width: 8, height: 85 }; + else if (process.platform === "darwin") + insets = { width: 2, height: 80 }; + if (this._crPage._browserContext.isPersistentContext()) { + insets.height += 46; + } + } + promises2.push(this.setWindowBounds({ + width: viewportSize.width + insets.width, + height: viewportSize.height + insets.height + })); + } + promises2.push(this._client.send("Emulation.setDeviceMetricsOverride", metricsOverride)); + await Promise.all(promises2); + this._metricsOverride = metricsOverride; + } + async windowBounds() { + const { bounds } = await this._client.send("Browser.getWindowBounds", { + windowId: this._windowId + }); + return bounds; + } + async setWindowBounds(bounds) { + return await this._client.send("Browser.setWindowBounds", { + windowId: this._windowId, + bounds + }); + } + async _updateEmulateMedia() { + const emulatedMedia = this._page.emulatedMedia(); + const media = emulatedMedia.media === "no-override" ? "" : emulatedMedia.media; + const colorScheme = emulatedMedia.colorScheme === "no-override" ? "" : emulatedMedia.colorScheme; + const reducedMotion = emulatedMedia.reducedMotion === "no-override" ? "" : emulatedMedia.reducedMotion; + const forcedColors = emulatedMedia.forcedColors === "no-override" ? "" : emulatedMedia.forcedColors; + const contrast = emulatedMedia.contrast === "no-override" ? "" : emulatedMedia.contrast; + const features = [ + { name: "prefers-color-scheme", value: colorScheme }, + { name: "prefers-reduced-motion", value: reducedMotion }, + { name: "forced-colors", value: forcedColors }, + { name: "prefers-contrast", value: contrast } + ]; + await this._client.send("Emulation.setEmulatedMedia", { media, features }); + } + async _updateUserAgent() { + const options2 = this._crPage._browserContext._options; + await this._client.send("Emulation.setUserAgentOverride", { + userAgent: options2.userAgent || "", + acceptLanguage: options2.locale, + userAgentMetadata: calculateUserAgentMetadata(options2) + }); + } + async _setDefaultFontFamilies(session) { + const fontFamilies = platformToFontFamilies[this._crPage._browserContext._browser._platform()]; + await session.send("Page.setFontFamilies", fontFamilies); + } + async _updateFileChooserInterception(initial) { + const enabled = this._page.fileChooserIntercepted(); + if (initial && !enabled) + return; + await this._client.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => { + }); + } + async _evaluateOnNewDocument(initScript, world, runImmediately) { + const worldName = world === "utility" ? this._crPage.utilityWorldName : void 0; + const { identifier } = await this._client.send("Page.addScriptToEvaluateOnNewDocument", { source: initScript.source, worldName, runImmediately }); + this._initScriptIds.set(initScript, identifier); + } + async _removeEvaluatesOnNewDocument(initScripts) { + const ids = []; + for (const script of initScripts) { + const id = this._initScriptIds.get(script); + if (id) + ids.push(id); + this._initScriptIds.delete(script); + } + await Promise.all(ids.map((identifier) => this._client.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => { + }))); + } + async exposePlaywrightBinding() { + await this._client.send("Runtime.addBinding", { name: PageBinding.kBindingName }); + } + async _getContentFrame(handle) { + const nodeInfo = await this._client.send("DOM.describeNode", { + objectId: handle._objectId + }); + if (!nodeInfo || typeof nodeInfo.node.frameId !== "string") + return null; + return this._page.frameManager.frame(nodeInfo.node.frameId); + } + async _getOwnerFrame(handle) { + const documentElement = await handle.evaluateHandle((node2) => { + const doc = node2; + if (doc.documentElement && doc.documentElement.ownerDocument === doc) + return doc.documentElement; + return node2.ownerDocument ? node2.ownerDocument.documentElement : null; + }); + if (!documentElement) + return null; + if (!documentElement._objectId) + return null; + const nodeInfo = await this._client.send("DOM.describeNode", { + objectId: documentElement._objectId + }); + const frameId = nodeInfo && typeof nodeInfo.node.frameId === "string" ? nodeInfo.node.frameId : null; + documentElement.dispose(); + return frameId; + } + async _getBoundingBox(handle) { + const result = await this._client._sendMayFail("DOM.getBoxModel", { + objectId: handle._objectId + }); + if (!result) + return null; + const quad = result.model.border; + const x = Math.min(quad[0], quad[2], quad[4], quad[6]); + const y = Math.min(quad[1], quad[3], quad[5], quad[7]); + const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x; + const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y; + const position = await this._framePosition(); + if (!position) + return null; + return { x: x + position.x, y: y + position.y, width, height }; + } + async _framePosition() { + const frame = this._page.frameManager.frame(this._targetId); + if (!frame) + return null; + if (frame === this._page.mainFrame()) + return { x: 0, y: 0 }; + const element = await frame.frameElement(); + const box = await element.boundingBox(); + return box; + } + async _scrollRectIntoViewIfNeeded(handle, rect) { + return await this._client.send("DOM.scrollIntoViewIfNeeded", { + objectId: handle._objectId, + rect + }).then(() => "done").catch((e) => { + if (e instanceof Error && e.message.includes("Node does not have a layout object")) + return "error:notvisible"; + if (e instanceof Error && e.message.includes("Node is detached from document")) + return "error:notconnected"; + throw e; + }); + } + async _getContentQuads(handle) { + const result = await this._client._sendMayFail("DOM.getContentQuads", { + objectId: handle._objectId + }); + if (!result) + return null; + const position = await this._framePosition(); + if (!position) + return null; + return result.quads.map((quad) => [ + { x: quad[0] + position.x, y: quad[1] + position.y }, + { x: quad[2] + position.x, y: quad[3] + position.y }, + { x: quad[4] + position.x, y: quad[5] + position.y }, + { x: quad[6] + position.x, y: quad[7] + position.y } + ]); + } + async _adoptElementHandle(handle, to) { + const nodeInfo = await this._client.send("DOM.describeNode", { + objectId: handle._objectId + }); + return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to); + } + async _adoptBackendNodeId(backendNodeId, to) { + const result = await this._client._sendMayFail("DOM.resolveNode", { + backendNodeId, + executionContextId: to.delegate._contextId + }); + if (!result || result.object.subtype === "null") + throw new Error(kUnableToAdoptErrorMessage); + return createHandle$3(to, result.object).asElement(); + } +} +async function emulateLocale(session, locale) { + try { + await session.send("Emulation.setLocaleOverride", { locale }); + } catch (exception) { + if (exception.message.includes("Another locale override is already in effect")) + return; + throw exception; + } +} +async function emulateTimezone(session, timezoneId) { + try { + await session.send("Emulation.setTimezoneOverride", { timezoneId }); + } catch (exception) { + if (exception.message.includes("Timezone override is already in effect")) + return; + if (exception.message.includes("Invalid timezone")) + throw new Error(`Invalid timezone ID: ${timezoneId}`); + throw exception; + } +} +function calculateUserAgentMetadata(options2) { + const ua = options2.userAgent; + if (!ua) + return void 0; + const metadata = { + mobile: !!options2.isMobile, + model: "", + architecture: "x86", + platform: "Windows", + platformVersion: "" + }; + const androidMatch = ua.match(/Android (\d+(\.\d+)?(\.\d+)?)/); + const iPhoneMatch = ua.match(/iPhone OS (\d+(_\d+)?)/); + const iPadMatch = ua.match(/iPad; CPU OS (\d+(_\d+)?)/); + const macOSMatch = ua.match(/Mac OS X (\d+(_\d+)?(_\d+)?)/); + const windowsMatch = ua.match(/Windows\D+(\d+(\.\d+)?(\.\d+)?)/); + if (androidMatch) { + metadata.platform = "Android"; + metadata.platformVersion = androidMatch[1]; + metadata.architecture = "arm"; + } else if (iPhoneMatch) { + metadata.platform = "iOS"; + metadata.platformVersion = iPhoneMatch[1]; + metadata.architecture = "arm"; + } else if (iPadMatch) { + metadata.platform = "iOS"; + metadata.platformVersion = iPadMatch[1]; + metadata.architecture = "arm"; + } else if (macOSMatch) { + metadata.platform = "macOS"; + metadata.platformVersion = macOSMatch[1]; + if (!ua.includes("Intel")) + metadata.architecture = "arm"; + } else if (windowsMatch) { + metadata.platform = "Windows"; + metadata.platformVersion = windowsMatch[1]; + } else if (ua.toLowerCase().includes("linux")) { + metadata.platform = "Linux"; + } + if (ua.includes("ARM")) + metadata.architecture = "arm"; + return metadata; +} +class CRServiceWorker extends Worker$1 { + constructor(browserContext, session, url2) { + super(browserContext, url2); + this._session = session; + this.browserContext = browserContext; + if (!!define_process_env_default.PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS) + this._networkManager = new CRNetworkManager(null, this); + session.once("Runtime.executionContextCreated", (event) => { + this.createExecutionContext(new CRExecutionContext(session, event.context)); + }); + if (this._networkManager && this._isNetworkInspectionEnabled()) { + this.updateRequestInterception(); + this.updateExtraHTTPHeaders(); + this.updateHttpCredentials(); + this.updateOffline(); + this._networkManager.addSession( + session, + void 0, + true + /* isMain */ + ).catch(() => { + }); + } + session.send("Runtime.enable", {}).catch((e) => { + }); + session.send("Runtime.runIfWaitingForDebugger").catch((e) => { + }); + session.on("Inspector.targetReloadedAfterCrash", () => { + session._sendMayFail("Runtime.runIfWaitingForDebugger", {}); + }); + } + didClose() { + var _a2; + (_a2 = this._networkManager) == null ? void 0 : _a2.removeSession(this._session); + this._session.dispose(); + super.didClose(); + } + async updateOffline() { + var _a2; + if (!this._isNetworkInspectionEnabled()) + return; + await ((_a2 = this._networkManager) == null ? void 0 : _a2.setOffline(!!this.browserContext._options.offline).catch(() => { + })); + } + async updateHttpCredentials() { + var _a2; + if (!this._isNetworkInspectionEnabled()) + return; + await ((_a2 = this._networkManager) == null ? void 0 : _a2.authenticate(this.browserContext._options.httpCredentials || null).catch(() => { + })); + } + async updateExtraHTTPHeaders() { + var _a2; + if (!this._isNetworkInspectionEnabled()) + return; + await ((_a2 = this._networkManager) == null ? void 0 : _a2.setExtraHTTPHeaders(this.browserContext._options.extraHTTPHeaders || []).catch(() => { + })); + } + async updateRequestInterception() { + var _a2; + if (!this._isNetworkInspectionEnabled()) + return; + await ((_a2 = this._networkManager) == null ? void 0 : _a2.setRequestInterception(this.needsRequestInterception()).catch(() => { + })); + } + needsRequestInterception() { + return this._isNetworkInspectionEnabled() && this.browserContext.requestInterceptors.length > 0; + } + reportRequestFinished(request2, response2) { + this.browserContext.emit(BrowserContext$1.Events.RequestFinished, { request: request2, response: response2 }); + } + requestFailed(request2, _canceled) { + this.browserContext.emit(BrowserContext$1.Events.RequestFailed, request2); + } + requestReceivedResponse(response2) { + this.browserContext.emit(BrowserContext$1.Events.Response, response2); + } + requestStarted(request2, route) { + this.browserContext.emit(BrowserContext$1.Events.Request, request2); + if (route) + new Route$1(request2, route).handle(this.browserContext.requestInterceptors); + } + _isNetworkInspectionEnabled() { + return this.browserContext._options.serviceWorkers !== "block"; + } +} +class CRBrowser extends Browser$1 { + constructor(parent, connection, options2) { + super(parent, options2); + this._clientRootSessionPromise = null; + this._contexts = /* @__PURE__ */ new Map(); + this._crPages = /* @__PURE__ */ new Map(); + this._backgroundPages = /* @__PURE__ */ new Map(); + this._serviceWorkers = /* @__PURE__ */ new Map(); + this._version = ""; + this._tracingRecording = false; + this._userAgent = ""; + this._connection = connection; + this._session = this._connection.rootSession; + this._connection.on(ConnectionEvents$1.Disconnected, () => this._didDisconnect()); + this._session.on("Target.attachedToTarget", this._onAttachedToTarget.bind(this)); + this._session.on("Target.detachedFromTarget", this._onDetachedFromTarget.bind(this)); + this._session.on("Browser.downloadWillBegin", this._onDownloadWillBegin.bind(this)); + this._session.on("Browser.downloadProgress", this._onDownloadProgress.bind(this)); + } + static async connect(parent, transport, options2, devtools) { + options2 = { ...options2 }; + const connection = new CRConnection(transport, options2.protocolLogger, options2.browserLogsCollector); + const browser2 = new CRBrowser(parent, connection, options2); + browser2._devtools = devtools; + if (browser2.isClank()) + browser2._isCollocatedWithServer = false; + const session = connection.rootSession; + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + const version2 = await session.send("Browser.getVersion"); + browser2._version = version2.product.substring(version2.product.indexOf("/") + 1); + browser2._userAgent = version2.userAgent; + browser2.options.headful = !version2.userAgent.includes("Headless"); + if (!options2.persistent) { + await session.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }); + return browser2; + } + browser2._defaultContext = new CRBrowserContext(browser2, void 0, options2.persistent); + await Promise.all([ + session.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }).then(async () => { + await session.send("Target.getTargetInfo"); + }), + browser2._defaultContext._initialize() + ]); + await browser2._waitForAllPagesToBeInitialized(); + return browser2; + } + async doCreateNewContext(options2) { + const proxy = options2.proxyOverride || options2.proxy; + let proxyBypassList = void 0; + if (proxy) { + if (define_process_env_default.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK) + proxyBypassList = proxy.bypass; + else + proxyBypassList = "<-loopback>" + (proxy.bypass ? `,${proxy.bypass}` : ""); + } + const { browserContextId } = await this._session.send("Target.createBrowserContext", { + disposeOnDetach: true, + proxyServer: proxy ? proxy.server : void 0, + proxyBypassList + }); + const context = new CRBrowserContext(this, browserContextId, options2); + await context._initialize(); + this._contexts.set(browserContextId, context); + return context; + } + contexts() { + return Array.from(this._contexts.values()); + } + version() { + return this._version; + } + userAgent() { + return this._userAgent; + } + _platform() { + if (this._userAgent.includes("Windows")) + return "win"; + if (this._userAgent.includes("Macintosh")) + return "mac"; + return "linux"; + } + isClank() { + return this.options.name === "clank"; + } + async _waitForAllPagesToBeInitialized() { + await Promise.all([...this._crPages.values()].map((crPage) => crPage._page.waitForInitializedOrError())); + } + _onAttachedToTarget({ targetInfo, sessionId, waitingForDebugger }) { + if (targetInfo.type === "browser") + return; + const session = this._session.createChildSession(sessionId); + assert(targetInfo.browserContextId, "targetInfo: " + JSON.stringify(targetInfo, null, 2)); + let context = this._contexts.get(targetInfo.browserContextId) || null; + if (!context) { + context = this._defaultContext; + } + if (targetInfo.type === "other" && targetInfo.url.startsWith("devtools://devtools") && this._devtools) { + this._devtools.install(session); + return; + } + const treatOtherAsPage = targetInfo.type === "other" && define_process_env_default.PW_CHROMIUM_ATTACH_TO_OTHER; + if (!context || targetInfo.type === "other" && !treatOtherAsPage) { + session.detach().catch(() => { + }); + return; + } + assert(!this._crPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId); + assert(!this._backgroundPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId); + assert(!this._serviceWorkers.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId); + if (targetInfo.type === "background_page") { + const backgroundPage = new CRPage(session, targetInfo.targetId, context, null, { hasUIWindow: false, isBackgroundPage: true }); + this._backgroundPages.set(targetInfo.targetId, backgroundPage); + return; + } + if (targetInfo.type === "page" || treatOtherAsPage) { + const opener = targetInfo.openerId ? this._crPages.get(targetInfo.openerId) || null : null; + const crPage = new CRPage(session, targetInfo.targetId, context, opener, { hasUIWindow: targetInfo.type === "page", isBackgroundPage: false }); + this._crPages.set(targetInfo.targetId, crPage); + return; + } + if (targetInfo.type === "service_worker") { + const serviceWorker = new CRServiceWorker(context, session, targetInfo.url); + this._serviceWorkers.set(targetInfo.targetId, serviceWorker); + context.emit(CRBrowserContext.CREvents.ServiceWorker, serviceWorker); + return; + } + session.detach().catch(() => { + }); + } + _onDetachedFromTarget(payload) { + const targetId = payload.targetId; + const crPage = this._crPages.get(targetId); + if (crPage) { + this._crPages.delete(targetId); + crPage.didClose(); + return; + } + const backgroundPage = this._backgroundPages.get(targetId); + if (backgroundPage) { + this._backgroundPages.delete(targetId); + backgroundPage.didClose(); + return; + } + const serviceWorker = this._serviceWorkers.get(targetId); + if (serviceWorker) { + this._serviceWorkers.delete(targetId); + serviceWorker.didClose(); + return; + } + } + _didDisconnect() { + for (const crPage of this._crPages.values()) + crPage.didClose(); + this._crPages.clear(); + for (const backgroundPage of this._backgroundPages.values()) + backgroundPage.didClose(); + this._backgroundPages.clear(); + for (const serviceWorker of this._serviceWorkers.values()) + serviceWorker.didClose(); + this._serviceWorkers.clear(); + this._didClose(); + } + _findOwningPage(frameId) { + for (const crPage of this._crPages.values()) { + const frame = crPage._page.frameManager.frame(frameId); + if (frame) + return crPage; + } + return null; + } + _onDownloadWillBegin(payload) { + const page = this._findOwningPage(payload.frameId); + if (!page) { + return; + } + page.willBeginDownload(); + let originPage = page._page.initializedOrUndefined(); + if (!originPage && page._opener) + originPage = page._opener._page.initializedOrUndefined(); + if (!originPage) + return; + this._downloadCreated(originPage, payload.guid, payload.url, payload.suggestedFilename); + } + _onDownloadProgress(payload) { + if (payload.state === "completed") + this._downloadFinished(payload.guid, ""); + if (payload.state === "canceled") + this._downloadFinished(payload.guid, this._closeReason || "canceled"); + } + async _closePage(crPage) { + await this._session.send("Target.closeTarget", { targetId: crPage._targetId }); + } + async newBrowserCDPSession() { + return await this._connection.createBrowserSession(); + } + async startTracing(page, options2 = {}) { + assert(!this._tracingRecording, "Cannot start recording trace while already recording trace."); + this._tracingClient = page ? page.delegate._mainFrameSession._client : this._session; + const defaultCategories = [ + "-*", + "devtools.timeline", + "v8.execute", + "disabled-by-default-devtools.timeline", + "disabled-by-default-devtools.timeline.frame", + "toplevel", + "blink.console", + "blink.user_timing", + "latencyInfo", + "disabled-by-default-devtools.timeline.stack", + "disabled-by-default-v8.cpu_profiler", + "disabled-by-default-v8.cpu_profiler.hires" + ]; + const { + screenshots = false, + categories = defaultCategories + } = options2; + if (screenshots) + categories.push("disabled-by-default-devtools.screenshot"); + this._tracingRecording = true; + await this._tracingClient.send("Tracing.start", { + transferMode: "ReturnAsStream", + categories: categories.join(",") + }); + } + async stopTracing() { + assert(this._tracingClient, "Tracing was not started."); + const [event] = await Promise.all([ + new Promise((f) => this._tracingClient.once("Tracing.tracingComplete", f)), + this._tracingClient.send("Tracing.end") + ]); + const tracingPath = path.join(this.options.artifactsDir, createGuid() + ".crtrace"); + await saveProtocolStream(this._tracingClient, event.stream, tracingPath); + this._tracingRecording = false; + const artifact = new Artifact$1(this, tracingPath); + artifact.reportFinished(); + return artifact; + } + isConnected() { + return !this._connection._closed; + } + async _clientRootSession() { + if (!this._clientRootSessionPromise) + this._clientRootSessionPromise = this._connection.createBrowserSession(); + return this._clientRootSessionPromise; + } +} +const _CRBrowserContext = class _CRBrowserContext2 extends BrowserContext$1 { + constructor(browser2, browserContextId, options2) { + super(browser2, options2, browserContextId); + this._authenticateProxyViaCredentials(); + } + async _initialize() { + assert(!Array.from(this._browser._crPages.values()).some((page) => page._browserContext === this)); + const promises2 = [super._initialize()]; + if (this._browser.options.name !== "clank" && this._options.acceptDownloads !== "internal-browser-default") { + promises2.push(this._browser._session.send("Browser.setDownloadBehavior", { + behavior: this._options.acceptDownloads === "accept" ? "allowAndName" : "deny", + browserContextId: this._browserContextId, + downloadPath: this._browser.options.downloadsPath, + eventsEnabled: true + })); + } + await Promise.all(promises2); + } + _crPages() { + return [...this._browser._crPages.values()].filter((crPage) => crPage._browserContext === this); + } + possiblyUninitializedPages() { + return this._crPages().map((crPage) => crPage._page); + } + async doCreateNewPage(markAsServerSideOnly) { + const { targetId } = await this._browser._session.send("Target.createTarget", { url: "about:blank", browserContextId: this._browserContextId }); + const page = this._browser._crPages.get(targetId)._page; + if (markAsServerSideOnly) + page.markAsServerSideOnly(); + return page; + } + async doGetCookies(urls) { + const { cookies } = await this._browser._session.send("Storage.getCookies", { browserContextId: this._browserContextId }); + return filterCookies(cookies.map((c) => { + const copy = { sameSite: "Lax", ...c }; + delete copy.size; + delete copy.priority; + delete copy.session; + delete copy.sameParty; + delete copy.sourceScheme; + delete copy.sourcePort; + return copy; + }), urls); + } + async addCookies(cookies) { + await this._browser._session.send("Storage.setCookies", { cookies: rewriteCookies(cookies), browserContextId: this._browserContextId }); + } + async doClearCookies() { + await this._browser._session.send("Storage.clearCookies", { browserContextId: this._browserContextId }); + } + async doGrantPermissions(origin, permissions) { + const webPermissionToProtocol = /* @__PURE__ */ new Map([ + ["geolocation", "geolocation"], + ["midi", "midi"], + ["notifications", "notifications"], + ["camera", "videoCapture"], + ["microphone", "audioCapture"], + ["background-sync", "backgroundSync"], + ["ambient-light-sensor", "sensors"], + ["accelerometer", "sensors"], + ["gyroscope", "sensors"], + ["magnetometer", "sensors"], + ["clipboard-read", "clipboardReadWrite"], + ["clipboard-write", "clipboardSanitizedWrite"], + ["payment-handler", "paymentHandler"], + // chrome-specific permissions we have. + ["midi-sysex", "midiSysex"], + ["storage-access", "storageAccess"] + ]); + const filtered = permissions.map((permission) => { + const protocolPermission = webPermissionToProtocol.get(permission); + if (!protocolPermission) + throw new Error("Unknown permission: " + permission); + return protocolPermission; + }); + await this._browser._session.send("Browser.grantPermissions", { origin: origin === "*" ? void 0 : origin, browserContextId: this._browserContextId, permissions: filtered }); + } + async doClearPermissions() { + await this._browser._session.send("Browser.resetPermissions", { browserContextId: this._browserContextId }); + } + async setGeolocation(geolocation) { + verifyGeolocation(geolocation); + this._options.geolocation = geolocation; + for (const page of this.pages()) + await page.delegate.updateGeolocation(); + } + async setExtraHTTPHeaders(headers) { + this._options.extraHTTPHeaders = headers; + for (const page of this.pages()) + await page.delegate.updateExtraHTTPHeaders(); + for (const sw of this.serviceWorkers()) + await sw.updateExtraHTTPHeaders(); + } + async setUserAgent(userAgent) { + this._options.userAgent = userAgent; + for (const page of this.pages()) + await page.delegate.updateUserAgent(); + } + async setOffline(offline) { + this._options.offline = offline; + for (const page of this.pages()) + await page.delegate.updateOffline(); + for (const sw of this.serviceWorkers()) + await sw.updateOffline(); + } + async doSetHTTPCredentials(httpCredentials) { + this._options.httpCredentials = httpCredentials; + for (const page of this.pages()) + await page.delegate.updateHttpCredentials(); + for (const sw of this.serviceWorkers()) + await sw.updateHttpCredentials(); + } + async doAddInitScript(initScript) { + for (const page of this.pages()) + await page.delegate.addInitScript(initScript); + } + async doRemoveInitScripts(initScripts) { + for (const page of this.pages()) + await page.delegate.removeInitScripts(initScripts); + } + async doUpdateRequestInterception() { + for (const page of this.pages()) + await page.delegate.updateRequestInterception(); + for (const sw of this.serviceWorkers()) + await sw.updateRequestInterception(); + } + async doExposePlaywrightBinding() { + for (const page of this._crPages()) + await page.exposePlaywrightBinding(); + } + async doClose(reason) { + await this.dialogManager.closeBeforeUnloadDialogs(); + if (!this._browserContextId) { + await this.stopVideoRecording(); + await this._browser.close({ reason }); + return; + } + await this._browser._session.send("Target.disposeBrowserContext", { browserContextId: this._browserContextId }); + this._browser._contexts.delete(this._browserContextId); + for (const [targetId, serviceWorker] of this._browser._serviceWorkers) { + if (serviceWorker.browserContext !== this) + continue; + serviceWorker.didClose(); + this._browser._serviceWorkers.delete(targetId); + } + } + async stopVideoRecording() { + await Promise.all(this._crPages().map((crPage) => crPage._mainFrameSession._stopVideoRecording())); + } + onClosePersistent() { + for (const [targetId, backgroundPage] of this._browser._backgroundPages.entries()) { + if (backgroundPage._browserContext === this && backgroundPage._page.initializedOrUndefined()) { + backgroundPage.didClose(); + this._browser._backgroundPages.delete(targetId); + } + } + } + async clearCache() { + for (const page of this._crPages()) + await page._networkManager.clearCache(); + } + async cancelDownload(guid) { + await this._browser._session.send("Browser.cancelDownload", { + guid, + browserContextId: this._browserContextId + }); + } + backgroundPages() { + const result = []; + for (const backgroundPage of this._browser._backgroundPages.values()) { + if (backgroundPage._browserContext === this && backgroundPage._page.initializedOrUndefined()) + result.push(backgroundPage._page); + } + return result; + } + serviceWorkers() { + return Array.from(this._browser._serviceWorkers.values()).filter((serviceWorker) => serviceWorker.browserContext === this); + } + async newCDPSession(page) { + let targetId = null; + if (page instanceof Page$1) { + targetId = page.delegate._targetId; + } else if (page instanceof Frame$1) { + const session = page._page.delegate._sessions.get(page._id); + if (!session) + throw new Error(`This frame does not have a separate CDP session, it is a part of the parent frame's session`); + targetId = session._targetId; + } else { + throw new Error("page: expected Page or Frame"); + } + const rootSession = await this._browser._clientRootSession(); + return rootSession.attachToTarget(targetId); + } +}; +_CRBrowserContext.CREvents = { + BackgroundPage: "backgroundpage", + ServiceWorker: "serviceworker" +}; +let CRBrowserContext = _CRBrowserContext; +class WritableStreamDispatcher extends Dispatcher { + constructor(scope, streamOrDirectory, lastModifiedMs) { + super(scope, { guid: "writableStream@" + createGuid(), streamOrDirectory }, "WritableStream", {}); + this._type_WritableStream = true; + this._lastModifiedMs = lastModifiedMs; + } + async write(params) { + if (typeof this._object.streamOrDirectory === "string") + throw new Error("Cannot write to a directory"); + const stream2 = this._object.streamOrDirectory; + await new Promise((fulfill, reject) => { + stream2.write(params.binary, (error2) => { + if (error2) + reject(error2); + else + fulfill(); + }); + }); + } + async close() { + if (typeof this._object.streamOrDirectory === "string") + throw new Error("Cannot close a directory"); + const stream2 = this._object.streamOrDirectory; + await new Promise((fulfill) => stream2.end(fulfill)); + if (this._lastModifiedMs) + await fs.promises.utimes(this.path(), new Date(this._lastModifiedMs), new Date(this._lastModifiedMs)); + } + path() { + if (typeof this._object.streamOrDirectory === "string") + return this._object.streamOrDirectory; + return this._object.streamOrDirectory.path; + } +} +class BrowserContextDispatcher extends Dispatcher { + constructor(parentScope, context) { + const requestContext = APIRequestContextDispatcher.from(parentScope, context.fetchRequest); + const tracing = TracingDispatcher.from(parentScope, context.tracing); + super(parentScope, context, "BrowserContext", { + isChromium: context._browser.options.isChromium, + requestContext, + tracing, + options: context._options + }); + this._type_EventTarget = true; + this._type_BrowserContext = true; + this._subscriptions = /* @__PURE__ */ new Set(); + this._webSocketInterceptionPatterns = []; + this._bindings = []; + this._initScritps = []; + this._clockPaused = false; + this._interceptionUrlMatchers = []; + this.adopt(requestContext); + this.adopt(tracing); + this._requestInterceptor = (route, request2) => { + const matchesSome = this._interceptionUrlMatchers.some((urlMatch) => urlMatches(this._context._options.baseURL, request2.url(), urlMatch)); + const routeDispatcher = this.connection.existingDispatcher(route); + if (!matchesSome || routeDispatcher) { + route.continue({ isFallback: true }).catch(() => { + }); + return; + } + this._dispatchEvent("route", { route: new RouteDispatcher(RequestDispatcher.from(this, request2), route) }); + }; + this._context = context; + const onVideo = (artifact) => { + const artifactDispatcher = ArtifactDispatcher.from(parentScope, artifact); + this._dispatchEvent("video", { artifact: artifactDispatcher }); + }; + this.addObjectListener(BrowserContext$1.Events.VideoStarted, onVideo); + for (const video of context._browser._idToVideo.values()) { + if (video.context === context) + onVideo(video.artifact); + } + for (const page of context.pages()) + this._dispatchEvent("page", { page: PageDispatcher.from(this, page) }); + this.addObjectListener(BrowserContext$1.Events.Page, (page) => { + this._dispatchEvent("page", { page: PageDispatcher.from(this, page) }); + }); + this.addObjectListener(BrowserContext$1.Events.Close, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + this.addObjectListener(BrowserContext$1.Events.PageError, (error2, page) => { + this._dispatchEvent("pageError", { error: serializeError$1(error2), page: PageDispatcher.from(this, page) }); + }); + this.addObjectListener(BrowserContext$1.Events.Console, (message) => { + const page = message.page(); + if (this._shouldDispatchEvent(page, "console")) { + const pageDispatcher = PageDispatcher.from(this, page); + this._dispatchEvent("console", { + page: pageDispatcher, + type: message.type(), + text: message.text(), + args: message.args().map((a) => { + const elementHandle = a.asElement(); + if (elementHandle) + return ElementHandleDispatcher.from(FrameDispatcher.from(this, elementHandle._frame), elementHandle); + return JSHandleDispatcher.fromJSHandle(pageDispatcher, a); + }), + location: message.location() + }); + } + }); + this._dialogHandler = (dialog) => { + if (!this._shouldDispatchEvent(dialog.page(), "dialog")) + return false; + this._dispatchEvent("dialog", { dialog: new DialogDispatcher(this, dialog) }); + return true; + }; + context.dialogManager.addDialogHandler(this._dialogHandler); + if (context._browser.options.name === "chromium") { + for (const page of context.backgroundPages()) + this._dispatchEvent("backgroundPage", { page: PageDispatcher.from(this, page) }); + this.addObjectListener(CRBrowserContext.CREvents.BackgroundPage, (page) => this._dispatchEvent("backgroundPage", { page: PageDispatcher.from(this, page) })); + for (const serviceWorker of context.serviceWorkers()) + this._dispatchEvent("serviceWorker", { worker: new WorkerDispatcher(this, serviceWorker) }); + this.addObjectListener(CRBrowserContext.CREvents.ServiceWorker, (serviceWorker) => this._dispatchEvent("serviceWorker", { worker: new WorkerDispatcher(this, serviceWorker) })); + } + this.addObjectListener(BrowserContext$1.Events.Request, (request2) => { + var _a2; + const redirectFromDispatcher = request2.redirectedFrom() && this.connection.existingDispatcher(request2.redirectedFrom()); + if (!redirectFromDispatcher && !this._shouldDispatchNetworkEvent(request2, "request") && !request2.isNavigationRequest()) + return; + const requestDispatcher = RequestDispatcher.from(this, request2); + this._dispatchEvent("request", { + request: requestDispatcher, + page: PageDispatcher.fromNullable(this, (_a2 = request2.frame()) == null ? void 0 : _a2._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext$1.Events.Response, (response2) => { + var _a2; + const requestDispatcher = this.connection.existingDispatcher(response2.request()); + if (!requestDispatcher && !this._shouldDispatchNetworkEvent(response2.request(), "response")) + return; + this._dispatchEvent("response", { + response: ResponseDispatcher.from(this, response2), + page: PageDispatcher.fromNullable(this, (_a2 = response2.frame()) == null ? void 0 : _a2._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext$1.Events.RequestFailed, (request2) => { + var _a2; + const requestDispatcher = this.connection.existingDispatcher(request2); + if (!requestDispatcher && !this._shouldDispatchNetworkEvent(request2, "requestFailed")) + return; + this._dispatchEvent("requestFailed", { + request: RequestDispatcher.from(this, request2), + failureText: request2._failureText || void 0, + responseEndTiming: request2._responseEndTiming, + page: PageDispatcher.fromNullable(this, (_a2 = request2.frame()) == null ? void 0 : _a2._page.initializedOrUndefined()) + }); + }); + this.addObjectListener(BrowserContext$1.Events.RequestFinished, ({ request: request2, response: response2 }) => { + var _a2; + const requestDispatcher = this.connection.existingDispatcher(request2); + if (!requestDispatcher && !this._shouldDispatchNetworkEvent(request2, "requestFinished")) + return; + this._dispatchEvent("requestFinished", { + request: RequestDispatcher.from(this, request2), + response: ResponseDispatcher.fromNullable(this, response2), + responseEndTiming: request2._responseEndTiming, + page: PageDispatcher.fromNullable(this, (_a2 = request2.frame()) == null ? void 0 : _a2._page.initializedOrUndefined()) + }); + }); + } + static from(parentScope, context) { + const result = parentScope.connection.existingDispatcher(context); + return result || new BrowserContextDispatcher(parentScope, context); + } + _shouldDispatchNetworkEvent(request2, event) { + var _a2, _b2; + return this._shouldDispatchEvent((_b2 = (_a2 = request2.frame()) == null ? void 0 : _a2._page) == null ? void 0 : _b2.initializedOrUndefined(), event); + } + _shouldDispatchEvent(page, event) { + if (this._subscriptions.has(event)) + return true; + const pageDispatcher = page ? this.connection.existingDispatcher(page) : void 0; + if (pageDispatcher == null ? void 0 : pageDispatcher._subscriptions.has(event)) + return true; + return false; + } + async createTempFiles(params) { + const dir = this._context._browser.options.artifactsDir; + const tmpDir = path.join(dir, "upload-" + createGuid()); + const tempDirWithRootName = params.rootDirName ? path.join(tmpDir, path.basename(params.rootDirName)) : tmpDir; + await fs.promises.mkdir(tempDirWithRootName, { recursive: true }); + this._context._tempDirs.push(tmpDir); + return { + rootDir: params.rootDirName ? new WritableStreamDispatcher(this, tempDirWithRootName) : void 0, + writableStreams: await Promise.all(params.items.map(async (item) => { + await fs.promises.mkdir(path.dirname(path.join(tempDirWithRootName, item.name)), { recursive: true }); + const file = fs.createWriteStream(path.join(tempDirWithRootName, item.name)); + return new WritableStreamDispatcher(this, file, item.lastModifiedMs); + })) + }; + } + async exposeBinding(params) { + const binding2 = await this._context.exposeBinding(params.name, !!params.needsHandle, (source2, ...args) => { + if (this._disposed) + return; + const pageDispatcher = PageDispatcher.from(this, source2.page); + const binding22 = new BindingCallDispatcher(pageDispatcher, params.name, !!params.needsHandle, source2, args); + this._dispatchEvent("bindingCall", { binding: binding22 }); + return binding22.promise(); + }); + this._bindings.push(binding2); + } + async newPage(params, metadata) { + return { page: PageDispatcher.from(this, await this._context.newPage(metadata)) }; + } + async cookies(params) { + return { cookies: await this._context.cookies(params.urls) }; + } + async addCookies(params) { + await this._context.addCookies(params.cookies); + } + async clearCookies(params) { + const nameRe = params.nameRegexSource !== void 0 && params.nameRegexFlags !== void 0 ? new RegExp(params.nameRegexSource, params.nameRegexFlags) : void 0; + const domainRe = params.domainRegexSource !== void 0 && params.domainRegexFlags !== void 0 ? new RegExp(params.domainRegexSource, params.domainRegexFlags) : void 0; + const pathRe = params.pathRegexSource !== void 0 && params.pathRegexFlags !== void 0 ? new RegExp(params.pathRegexSource, params.pathRegexFlags) : void 0; + await this._context.clearCookies({ + name: nameRe || params.name, + domain: domainRe || params.domain, + path: pathRe || params.path + }); + } + async grantPermissions(params) { + await this._context.grantPermissions(params.permissions, params.origin); + } + async clearPermissions() { + await this._context.clearPermissions(); + } + async setGeolocation(params) { + await this._context.setGeolocation(params.geolocation); + } + async setExtraHTTPHeaders(params) { + await this._context.setExtraHTTPHeaders(params.headers); + } + async setOffline(params) { + await this._context.setOffline(params.offline); + } + async setHTTPCredentials(params) { + await this._context.setHTTPCredentials(params.httpCredentials); + } + async addInitScript(params) { + this._initScritps.push(await this._context.addInitScript(params.source)); + } + async setNetworkInterceptionPatterns(params) { + const hadMatchers = this._interceptionUrlMatchers.length > 0; + if (!params.patterns.length) { + if (hadMatchers) + await this._context.removeRequestInterceptor(this._requestInterceptor); + this._interceptionUrlMatchers = []; + } else { + this._interceptionUrlMatchers = params.patterns.map((pattern) => pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags) : pattern.glob); + if (!hadMatchers) + await this._context.addRequestInterceptor(this._requestInterceptor); + } + } + async setWebSocketInterceptionPatterns(params, metadata) { + this._webSocketInterceptionPatterns = params.patterns; + if (params.patterns.length) + await WebSocketRouteDispatcher.installIfNeeded(this.connection, this._context); + } + async storageState(params, metadata) { + return await this._context.storageState(params.indexedDB); + } + async close(params, metadata) { + metadata.potentiallyClosesScope = true; + await this._context.close(params); + } + async enableRecorder(params) { + await Recorder.show(this._context, RecorderApp.factory(this._context), params); + } + async pause(params, metadata) { + } + async newCDPSession(params) { + if (!this._object._browser.options.isChromium) + throw new Error(`CDP session is only available in Chromium`); + if (!params.page && !params.frame || params.page && params.frame) + throw new Error(`CDP session must be initiated with either Page or Frame, not none or both`); + const crBrowserContext = this._object; + return { session: new CDPSessionDispatcher(this, await crBrowserContext.newCDPSession((params.page ? params.page : params.frame)._object)) }; + } + async harStart(params) { + const harId = await this._context._harStart(params.page ? params.page._object : null, params.options); + return { harId }; + } + async harExport(params) { + const artifact = await this._context._harExport(params.harId); + if (!artifact) + throw new Error("No HAR artifact. Ensure record.harPath is set."); + return { artifact: ArtifactDispatcher.from(this, artifact) }; + } + async clockFastForward(params, metadata) { + await this._context.clock.fastForward(params.ticksString ?? params.ticksNumber ?? 0); + } + async clockInstall(params, metadata) { + await this._context.clock.install(params.timeString ?? params.timeNumber ?? void 0); + } + async clockPauseAt(params, metadata) { + await this._context.clock.pauseAt(params.timeString ?? params.timeNumber ?? 0); + this._clockPaused = true; + } + async clockResume(params, metadata) { + await this._context.clock.resume(); + this._clockPaused = false; + } + async clockRunFor(params, metadata) { + await this._context.clock.runFor(params.ticksString ?? params.ticksNumber ?? 0); + } + async clockSetFixedTime(params, metadata) { + await this._context.clock.setFixedTime(params.timeString ?? params.timeNumber ?? 0); + } + async clockSetSystemTime(params, metadata) { + await this._context.clock.setSystemTime(params.timeString ?? params.timeNumber ?? 0); + } + async updateSubscription(params) { + if (params.enabled) + this._subscriptions.add(params.event); + else + this._subscriptions.delete(params.event); + } + async registerSelectorEngine(params) { + this._object.selectors().register(params.selectorEngine); + } + async setTestIdAttributeName(params) { + this._object.selectors().setTestIdAttributeName(params.testIdAttributeName); + } + _onDispose() { + if (this._context.isClosingOrClosed()) + return; + this._context.dialogManager.removeDialogHandler(this._dialogHandler); + this._interceptionUrlMatchers = []; + this._context.removeRequestInterceptor(this._requestInterceptor).catch(() => { + }); + this._context.removeExposedBindings(this._bindings).catch(() => { + }); + this._bindings = []; + this._context.removeInitScripts(this._initScritps).catch(() => { + }); + this._initScritps = []; + if (this._clockPaused) + this._context.clock.resume().catch(() => { + }); + this._clockPaused = false; + } +} +let PipeTransport$1 = class PipeTransport { + constructor(pipeWrite, pipeRead, closeable, endian = "le") { + this._data = Buffer.from([]); + this._waitForNextTask = makeWaitForNextTask(); + this._closed = false; + this._bytesLeft = 0; + this._pipeWrite = pipeWrite; + this._endian = endian; + this._closeableStream = closeable; + pipeRead.on("data", (buffer2) => this._dispatch(buffer2)); + pipeRead.on("close", () => { + this._closed = true; + if (this.onclose) + this.onclose(); + }); + this.onmessage = void 0; + this.onclose = void 0; + } + send(message) { + if (this._closed) + throw new Error("Pipe has been closed"); + const data2 = Buffer.from(message, "utf-8"); + const dataLength = Buffer.alloc(4); + if (this._endian === "be") + dataLength.writeUInt32BE(data2.length, 0); + else + dataLength.writeUInt32LE(data2.length, 0); + this._pipeWrite.write(dataLength); + this._pipeWrite.write(data2); + } + close() { + this._closeableStream.close(); + } + _dispatch(buffer2) { + this._data = Buffer.concat([this._data, buffer2]); + while (true) { + if (!this._bytesLeft && this._data.length < 4) { + break; + } + if (!this._bytesLeft) { + this._bytesLeft = this._endian === "be" ? this._data.readUInt32BE(0) : this._data.readUInt32LE(0); + this._data = this._data.slice(4); + } + if (!this._bytesLeft || this._data.length < this._bytesLeft) { + break; + } + const message = this._data.slice(0, this._bytesLeft); + this._data = this._data.slice(this._bytesLeft); + this._bytesLeft = 0; + this._waitForNextTask(() => { + if (this.onmessage) + this.onmessage(message.toString("utf-8")); + }); + } + } +}; +const disabledFeatures = (assistantMode) => [ + // See https://github.com/microsoft/playwright/pull/10380 + "AcceptCHFrame", + // See https://github.com/microsoft/playwright/pull/10679 + "AutoExpandDetailsElement", + // See https://github.com/microsoft/playwright/issues/14047 + "AvoidUnnecessaryBeforeUnloadCheckSync", + // See https://github.com/microsoft/playwright/pull/12992 + "CertificateTransparencyComponentUpdater", + "DestroyProfileOnBrowserClose", + // See https://github.com/microsoft/playwright/pull/13854 + "DialMediaRouteProvider", + // Chromium is disabling manifest version 2. Allow testing it as long as Chromium can actually run it. + // Disabled in https://chromium-review.googlesource.com/c/chromium/src/+/6265903. + "ExtensionManifestV2Disabled", + "GlobalMediaControls", + // See https://github.com/microsoft/playwright/pull/27605 + "HttpsUpgrades", + "ImprovedCookieControls", + "LazyFrameLoading", + // Hides the Lens feature in the URL address bar. Its not working in unofficial builds. + "LensOverlay", + // See https://github.com/microsoft/playwright/pull/8162 + "MediaRouter", + // See https://github.com/microsoft/playwright/issues/28023 + "PaintHolding", + // See https://github.com/microsoft/playwright/issues/32230 + "ThirdPartyStoragePartitioning", + // See https://github.com/microsoft/playwright/issues/16126 + "Translate", + assistantMode ? "AutomationControlled" : "" +].filter(Boolean); +const chromiumSwitches = (assistantMode, channel) => [ + "--disable-field-trial-config", + // https://source.chromium.org/chromium/chromium/src/+/main:testing/variations/README.md + "--disable-background-networking", + "--disable-background-timer-throttling", + "--disable-backgrounding-occluded-windows", + "--disable-back-forward-cache", + // Avoids surprises like main request not being intercepted during page.goBack(). + "--disable-breakpad", + "--disable-client-side-phishing-detection", + "--disable-component-extensions-with-background-pages", + "--disable-component-update", + // Avoids unneeded network activity after startup. + "--no-default-browser-check", + "--disable-default-apps", + "--disable-dev-shm-usage", + "--disable-extensions", + "--disable-features=" + disabledFeatures(assistantMode).join(","), + channel === "chromium-tip-of-tree" ? "--enable-features=CDPScreenshotNewSurface" : "", + "--allow-pre-commit-input", + "--disable-hang-monitor", + "--disable-ipc-flooding-protection", + "--disable-popup-blocking", + "--disable-prompt-on-repost", + "--disable-renderer-backgrounding", + "--force-color-profile=srgb", + "--metrics-recording-only", + "--no-first-run", + "--password-store=basic", + "--use-mock-keychain", + // See https://chromium-review.googlesource.com/c/chromium/src/+/2436773 + "--no-service-autorun", + "--export-tagged-pdf", + // https://chromium-review.googlesource.com/c/chromium/src/+/4853540 + "--disable-search-engine-choice-screen", + // https://issues.chromium.org/41491762 + "--unsafely-disable-devtools-self-xss-warnings", + assistantMode ? "" : "--enable-automation" +].filter(Boolean); +const ARTIFACTS_FOLDER$2 = path.join(os.tmpdir(), "playwright-artifacts-"); +let Android$1 = class Android extends SdkObject { + constructor(parent, backend) { + super(parent, "android"); + this._devices = /* @__PURE__ */ new Map(); + this._backend = backend; + } + async devices(options2) { + const devices = (await this._backend.devices(options2)).filter((d) => d.status === "device"); + const newSerials = /* @__PURE__ */ new Set(); + for (const d of devices) { + newSerials.add(d.serial); + if (this._devices.has(d.serial)) + continue; + const device = await AndroidDevice$1.create(this, d, options2); + this._devices.set(d.serial, device); + } + for (const d of this._devices.keys()) { + if (!newSerials.has(d)) + this._devices.delete(d); + } + return [...this._devices.values()]; + } + _deviceClosed(device) { + this._devices.delete(device.serial); + } +}; +let AndroidDevice$1 = (_i = class extends SdkObject { + constructor(android, backend, model, options2) { + super(android, "android-device"); + this._lastId = 0; + this._callbacks = /* @__PURE__ */ new Map(); + this._webViews = /* @__PURE__ */ new Map(); + this._browserConnections = /* @__PURE__ */ new Set(); + this._isClosed = false; + this._android = android; + this._backend = backend; + this.model = model; + this.serial = backend.serial; + this._options = options2; + } + static async create(android, backend, options2) { + await backend.init(); + const model = await backend.runCommand("shell:getprop ro.product.model"); + const device = new _i(android, backend, model.toString().trim(), options2); + await device._init(); + return device; + } + async _init() { + await this._refreshWebViews(); + const poll = () => { + this._pollingWebViews = setTimeout(() => this._refreshWebViews().then(poll).catch(() => { + this.close().catch(() => { + }); + }), 500); + }; + poll(); + } + async shell(command2) { + const result = await this._backend.runCommand(`shell:${command2}`); + await this._refreshWebViews(); + return result; + } + async open(command2) { + return await this._backend.open(`${command2}`); + } + async screenshot() { + return await this._backend.runCommand(`shell:screencap -p`); + } + async _driver() { + if (this._isClosed) + return; + if (!this._driverPromise) + this._driverPromise = this._installDriver(); + return this._driverPromise; + } + async _installDriver() { + debug$2("pw:android")("Stopping the old driver"); + await this.shell(`am force-stop com.microsoft.playwright.androiddriver`); + if (!this._options.omitDriverInstall) { + debug$2("pw:android")("Uninstalling the old driver"); + await this.shell(`cmd package uninstall com.microsoft.playwright.androiddriver`); + await this.shell(`cmd package uninstall com.microsoft.playwright.androiddriver.test`); + debug$2("pw:android")("Installing the new driver"); + const executable = registry.findExecutable("android"); + const packageManagerCommand = getPackageManagerExecCommand(); + for (const file of ["android-driver.apk", "android-driver-target.apk"]) { + const fullName = path.join(executable.directory, file); + if (!fs.existsSync(fullName)) + throw new Error(`Please install Android driver apk using '${packageManagerCommand} playwright install android'`); + await this.installApk(await fs.promises.readFile(fullName)); + } + } else { + debug$2("pw:android")("Skipping the driver installation"); + } + debug$2("pw:android")("Starting the new driver"); + this.shell("am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner").catch((e) => debug$2("pw:android")(e)); + const socket = await this._waitForLocalAbstract("playwright_android_driver_socket"); + const transport = new PipeTransport$1(socket, socket, socket, "be"); + transport.onmessage = (message) => { + const response2 = JSON.parse(message); + const { id, result, error: error2 } = response2; + const callback = this._callbacks.get(id); + if (!callback) + return; + if (error2) + callback.reject(new Error(error2)); + else + callback.fulfill(result); + this._callbacks.delete(id); + }; + return transport; + } + async _waitForLocalAbstract(socketName) { + let socket; + debug$2("pw:android")(`Polling the socket localabstract:${socketName}`); + while (!socket) { + try { + socket = await this._backend.open(`localabstract:${socketName}`); + } catch (e) { + await new Promise((f) => setTimeout(f, 250)); + } + } + debug$2("pw:android")(`Connected to localabstract:${socketName}`); + return socket; + } + async send(method, params = {}) { + params = { + ...params, + // Patch the timeout in, just in case it's missing in one of the commands. + timeout: params.timeout || 0 + }; + if (params.androidSelector) { + params.selector = params.androidSelector; + delete params.androidSelector; + } + const driver = await this._driver(); + if (!driver) + throw new Error("Device is closed"); + const id = ++this._lastId; + const result = new Promise((fulfill, reject) => this._callbacks.set(id, { fulfill, reject })); + driver.send(JSON.stringify({ id, method, params })); + return result; + } + async close() { + if (this._isClosed) + return; + this._isClosed = true; + if (this._pollingWebViews) + clearTimeout(this._pollingWebViews); + for (const connection of this._browserConnections) + await connection.close(); + if (this._driverPromise) { + const driver = await this._driver(); + driver == null ? void 0 : driver.close(); + } + await this._backend.close(); + this._android._deviceClosed(this); + this.emit(_i.Events.Close); + } + async launchBrowser(pkg = "com.android.chrome", options2) { + debug$2("pw:android")("Force-stopping", pkg); + await this._backend.runCommand(`shell:am force-stop ${pkg}`); + const socketName = isUnderTest() ? "webview_devtools_remote_playwright_test" : "playwright_" + createGuid() + "_devtools_remote"; + const commandLine = this._defaultArgs(options2, socketName).join(" "); + debug$2("pw:android")("Starting", pkg, commandLine); + await this._backend.runCommand(`shell:echo "${Buffer.from(commandLine).toString("base64")}" | base64 -d > /data/local/tmp/chrome-command-line`); + await this._backend.runCommand(`shell:am start -a android.intent.action.VIEW -d about:blank ${pkg}`); + const browserContext = await this._connectToBrowser(socketName, options2); + await this._backend.runCommand(`shell:rm /data/local/tmp/chrome-command-line`); + return browserContext; + } + _defaultArgs(options2, socketName) { + const chromeArguments = [ + "_", + "--disable-fre", + "--no-default-browser-check", + `--remote-debugging-socket-name=${socketName}`, + ...chromiumSwitches(), + ...this._innerDefaultArgs(options2) + ]; + return chromeArguments; + } + _innerDefaultArgs(options2) { + const { args = [], proxy } = options2; + const chromeArguments = []; + if (proxy) { + chromeArguments.push(`--proxy-server=${proxy.server}`); + const proxyBypassRules = []; + if (proxy.bypass) + proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t)); + if (!define_process_env_default.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>")) + proxyBypassRules.push("<-loopback>"); + if (proxyBypassRules.length > 0) + chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`); + } + chromeArguments.push(...args); + return chromeArguments; + } + async connectToWebView(socketName) { + const webView = this._webViews.get(socketName); + if (!webView) + throw new Error("WebView has been closed"); + return await this._connectToBrowser(socketName); + } + async _connectToBrowser(socketName, options2 = {}) { + const socket = await this._waitForLocalAbstract(socketName); + const androidBrowser = new AndroidBrowser(this, socket); + await androidBrowser._init(); + this._browserConnections.add(androidBrowser); + const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER$2); + const cleanupArtifactsDir = async () => { + const errors2 = (await removeFolders([artifactsDir])).filter(Boolean); + for (let i = 0; i < (errors2 || []).length; ++i) + debug$2("pw:android")(`exception while removing ${artifactsDir}: ${errors2[i]}`); + }; + gracefullyCloseSet.add(cleanupArtifactsDir); + socket.on("close", async () => { + gracefullyCloseSet.delete(cleanupArtifactsDir); + cleanupArtifactsDir().catch((e) => debug$2("pw:android")(`could not cleanup artifacts dir: ${e}`)); + }); + const browserOptions = { + name: "clank", + isChromium: true, + slowMo: 0, + persistent: { ...options2, noDefaultViewport: true }, + artifactsDir, + downloadsPath: artifactsDir, + tracesDir: artifactsDir, + browserProcess: new ClankBrowserProcess(androidBrowser), + proxy: options2.proxy, + protocolLogger: helper.debugProtocolLogger(), + browserLogsCollector: new RecentLogsCollector(), + originalLaunchOptions: { timeout: 0 } + }; + validateBrowserContextOptions(options2, browserOptions); + const browser2 = await CRBrowser.connect(this.attribution.playwright, androidBrowser, browserOptions); + const controller = new ProgressController(serverSideCallMetadata(), this); + const defaultContext = browser2._defaultContext; + await controller.run(async (progress2) => { + await defaultContext._loadDefaultContextAsIs(progress2); + }); + return defaultContext; + } + webViews() { + return [...this._webViews.values()]; + } + async installApk(content, options2) { + const args = options2 && options2.args ? options2.args : ["-r", "-t", "-S"]; + debug$2("pw:android")("Opening install socket"); + const installSocket = await this._backend.open(`shell:cmd package install ${args.join(" ")} ${content.length}`); + debug$2("pw:android")("Writing driver bytes: " + content.length); + await installSocket.write(content); + const success = await new Promise((f) => installSocket.on("data", f)); + debug$2("pw:android")("Written driver bytes: " + success); + installSocket.close(); + } + async push(content, path2, mode = 420) { + const socket = await this._backend.open(`sync:`); + const sendHeader = async (command2, length) => { + const buffer2 = Buffer.alloc(command2.length + 4); + buffer2.write(command2, 0); + buffer2.writeUInt32LE(length, command2.length); + await socket.write(buffer2); + }; + const send = async (command2, data2) => { + await sendHeader(command2, data2.length); + await socket.write(data2); + }; + await send("SEND", Buffer.from(`${path2},${mode}`)); + const maxChunk = 65535; + for (let i = 0; i < content.length; i += maxChunk) + await send("DATA", content.slice(i, i + maxChunk)); + await sendHeader("DONE", Date.now() / 1e3 | 0); + const result = await new Promise((f) => socket.once("data", f)); + const code = result.slice(0, 4).toString(); + if (code !== "OKAY") + throw new Error("Could not push: " + code); + socket.close(); + } + async _refreshWebViews() { + const sockets = (await this._backend.runCommand(`shell:cat /proc/net/unix | grep webview_devtools_remote`)).toString().split("\n"); + if (this._isClosed) + return; + const socketNames = /* @__PURE__ */ new Set(); + for (const line of sockets) { + const matchSocketName = line.match(/[^@]+@(.*?webview_devtools_remote_?.*)/); + if (!matchSocketName) + continue; + const socketName = matchSocketName[1]; + socketNames.add(socketName); + if (this._webViews.has(socketName)) + continue; + const match = line.match(/[^@]+@.*?webview_devtools_remote_?(\d*)/); + let pid = -1; + if (match && match[1]) + pid = +match[1]; + const pkg = await this._extractPkg(pid); + if (this._isClosed) + return; + const webView = { pid, pkg, socketName }; + this._webViews.set(socketName, webView); + this.emit(_i.Events.WebViewAdded, webView); + } + for (const p of this._webViews.keys()) { + if (!socketNames.has(p)) { + this._webViews.delete(p); + this.emit(_i.Events.WebViewRemoved, p); + } + } + } + async _extractPkg(pid) { + let pkg = ""; + if (pid === -1) + return pkg; + const procs = (await this._backend.runCommand(`shell:ps -A | grep ${pid}`)).toString().split("\n"); + for (const proc of procs) { + const match = proc.match(/[^\s]+\s+(\d+).*$/); + if (!match) + continue; + pkg = proc.substring(proc.lastIndexOf(" ") + 1); + } + return pkg; + } +}, _i.Events = { + WebViewAdded: "webViewAdded", + WebViewRemoved: "webViewRemoved", + Close: "close" +}, _i); +class AndroidBrowser extends eventsExports.EventEmitter { + constructor(device, socket) { + super(); + this._waitForNextTask = makeWaitForNextTask(); + this.setMaxListeners(0); + this.device = device; + this._socket = socket; + this._socket.on("close", () => { + this._waitForNextTask(() => { + if (this.onclose) + this.onclose(); + }); + }); + this._receiver = new wsReceiver(); + this._receiver.on("message", (message) => { + this._waitForNextTask(() => { + if (this.onmessage) + this.onmessage(JSON.parse(message)); + }); + }); + } + async _init() { + await this._socket.write(Buffer.from(`GET /devtools/browser HTTP/1.1\r +Upgrade: WebSocket\r +Connection: Upgrade\r +Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r +Sec-WebSocket-Version: 13\r +\r +`)); + await new Promise((f) => this._socket.once("data", f)); + this._socket.on("data", (data2) => this._receiver._write(data2, "binary", () => { + })); + } + async send(s) { + await this._socket.write(encodeWebFrame(JSON.stringify(s))); + } + async close() { + this._socket.close(); + } +} +function encodeWebFrame(data2) { + return wsSender.frame(Buffer.from(data2), { + opcode: 1, + mask: true, + fin: true, + readOnly: true + })[0]; +} +class ClankBrowserProcess { + constructor(browser2) { + this._browser = browser2; + } + async kill() { + } + async close() { + await this._browser.close(); + } +} +class AndroidDispatcher extends Dispatcher { + constructor(scope, android) { + super(scope, android, "Android", {}); + this._type_Android = true; + } + async devices(params) { + const devices = await this._object.devices(params); + return { + devices: devices.map((d) => AndroidDeviceDispatcher.from(this, d)) + }; + } +} +class AndroidDeviceDispatcher extends Dispatcher { + constructor(scope, device) { + super(scope, device, "AndroidDevice", { + model: device.model, + serial: device.serial + }); + this._type_EventTarget = true; + this._type_AndroidDevice = true; + for (const webView of device.webViews()) + this._dispatchEvent("webViewAdded", { webView }); + this.addObjectListener(AndroidDevice$1.Events.WebViewAdded, (webView) => this._dispatchEvent("webViewAdded", { webView })); + this.addObjectListener(AndroidDevice$1.Events.WebViewRemoved, (socketName) => this._dispatchEvent("webViewRemoved", { socketName })); + this.addObjectListener(AndroidDevice$1.Events.Close, (socketName) => this._dispatchEvent("close")); + } + static from(scope, device) { + const result = scope.connection.existingDispatcher(device); + return result || new AndroidDeviceDispatcher(scope, device); + } + async wait(params) { + await this._object.send("wait", params); + } + async fill(params) { + await this._object.send("click", { selector: params.androidSelector }); + await this._object.send("fill", params); + } + async tap(params) { + await this._object.send("click", params); + } + async drag(params) { + await this._object.send("drag", params); + } + async fling(params) { + await this._object.send("fling", params); + } + async longTap(params) { + await this._object.send("longClick", params); + } + async pinchClose(params) { + await this._object.send("pinchClose", params); + } + async pinchOpen(params) { + await this._object.send("pinchOpen", params); + } + async scroll(params) { + await this._object.send("scroll", params); + } + async swipe(params) { + await this._object.send("swipe", params); + } + async info(params) { + const info = await this._object.send("info", params); + fixupAndroidElementInfo(info); + return { info }; + } + async inputType(params) { + const text = params.text; + const keyCodes = []; + for (let i = 0; i < text.length; ++i) { + const code = keyMap.get(text[i].toUpperCase()); + if (code === void 0) + throw new Error("No mapping for " + text[i] + " found"); + keyCodes.push(code); + } + await Promise.all(keyCodes.map((keyCode) => this._object.send("inputPress", { keyCode }))); + } + async inputPress(params) { + if (!keyMap.has(params.key)) + throw new Error("Unknown key: " + params.key); + await this._object.send("inputPress", { keyCode: keyMap.get(params.key) }); + } + async inputTap(params) { + await this._object.send("inputClick", params); + } + async inputSwipe(params) { + await this._object.send("inputSwipe", params); + } + async inputDrag(params) { + await this._object.send("inputDrag", params); + } + async screenshot(params) { + return { binary: await this._object.screenshot() }; + } + async shell(params) { + return { result: await this._object.shell(params.command) }; + } + async open(params, metadata) { + const socket = await this._object.open(params.command); + return { socket: new AndroidSocketDispatcher(this, socket) }; + } + async installApk(params) { + await this._object.installApk(params.file, { args: params.args }); + } + async push(params) { + await this._object.push(params.file, params.path, params.mode); + } + async launchBrowser(params) { + const context = await this._object.launchBrowser(params.pkg, params); + return { context: BrowserContextDispatcher.from(this, context) }; + } + async close(params) { + await this._object.close(); + } + async connectToWebView(params) { + return { context: BrowserContextDispatcher.from(this, await this._object.connectToWebView(params.socketName)) }; + } +} +class AndroidSocketDispatcher extends Dispatcher { + constructor(scope, socket) { + super(scope, socket, "AndroidSocket", {}); + this._type_AndroidSocket = true; + this.addObjectListener("data", (data2) => this._dispatchEvent("data", { data: data2 })); + this.addObjectListener("close", () => { + this._dispatchEvent("close"); + this._dispose(); + }); + } + async write(params, metadata) { + await this._object.write(params.data); + } + async close(params, metadata) { + this._object.close(); + } +} +const keyMap = /* @__PURE__ */ new Map([ + ["Unknown", 0], + ["SoftLeft", 1], + ["SoftRight", 2], + ["Home", 3], + ["Back", 4], + ["Call", 5], + ["EndCall", 6], + ["0", 7], + ["1", 8], + ["2", 9], + ["3", 10], + ["4", 11], + ["5", 12], + ["6", 13], + ["7", 14], + ["8", 15], + ["9", 16], + ["Star", 17], + ["*", 17], + ["Pound", 18], + ["#", 18], + ["DialUp", 19], + ["DialDown", 20], + ["DialLeft", 21], + ["DialRight", 22], + ["DialCenter", 23], + ["VolumeUp", 24], + ["VolumeDown", 25], + ["Power", 26], + ["Camera", 27], + ["Clear", 28], + ["A", 29], + ["B", 30], + ["C", 31], + ["D", 32], + ["E", 33], + ["F", 34], + ["G", 35], + ["H", 36], + ["I", 37], + ["J", 38], + ["K", 39], + ["L", 40], + ["M", 41], + ["N", 42], + ["O", 43], + ["P", 44], + ["Q", 45], + ["R", 46], + ["S", 47], + ["T", 48], + ["U", 49], + ["V", 50], + ["W", 51], + ["X", 52], + ["Y", 53], + ["Z", 54], + ["Comma", 55], + [",", 55], + ["Period", 56], + [".", 56], + ["AltLeft", 57], + ["AltRight", 58], + ["ShiftLeft", 59], + ["ShiftRight", 60], + ["Tab", 61], + [" ", 61], + ["Space", 62], + [" ", 62], + ["Sym", 63], + ["Explorer", 64], + ["Envelop", 65], + ["Enter", 66], + ["Del", 67], + ["Grave", 68], + ["Minus", 69], + ["-", 69], + ["Equals", 70], + ["=", 70], + ["LeftBracket", 71], + ["(", 71], + ["RightBracket", 72], + [")", 72], + ["Backslash", 73], + ["\\", 73], + ["Semicolon", 74], + [";", 74], + ["Apostrophe", 75], + ["`", 75], + ["Slash", 76], + ["/", 76], + ["At", 77], + ["@", 77], + ["Num", 78], + ["HeadsetHook", 79], + ["Focus", 80], + ["Plus", 81], + ["Menu", 82], + ["Notification", 83], + ["Search", 84], + ["ChannelUp", 166], + ["ChannelDown", 167], + ["AppSwitch", 187], + ["Assist", 219], + ["Cut", 277], + ["Copy", 278], + ["Paste", 279] +]); +function fixupAndroidElementInfo(info) { + info.clazz = info.clazz || ""; + info.pkg = info.pkg || ""; + info.res = info.res || ""; + info.desc = info.desc || ""; + info.text = info.text || ""; + for (const child of info.children || []) + fixupAndroidElementInfo(child); +} +class BrowserDispatcher extends Dispatcher { + constructor(scope, browser2, options2 = {}) { + super(scope, browser2, "Browser", { version: browser2.version(), name: browser2.options.name }); + this._type_Browser = true; + this._isolatedContexts = /* @__PURE__ */ new Set(); + this._options = options2; + if (!options2.isolateContexts) { + this.addObjectListener(Browser$1.Events.Context, (context) => this._dispatchEvent("context", { context: BrowserContextDispatcher.from(this, context) })); + this.addObjectListener(Browser$1.Events.Disconnected, () => this._didClose()); + if (browser2._defaultContext) + this._dispatchEvent("context", { context: BrowserContextDispatcher.from(this, browser2._defaultContext) }); + for (const context of browser2.contexts()) + this._dispatchEvent("context", { context: BrowserContextDispatcher.from(this, context) }); + } + } + _didClose() { + this._dispatchEvent("close"); + this._dispose(); + } + async newContext(params, metadata) { + if (!this._options.isolateContexts) { + const context2 = await this._object.newContext(metadata, params); + const contextDispatcher2 = BrowserContextDispatcher.from(this, context2); + return { context: contextDispatcher2 }; + } + if (params.recordVideo) + params.recordVideo.dir = this._object.options.artifactsDir; + const context = await this._object.newContext(metadata, params); + this._isolatedContexts.add(context); + context.on(BrowserContext$1.Events.Close, () => this._isolatedContexts.delete(context)); + const contextDispatcher = BrowserContextDispatcher.from(this, context); + this._dispatchEvent("context", { context: contextDispatcher }); + return { context: contextDispatcher }; + } + async newContextForReuse(params, metadata) { + const { context, needsReset } = await this._object.newContextForReuse(params, metadata); + if (needsReset) { + const oldContextDispatcher = this.connection.existingDispatcher(context); + if (oldContextDispatcher) + oldContextDispatcher._dispose(); + await context.resetForReuse(metadata, params); + } + const contextDispatcher = BrowserContextDispatcher.from(this, context); + this._dispatchEvent("context", { context: contextDispatcher }); + return { context: contextDispatcher }; + } + async stopPendingOperations(params, metadata) { + await this._object.stopPendingOperations(params.reason); + } + async close(params, metadata) { + if (this._options.ignoreStopAndKill) + return; + metadata.potentiallyClosesScope = true; + await this._object.close(params); + } + async killForTests(_, metadata) { + if (this._options.ignoreStopAndKill) + return; + metadata.potentiallyClosesScope = true; + await this._object.killForTests(); + } + async defaultUserAgentForTest() { + return { userAgent: this._object.userAgent() }; + } + async newBrowserCDPSession() { + if (!this._object.options.isChromium) + throw new Error(`CDP session is only available in Chromium`); + const crBrowser = this._object; + return { session: new CDPSessionDispatcher(this, await crBrowser.newBrowserCDPSession()) }; + } + async startTracing(params) { + if (!this._object.options.isChromium) + throw new Error(`Tracing is only available in Chromium`); + const crBrowser = this._object; + await crBrowser.startTracing(params.page ? params.page._object : void 0, params); + } + async stopTracing() { + if (!this._object.options.isChromium) + throw new Error(`Tracing is only available in Chromium`); + const crBrowser = this._object; + return { artifact: ArtifactDispatcher.from(this, await crBrowser.stopTracing()) }; + } + async cleanupContexts() { + await Promise.all(Array.from(this._isolatedContexts).map((context) => context.close({ reason: "Global context cleanup (connection terminated)" }))); + } +} +class BrowserTypeDispatcher extends Dispatcher { + constructor(scope, browserType) { + super(scope, browserType, "BrowserType", { + executablePath: browserType.executablePath(), + name: browserType.name() + }); + this._type_BrowserType = true; + } + async launch(params, metadata) { + const browser2 = await this._object.launch(metadata, params); + return { browser: new BrowserDispatcher(this, browser2) }; + } + async launchPersistentContext(params, metadata) { + const browserContext = await this._object.launchPersistentContext(metadata, params.userDataDir, params); + const browserDispatcher = new BrowserDispatcher(this, browserContext._browser); + const contextDispatcher = BrowserContextDispatcher.from(browserDispatcher, browserContext); + return { browser: browserDispatcher, context: contextDispatcher }; + } + async connectOverCDP(params, metadata) { + const browser2 = await this._object.connectOverCDP(metadata, params.endpointURL, params); + const browserDispatcher = new BrowserDispatcher(this, browser2); + return { + browser: browserDispatcher, + defaultContext: browser2._defaultContext ? BrowserContextDispatcher.from(browserDispatcher, browser2._defaultContext) : void 0 + }; + } +} +const perMessageDeflate = { + clientNoContextTakeover: true, + zlibDeflateOptions: { + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + threshold: 10 * 1024 +}; +let WebSocketTransport$1 = class WebSocketTransport { + constructor(progress2, url2, logUrl, options2) { + this.headers = []; + this.wsEndpoint = url2; + this._logUrl = logUrl; + this._ws = new ws(url2, [], { + maxPayload: 256 * 1024 * 1024, + // 256Mb, + // Prevent internal http client error when passing negative timeout. + handshakeTimeout: Math.max((progress2 == null ? void 0 : progress2.timeUntilDeadline()) ?? DEFAULT_PLAYWRIGHT_TIMEOUT, 1), + headers: options2.headers, + followRedirects: options2.followRedirects, + agent: /^(https|wss):\/\//.test(url2) ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent, + perMessageDeflate + }); + this._ws.on("upgrade", (response2) => { + for (let i = 0; i < response2.rawHeaders.length; i += 2) { + this.headers.push({ name: response2.rawHeaders[i], value: response2.rawHeaders[i + 1] }); + if (options2.debugLogHeader && response2.rawHeaders[i] === options2.debugLogHeader) + progress2 == null ? void 0 : progress2.log(response2.rawHeaders[i + 1]); + } + }); + this._progress = progress2; + const messageWrap = makeWaitForNextTask(); + this._ws.addEventListener("message", (event) => { + messageWrap(() => { + var _a2, _b2; + const eventData = event.data; + let parsedJson; + try { + parsedJson = JSON.parse(eventData); + } catch (e) { + (_a2 = this._progress) == null ? void 0 : _a2.log(` Closing websocket due to malformed JSON. eventData=${eventData} e=${e == null ? void 0 : e.message}`); + this._ws.close(); + return; + } + try { + if (this.onmessage) + this.onmessage.call(null, parsedJson); + } catch (e) { + (_b2 = this._progress) == null ? void 0 : _b2.log(` Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e == null ? void 0 : e.message}`); + this._ws.close(); + } + }); + }); + this._ws.addEventListener("close", (event) => { + var _a2; + (_a2 = this._progress) == null ? void 0 : _a2.log(` ${logUrl} code=${event.code} reason=${event.reason}`); + if (this.onclose) + this.onclose.call(null, event.reason); + }); + this._ws.addEventListener("error", (error2) => { + var _a2; + return (_a2 = this._progress) == null ? void 0 : _a2.log(` ${logUrl} ${error2.type} ${error2.message}`); + }); + } + static async connect(progress2, url2, options2 = {}) { + return await WebSocketTransport._connect( + progress2, + url2, + options2, + false + /* hadRedirects */ + ); + } + static async _connect(progress2, url2, options2, hadRedirects) { + const logUrl = stripQueryParams(url2); + progress2 == null ? void 0 : progress2.log(` ${logUrl}`); + const transport = new WebSocketTransport(progress2, url2, logUrl, { ...options2, followRedirects: !!options2.followRedirects && hadRedirects }); + let success = false; + progress2 == null ? void 0 : progress2.cleanupWhenAborted(async () => { + if (!success) + await transport.closeAndWait().catch((e) => null); + }); + const result = await new Promise((fulfill, reject) => { + transport._ws.on("open", async () => { + progress2 == null ? void 0 : progress2.log(` ${logUrl}`); + fulfill({ transport }); + }); + transport._ws.on("error", (event) => { + progress2 == null ? void 0 : progress2.log(` ${logUrl} ${event.message}`); + reject(new Error("WebSocket error: " + event.message)); + transport._ws.close(); + }); + transport._ws.on("unexpected-response", (request2, response2) => { + if (options2.followRedirects && !hadRedirects && (response2.statusCode === 301 || response2.statusCode === 302 || response2.statusCode === 307 || response2.statusCode === 308)) { + fulfill({ redirect: response2 }); + transport._ws.close(); + return; + } + for (let i = 0; i < response2.rawHeaders.length; i += 2) { + if (options2.debugLogHeader && response2.rawHeaders[i] === options2.debugLogHeader) + progress2 == null ? void 0 : progress2.log(response2.rawHeaders[i + 1]); + } + const chunks = []; + const errorPrefix = `${logUrl} ${response2.statusCode} ${response2.statusMessage}`; + response2.on("data", (chunk) => chunks.push(chunk)); + response2.on("close", () => { + const error2 = chunks.length ? `${errorPrefix} +${Buffer.concat(chunks)}` : errorPrefix; + progress2 == null ? void 0 : progress2.log(` ${error2}`); + reject(new Error("WebSocket error: " + error2)); + transport._ws.close(); + }); + }); + }); + if (result.redirect) { + const newHeaders = Object.fromEntries(Object.entries(options2.headers || {}).filter(([name]) => { + return !name.includes("access-key") && name.toLowerCase() !== "authorization"; + })); + return WebSocketTransport._connect( + progress2, + result.redirect.headers.location, + { ...options2, headers: newHeaders }, + true + /* hadRedirects */ + ); + } + success = true; + return transport; + } + send(message) { + this._ws.send(JSON.stringify(message)); + } + close() { + var _a2; + (_a2 = this._progress) == null ? void 0 : _a2.log(` ${this._logUrl}`); + this._ws.close(); + } + async closeAndWait() { + if (this._ws.readyState === ws.CLOSED) + return; + const promise = new Promise((f) => this._ws.once("close", f)); + this.close(); + await promise; + } +}; +function stripQueryParams(url2) { + try { + const u = new URL(url2); + u.search = ""; + u.hash = ""; + return u.toString(); + } catch { + return url2; + } +} +const ARTIFACTS_FOLDER$1 = path.join(os.tmpdir(), "playwright-artifacts-"); +let ElectronApplication$1 = (_j = class extends SdkObject { + constructor(parent, browser2, nodeConnection, process2) { + super(parent, "electron-app"); + this._nodeElectronHandlePromise = new ManualPromise(); + this._process = process2; + this._browserContext = browser2._defaultContext; + this._nodeConnection = nodeConnection; + this._nodeSession = nodeConnection.rootSession; + this._nodeSession.on("Runtime.executionContextCreated", async (event) => { + if (!event.context.auxData || !event.context.auxData.isDefault) + return; + const crExecutionContext = new CRExecutionContext(this._nodeSession, event.context); + this._nodeExecutionContext = new ExecutionContext(this, crExecutionContext, "electron"); + const { result: remoteObject } = await crExecutionContext._client.send("Runtime.evaluate", { + expression: `require('electron')`, + contextId: event.context.id, + // Needed after Electron 28 to get access to require: https://github.com/microsoft/playwright/issues/28048 + includeCommandLineAPI: true + }); + this._nodeElectronHandlePromise.resolve(new JSHandle$1(this._nodeExecutionContext, "object", "ElectronModule", remoteObject.objectId)); + }); + this._nodeSession.on("Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)); + const appClosePromise = new Promise((f) => this.once(_j.Events.Close, f)); + this._browserContext.setCustomCloseHandler(async () => { + await this._browserContext.stopVideoRecording(); + const electronHandle = await this._nodeElectronHandlePromise; + await electronHandle.evaluate(({ app }) => app.quit()).catch(() => { + }); + this._nodeConnection.close(); + await appClosePromise; + }); + } + async _onConsoleAPI(event) { + if (event.executionContextId === 0) { + return; + } + if (!this._nodeExecutionContext) + return; + const args = event.args.map((arg) => createHandle$3(this._nodeExecutionContext, arg)); + const message = new ConsoleMessage$1(null, event.type, void 0, args, toConsoleMessageLocation(event.stackTrace)); + this.emit(_j.Events.Console, message); + } + async initialize() { + await this._nodeSession.send("Runtime.enable", {}); + await this._nodeSession.send("Runtime.evaluate", { expression: "__playwright_run()" }); + } + process() { + return this._process; + } + context() { + return this._browserContext; + } + async close() { + await this._browserContext.close({ reason: "Application exited" }); + } + async browserWindow(page) { + const targetId = page.delegate._targetId; + const electronHandle = await this._nodeElectronHandlePromise; + return await electronHandle.evaluateHandle(({ BrowserWindow, webContents }, targetId2) => { + const wc = webContents.fromDevToolsTargetId(targetId2); + return BrowserWindow.fromWebContents(wc); + }, targetId); + } +}, _j.Events = { + Close: "close", + Console: "console" +}, _j); +let Electron$1 = class Electron extends SdkObject { + constructor(playwright2) { + super(playwright2, "electron"); + } + async launch(options2) { + const { + args = [] + } = options2; + const controller = new ProgressController(serverSideCallMetadata(), this); + controller.setLogName("browser"); + return controller.run(async (progress2) => { + let app = void 0; + let electronArguments = ["--inspect=0", "--remote-debugging-port=0", ...args]; + if (os.platform() === "linux") { + const runningAsRoot = process.geteuid && process.geteuid() === 0; + if (runningAsRoot && electronArguments.indexOf("--no-sandbox") === -1) + electronArguments.unshift("--no-sandbox"); + } + const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER$1); + const browserLogsCollector = new RecentLogsCollector(); + const env = options2.env ? envArrayToObject(options2.env) : define_process_env_default; + let command2; + if (options2.executablePath) { + command2 = options2.executablePath; + } else { + try { + command2 = require("electron/index.js"); + } catch (error2) { + if ((error2 == null ? void 0 : error2.code) === "MODULE_NOT_FOUND") { + throw new Error("\n" + wrapInASCIIBox([ + "Electron executablePath not found!", + "Please install it using `npm install -D electron` or set the executablePath to your Electron executable." + ].join("\n"), 1)); + } + throw error2; + } + electronArguments.unshift("-r", Boolean("./loader")); + } + let shell = false; + if (process.platform === "win32") { + shell = true; + command2 = `"${command2}"`; + electronArguments = electronArguments.map((arg) => `"${arg}"`); + } + delete env.NODE_OPTIONS; + const { launchedProcess, gracefullyClose, kill } = await launchProcess({ + command: command2, + args: electronArguments, + env, + log: (message) => { + progress2.log(message); + browserLogsCollector.log(message); + }, + shell, + stdio: "pipe", + cwd: options2.cwd, + tempDirectories: [artifactsDir], + attemptToGracefullyClose: () => app.close(), + handleSIGINT: true, + handleSIGTERM: true, + handleSIGHUP: true, + onExit: () => app == null ? void 0 : app.emit(ElectronApplication$1.Events.Close) + }); + const waitForXserverError = new Promise(async (resolve, reject) => { + waitForLine(progress2, launchedProcess, /Unable to open X display/).then(() => reject(new Error([ + "Unable to open X display!", + `================================`, + "Most likely this is because there is no X server available.", + "Use 'xvfb-run' on Linux to launch your tests with an emulated display server.", + "For example: 'xvfb-run npm run test:e2e'", + `================================`, + progress2.metadata.log + ].join("\n")))).catch(() => { + }); + }); + const nodeMatchPromise = waitForLine(progress2, launchedProcess, /^Debugger listening on (ws:\/\/.*)$/); + const chromeMatchPromise = waitForLine(progress2, launchedProcess, /^DevTools listening on (ws:\/\/.*)$/); + const debuggerDisconnectPromise = waitForLine(progress2, launchedProcess, /Waiting for the debugger to disconnect\.\.\./); + const nodeMatch = await nodeMatchPromise; + const nodeTransport = await WebSocketTransport$1.connect(progress2, nodeMatch[1]); + const nodeConnection = new CRConnection(nodeTransport, helper.debugProtocolLogger(), browserLogsCollector); + debuggerDisconnectPromise.then(() => { + nodeTransport.close(); + }).catch(() => { + }); + const chromeMatch = await Promise.race([ + chromeMatchPromise, + waitForXserverError + ]); + const chromeTransport = await WebSocketTransport$1.connect(progress2, chromeMatch[1]); + const browserProcess = { + onclose: void 0, + process: launchedProcess, + close: gracefullyClose, + kill + }; + const contextOptions = { + ...options2, + noDefaultViewport: true + }; + const browserOptions = { + name: "electron", + isChromium: true, + headful: true, + persistent: contextOptions, + browserProcess, + protocolLogger: helper.debugProtocolLogger(), + browserLogsCollector, + artifactsDir, + downloadsPath: artifactsDir, + tracesDir: options2.tracesDir || artifactsDir, + originalLaunchOptions: { timeout: options2.timeout } + }; + validateBrowserContextOptions(contextOptions, browserOptions); + const browser2 = await CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions); + app = new ElectronApplication$1(this, browser2, nodeConnection, launchedProcess); + await app.initialize(); + return app; + }, options2.timeout); + } +}; +function waitForLine(progress2, process2, regex) { + return new Promise((resolve, reject) => { + const rl = createInterface({ input: process2.stderr }); + const failError = new Error("Process failed to launch!"); + const listeners = [ + eventsHelper.addEventListener(rl, "line", onLine), + eventsHelper.addEventListener(rl, "close", reject.bind(null, failError)), + eventsHelper.addEventListener(process2, "exit", reject.bind(null, failError)), + // It is Ok to remove error handler because we did not create process and there is another listener. + eventsHelper.addEventListener(process2, "error", reject.bind(null, failError)) + ]; + progress2.cleanupWhenAborted(cleanup); + function onLine(line) { + const match = line.match(regex); + if (!match) + return; + cleanup(); + resolve(match); + } + function cleanup() { + eventsHelper.removeEventListeners(listeners); + } + }); +} +class ElectronDispatcher extends Dispatcher { + constructor(scope, electron) { + super(scope, electron, "Electron", {}); + this._type_Electron = true; + } + async launch(params) { + const electronApplication = await this._object.launch(params); + return { electronApplication: new ElectronApplicationDispatcher(this, electronApplication) }; + } +} +class ElectronApplicationDispatcher extends Dispatcher { + constructor(scope, electronApplication) { + super(scope, electronApplication, "ElectronApplication", { + context: BrowserContextDispatcher.from(scope, electronApplication.context()) + }); + this._type_EventTarget = true; + this._type_ElectronApplication = true; + this._subscriptions = /* @__PURE__ */ new Set(); + this.addObjectListener(ElectronApplication$1.Events.Close, () => { + this._dispatchEvent("close"); + this._dispose(); + }); + this.addObjectListener(ElectronApplication$1.Events.Console, (message) => { + if (!this._subscriptions.has("console")) + return; + this._dispatchEvent("console", { + type: message.type(), + text: message.text(), + args: message.args().map((a) => JSHandleDispatcher.fromJSHandle(this, a)), + location: message.location() + }); + }); + } + async browserWindow(params) { + const handle = await this._object.browserWindow(params.page.page()); + return { handle: JSHandleDispatcher.fromJSHandle(this, handle) }; + } + async evaluateExpression(params) { + const handle = await this._object._nodeElectronHandlePromise; + return { value: serializeResult(await handle.evaluateExpression(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) }; + } + async evaluateExpressionHandle(params) { + const handle = await this._object._nodeElectronHandlePromise; + const result = await handle.evaluateExpressionHandle(params.expression, { isFunction: params.isFunction }, parseArgument(params.arg)); + return { handle: JSHandleDispatcher.fromJSHandle(this, result) }; + } + async updateSubscription(params) { + if (params.enabled) + this._subscriptions.add(params.event); + else + this._subscriptions.delete(params.event); + } + async close() { + await this._object.close(); + } +} +const redirectStatus = [301, 302, 303, 307, 308]; +class HarBackend { + constructor(harFile, baseDir, zipFile) { + this.id = createGuid(); + this._harFile = harFile; + this._baseDir = baseDir; + this._zipFile = zipFile; + } + async lookup(url2, method, headers, postData, isNavigationRequest) { + let entry; + try { + entry = await this._harFindResponse(url2, method, headers, postData); + } catch (e) { + return { action: "error", message: "HAR error: " + e.message }; + } + if (!entry) + return { action: "noentry" }; + if (entry.request.url !== url2 && isNavigationRequest) + return { action: "redirect", redirectURL: entry.request.url }; + const response2 = entry.response; + try { + const buffer2 = await this._loadContent(response2.content); + return { + action: "fulfill", + status: response2.status, + headers: response2.headers, + body: buffer2 + }; + } catch (e) { + return { action: "error", message: e.message }; + } + } + async _loadContent(content) { + const file = content._file; + let buffer2; + if (file) { + if (this._zipFile) + buffer2 = await this._zipFile.read(file); + else + buffer2 = await fs.promises.readFile(path.resolve(this._baseDir, file)); + } else { + buffer2 = Buffer.from(content.text || "", content.encoding === "base64" ? "base64" : "utf-8"); + } + return buffer2; + } + async _harFindResponse(url2, method, headers, postData) { + const harLog = this._harFile.log; + const visited = /* @__PURE__ */ new Set(); + while (true) { + const entries = []; + for (const candidate of harLog.entries) { + if (candidate.request.url !== url2 || candidate.request.method !== method) + continue; + if (method === "POST" && postData && candidate.request.postData) { + const buffer2 = await this._loadContent(candidate.request.postData); + if (!buffer2.equals(postData)) { + const boundary = multipartBoundary(headers); + if (!boundary) + continue; + const candidataBoundary = multipartBoundary(candidate.request.headers); + if (!candidataBoundary) + continue; + if (postData.toString().replaceAll(boundary, "") !== buffer2.toString().replaceAll(candidataBoundary, "")) + continue; + } + } + entries.push(candidate); + } + if (!entries.length) + return; + let entry = entries[0]; + if (entries.length > 1) { + const list = []; + for (const candidate of entries) { + const matchingHeaders = countMatchingHeaders(candidate.request.headers, headers); + list.push({ candidate, matchingHeaders }); + } + list.sort((a, b) => b.matchingHeaders - a.matchingHeaders); + entry = list[0].candidate; + } + if (visited.has(entry)) + throw new Error(`Found redirect cycle for ${url2}`); + visited.add(entry); + const locationHeader = entry.response.headers.find((h) => h.name.toLowerCase() === "location"); + if (redirectStatus.includes(entry.response.status) && locationHeader) { + const locationURL = new URL(locationHeader.value, url2); + url2 = locationURL.toString(); + if ((entry.response.status === 301 || entry.response.status === 302) && method === "POST" || entry.response.status === 303 && !["GET", "HEAD"].includes(method)) { + method = "GET"; + } + continue; + } + return entry; + } + } + dispose() { + var _a2; + (_a2 = this._zipFile) == null ? void 0 : _a2.close(); + } +} +function countMatchingHeaders(harHeaders, headers) { + const set2 = new Set(headers.map((h) => h.name.toLowerCase() + ":" + h.value)); + let matches = 0; + for (const h of harHeaders) { + if (set2.has(h.name.toLowerCase() + ":" + h.value)) + ++matches; + } + return matches; +} +function multipartBoundary(headers) { + const contentType = headers.find((h) => h.name.toLowerCase() === "content-type"); + if (!(contentType == null ? void 0 : contentType.value.includes("multipart/form-data"))) + return void 0; + const boundary = contentType.value.match(/boundary=(\S+)/); + if (boundary) + return boundary[1]; + return void 0; +} +function serializeClientSideCallMetadata(metadatas) { + const fileNames = /* @__PURE__ */ new Map(); + const stacks = []; + for (const m of metadatas) { + if (!m.stack || !m.stack.length) + continue; + const stack = []; + for (const frame of m.stack) { + let ordinal = fileNames.get(frame.file); + if (typeof ordinal !== "number") { + ordinal = fileNames.size; + fileNames.set(frame.file, ordinal); + } + const stackFrame = [ordinal, frame.line || 0, frame.column || 0, frame.function || ""]; + stack.push(stackFrame); + } + stacks.push([m.id, stack]); + } + return { files: [...fileNames.keys()], stacks }; +} +async function zip(stackSessions, params) { + const promise = new ManualPromise(); + const zipFile = new yazl.ZipFile(); + zipFile.on("error", (error2) => promise.reject(error2)); + const addFile = (file, name) => { + try { + if (fs.statSync(file).isFile()) + zipFile.addFile(file, name); + } catch (e) { + } + }; + for (const entry of params.entries) + addFile(entry.value, entry.name); + const stackSession = params.stacksId ? stackSessions.get(params.stacksId) : void 0; + if (stackSession == null ? void 0 : stackSession.callStacks.length) { + await stackSession.writer; + if (define_process_env_default.PW_LIVE_TRACE_STACKS) { + zipFile.addFile(stackSession.file, "trace.stacks"); + } else { + const buffer2 = Buffer.from(JSON.stringify(serializeClientSideCallMetadata(stackSession.callStacks))); + zipFile.addBuffer(buffer2, "trace.stacks"); + } + } + if (params.includeSources) { + const sourceFiles = /* @__PURE__ */ new Set(); + for (const { stack } of (stackSession == null ? void 0 : stackSession.callStacks) || []) { + if (!stack) + continue; + for (const { file } of stack) + sourceFiles.add(file); + } + for (const sourceFile of sourceFiles) + addFile(sourceFile, "resources/src@" + await calculateSha1(sourceFile) + ".txt"); + } + if (params.mode === "write") { + await fs.promises.mkdir(path.dirname(params.zipFile), { recursive: true }); + zipFile.end(void 0, () => { + zipFile.outputStream.pipe(fs.createWriteStream(params.zipFile)).on("close", () => promise.resolve()).on("error", (error2) => promise.reject(error2)); + }); + await promise; + await deleteStackSession(stackSessions, params.stacksId); + return; + } + const tempFile = params.zipFile + ".tmp"; + await fs.promises.rename(params.zipFile, tempFile); + yauzl.open(tempFile, (err, inZipFile) => { + if (err) { + promise.reject(err); + return; + } + assert(inZipFile); + let pendingEntries = inZipFile.entryCount; + inZipFile.on("entry", (entry) => { + inZipFile.openReadStream(entry, (err2, readStream) => { + if (err2) { + promise.reject(err2); + return; + } + zipFile.addReadStream(readStream, entry.fileName); + if (--pendingEntries === 0) { + zipFile.end(void 0, () => { + zipFile.outputStream.pipe(fs.createWriteStream(params.zipFile)).on("close", () => { + fs.promises.unlink(tempFile).then(() => { + promise.resolve(); + }).catch((error2) => promise.reject(error2)); + }); + }); + } + }); + }); + }); + await promise; + await deleteStackSession(stackSessions, params.stacksId); +} +async function deleteStackSession(stackSessions, stacksId) { + const session = stacksId ? stackSessions.get(stacksId) : void 0; + if (!session) + return; + await session.writer; + if (session.tmpDir) + await removeFolders([session.tmpDir]); + stackSessions.delete(stacksId); +} +async function harOpen(harBackends, params) { + let harBackend; + if (params.file.endsWith(".zip")) { + const zipFile = new ZipFile(params.file); + const entryNames = await zipFile.entries(); + const harEntryName = entryNames.find((e) => e.endsWith(".har")); + if (!harEntryName) + return { error: "Specified archive does not have a .har file" }; + const har = await zipFile.read(harEntryName); + const harFile = JSON.parse(har.toString()); + harBackend = new HarBackend(harFile, null, zipFile); + } else { + const harFile = JSON.parse(await fs.promises.readFile(params.file, "utf-8")); + harBackend = new HarBackend(harFile, path.dirname(params.file), null); + } + harBackends.set(harBackend.id, harBackend); + return { harId: harBackend.id }; +} +async function harLookup(harBackends, params) { + const harBackend = harBackends.get(params.harId); + if (!harBackend) + return { action: "error", message: `Internal error: har was not opened` }; + return await harBackend.lookup(params.url, params.method, params.headers, params.postData, params.isNavigationRequest); +} +async function harClose(harBackends, params) { + const harBackend = harBackends.get(params.harId); + if (harBackend) { + harBackends.delete(harBackend.id); + harBackend.dispose(); + } +} +async function harUnzip(params) { + const dir = path.dirname(params.zipFile); + const zipFile = new ZipFile(params.zipFile); + for (const entry of await zipFile.entries()) { + const buffer2 = await zipFile.read(entry); + if (entry === "har.har") + await fs.promises.writeFile(params.harFile, buffer2); + else + await fs.promises.writeFile(path.join(dir, entry), buffer2); + } + zipFile.close(); + await fs.promises.unlink(params.zipFile); +} +async function tracingStarted(stackSessions, params) { + let tmpDir = void 0; + if (!params.tracesDir) + tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "playwright-tracing-")); + const traceStacksFile = path.join(params.tracesDir || tmpDir, params.traceName + ".stacks"); + stackSessions.set(traceStacksFile, { callStacks: [], file: traceStacksFile, writer: Promise.resolve(), tmpDir }); + return { stacksId: traceStacksFile }; +} +async function traceDiscarded(stackSessions, params) { + await deleteStackSession(stackSessions, params.stacksId); +} +async function addStackToTracingNoReply(stackSessions, params) { + for (const session of stackSessions.values()) { + session.callStacks.push(params.callData); + if (define_process_env_default.PW_LIVE_TRACE_STACKS) { + session.writer = session.writer.then(() => { + const buffer2 = Buffer.from(JSON.stringify(serializeClientSideCallMetadata(session.callStacks))); + return fs.promises.writeFile(session.file, buffer2); + }); + } + } +} +class JsonPipeDispatcher extends Dispatcher { + constructor(scope) { + super(scope, { guid: "jsonPipe@" + createGuid() }, "JsonPipe", {}); + this._type_JsonPipe = true; + } + async send(params) { + this.emit("message", params.message); + } + async close() { + this.emit("close"); + if (!this._disposed) { + this._dispatchEvent("closed", {}); + this._dispose(); + } + } + dispatch(message) { + if (!this._disposed) + this._dispatchEvent("message", { message }); + } + wasClosed(reason) { + if (!this._disposed) { + this._dispatchEvent("closed", { reason }); + this._dispose(); + } + } + dispose() { + this._dispose(); + } +} +class SocksInterceptor { + constructor(transport, pattern, redirectPortForTest) { + this._ids = /* @__PURE__ */ new Set(); + this._handler = new SocksProxyHandler(pattern, redirectPortForTest); + let lastId = -1; + this._channel = new Proxy(new EventEmitter$1(), { + get: (obj, prop) => { + if (prop in obj || obj[prop] !== void 0 || typeof prop !== "string") + return obj[prop]; + return (params) => { + try { + const id = --lastId; + this._ids.add(id); + const validator = findValidator("SocksSupport", prop, "Params"); + params = validator(params, "", { tChannelImpl: tChannelForSocks, binary: "toBase64", isUnderTest }); + transport.send({ id, guid: this._socksSupportObjectGuid, method: prop, params, metadata: { stack: [], apiName: "", internal: true } }); + } catch (e) { + } + }; + } + }); + this._handler.on(SocksProxyHandler.Events.SocksConnected, (payload) => this._channel.socksConnected(payload)); + this._handler.on(SocksProxyHandler.Events.SocksData, (payload) => this._channel.socksData(payload)); + this._handler.on(SocksProxyHandler.Events.SocksError, (payload) => this._channel.socksError(payload)); + this._handler.on(SocksProxyHandler.Events.SocksFailed, (payload) => this._channel.socksFailed(payload)); + this._handler.on(SocksProxyHandler.Events.SocksEnd, (payload) => this._channel.socksEnd(payload)); + this._channel.on("socksRequested", (payload) => this._handler.socketRequested(payload)); + this._channel.on("socksClosed", (payload) => this._handler.socketClosed(payload)); + this._channel.on("socksData", (payload) => this._handler.sendSocketData(payload)); + } + cleanup() { + this._handler.cleanup(); + } + interceptMessage(message) { + if (this._ids.has(message.id)) { + this._ids.delete(message.id); + return true; + } + if (message.method === "__create__" && message.params.type === "SocksSupport") { + this._socksSupportObjectGuid = message.params.guid; + return false; + } + if (this._socksSupportObjectGuid && message.guid === this._socksSupportObjectGuid) { + const validator = findValidator("SocksSupport", message.method, "Event"); + const params = validator(message.params, "", { tChannelImpl: tChannelForSocks, binary: "fromBase64", isUnderTest }); + this._channel.emit(message.method, params); + return true; + } + return false; + } +} +function tChannelForSocks(names, arg, path2, context) { + throw new ValidationError(`${path2}: channels are not expected in SocksSupport`); +} +class LocalUtilsDispatcher extends Dispatcher { + constructor(scope, playwright2) { + const localUtils2 = new SdkObject(playwright2, "localUtils", "localUtils"); + const deviceDescriptors$1 = Object.entries(deviceDescriptors).map(([name, descriptor]) => ({ name, descriptor })); + super(scope, localUtils2, "LocalUtils", { + deviceDescriptors: deviceDescriptors$1 + }); + this._harBackends = /* @__PURE__ */ new Map(); + this._stackSessions = /* @__PURE__ */ new Map(); + this._type_LocalUtils = true; + } + async zip(params) { + return await zip(this._stackSessions, params); + } + async harOpen(params, metadata) { + return await harOpen(this._harBackends, params); + } + async harLookup(params, metadata) { + return await harLookup(this._harBackends, params); + } + async harClose(params, metadata) { + return await harClose(this._harBackends, params); + } + async harUnzip(params, metadata) { + return await harUnzip(params); + } + async tracingStarted(params, metadata) { + return await tracingStarted(this._stackSessions, params); + } + async traceDiscarded(params, metadata) { + return await traceDiscarded(this._stackSessions, params); + } + async addStackToTracingNoReply(params, metadata) { + return await addStackToTracingNoReply(this._stackSessions, params); + } + async connect(params, metadata) { + const controller = new ProgressController(metadata, this._object); + controller.setLogName("browser"); + return await controller.run(async (progress2) => { + const wsHeaders = { + "User-Agent": getUserAgent(), + "x-playwright-proxy": params.exposeNetwork ?? "", + ...params.headers + }; + const wsEndpoint = await urlToWSEndpoint$1(progress2, params.wsEndpoint); + const transport = await WebSocketTransport$1.connect(progress2, wsEndpoint, { headers: wsHeaders, followRedirects: true, debugLogHeader: "x-playwright-debug-log" }); + const socksInterceptor = new SocksInterceptor(transport, params.exposeNetwork, params.socksProxyRedirectPortForTest); + const pipe = new JsonPipeDispatcher(this); + transport.onmessage = (json) => { + if (socksInterceptor.interceptMessage(json)) + return; + const cb = () => { + try { + pipe.dispatch(json); + } catch (e) { + transport.close(); + } + }; + if (params.slowMo) + setTimeout(cb, params.slowMo); + else + cb(); + }; + pipe.on("message", (message) => { + transport.send(message); + }); + transport.onclose = (reason) => { + socksInterceptor == null ? void 0 : socksInterceptor.cleanup(); + pipe.wasClosed(reason); + }; + pipe.on("close", () => transport.close()); + return { pipe, headers: transport.headers }; + }, params.timeout); + } + async globToRegex(params, metadata) { + const regex = resolveGlobToRegexPattern(params.baseURL, params.glob, params.webSocketUrl); + return { regex }; + } +} +async function urlToWSEndpoint$1(progress2, endpointURL) { + if (endpointURL.startsWith("ws")) + return endpointURL; + progress2.log(` retrieving websocket url from ${endpointURL}`); + const fetchUrl = new URL(endpointURL); + if (!fetchUrl.pathname.endsWith("/")) + fetchUrl.pathname += "/"; + fetchUrl.pathname += "json"; + const json = await fetchData({ + url: fetchUrl.toString(), + method: "GET", + timeout: progress2.timeUntilDeadline(), + headers: { "User-Agent": getUserAgent() } + }, async (params, response2) => { + return new Error(`Unexpected status ${response2.statusCode} when connecting to ${fetchUrl.toString()}. +This does not look like a Playwright server, try connecting via ws://.`); + }); + progress2.throwIfAborted(); + const wsUrl = new URL(endpointURL); + let wsEndpointPath = JSON.parse(json).wsEndpointPath; + if (wsEndpointPath.startsWith("/")) + wsEndpointPath = wsEndpointPath.substring(1); + if (!wsUrl.pathname.endsWith("/")) + wsUrl.pathname += "/"; + wsUrl.pathname += wsEndpointPath; + wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:"; + return wsUrl.toString(); +} +class AdbBackend { + async devices(options2 = {}) { + const result = await runCommand("host:devices", options2.host, options2.port); + const lines = result.toString().trim().split("\n"); + return lines.map((line) => { + const [serial, status] = line.trim().split(" "); + return new AdbDevice(serial, status, options2.host, options2.port); + }); + } +} +class AdbDevice { + constructor(serial, status, host, port) { + this._closed = false; + this.serial = serial; + this.status = status; + this.host = host; + this.port = port; + } + async init() { + } + async close() { + this._closed = true; + } + runCommand(command2) { + if (this._closed) + throw new Error("Device is closed"); + return runCommand(command2, this.host, this.port, this.serial); + } + async open(command2) { + if (this._closed) + throw new Error("Device is closed"); + const result = await open(command2, this.host, this.port, this.serial); + result.becomeSocket(); + return result; + } +} +async function runCommand(command2, host = "127.0.0.1", port = 5037, serial) { + debug$2("pw:adb:runCommand")(command2, serial); + const socket = new BufferedSocketWrapper(command2, net.createConnection({ host, port })); + try { + if (serial) { + await socket.write(encodeMessage(`host:transport:${serial}`)); + const status2 = await socket.read(4); + assert(status2.toString() === "OKAY", status2.toString()); + } + await socket.write(encodeMessage(command2)); + const status = await socket.read(4); + assert(status.toString() === "OKAY", status.toString()); + let commandOutput; + if (!command2.startsWith("shell:")) { + const remainingLength = parseInt((await socket.read(4)).toString(), 16); + commandOutput = await socket.read(remainingLength); + } else { + commandOutput = await socket.readAll(); + } + return commandOutput; + } finally { + socket.close(); + } +} +async function open(command2, host = "127.0.0.1", port = 5037, serial) { + const socket = new BufferedSocketWrapper(command2, net.createConnection({ host, port })); + if (serial) { + await socket.write(encodeMessage(`host:transport:${serial}`)); + const status2 = await socket.read(4); + assert(status2.toString() === "OKAY", status2.toString()); + } + await socket.write(encodeMessage(command2)); + const status = await socket.read(4); + assert(status.toString() === "OKAY", status.toString()); + return socket; +} +function encodeMessage(message) { + let lenHex = message.length.toString(16); + lenHex = "0".repeat(4 - lenHex.length) + lenHex; + return Buffer.from(lenHex + message); +} +class BufferedSocketWrapper extends eventsExports.EventEmitter { + constructor(command2, socket) { + super(); + this.guid = createGuid(); + this._buffer = Buffer.from([]); + this._isSocket = false; + this._isClosed = false; + this._command = command2; + this._socket = socket; + this._connectPromise = new Promise((f) => this._socket.on("connect", f)); + this._socket.on("data", (data2) => { + debug$2("pw:adb:data")(data2.toString()); + if (this._isSocket) { + this.emit("data", data2); + return; + } + this._buffer = Buffer.concat([this._buffer, data2]); + if (this._notifyReader) + this._notifyReader(); + }); + this._socket.on("close", () => { + this._isClosed = true; + if (this._notifyReader) + this._notifyReader(); + this.close(); + this.emit("close"); + }); + this._socket.on("error", (error2) => this.emit("error", error2)); + } + async write(data2) { + debug$2("pw:adb:send")(data2.toString().substring(0, 100) + "..."); + await this._connectPromise; + await new Promise((f) => this._socket.write(data2, f)); + } + close() { + if (this._isClosed) + return; + debug$2("pw:adb")("Close " + this._command); + this._socket.destroy(); + } + async read(length) { + await this._connectPromise; + assert(!this._isSocket, "Can not read by length in socket mode"); + while (this._buffer.length < length) + await new Promise((f) => this._notifyReader = f); + const result = this._buffer.slice(0, length); + this._buffer = this._buffer.slice(length); + debug$2("pw:adb:recv")(result.toString().substring(0, 100) + "..."); + return result; + } + async readAll() { + while (!this._isClosed) + await new Promise((f) => this._notifyReader = f); + return this._buffer; + } + becomeSocket() { + assert(!this._buffer.length); + this._isSocket = true; + } +} +class PipeTransport2 { + constructor(pipeWrite, pipeRead) { + this._pendingBuffers = []; + this._waitForNextTask = makeWaitForNextTask(); + this._closed = false; + this._pipeRead = pipeRead; + this._pipeWrite = pipeWrite; + pipeRead.on("data", (buffer2) => this._dispatch(buffer2)); + pipeRead.on("close", () => { + this._closed = true; + if (this._onclose) + this._onclose.call(null); + }); + pipeRead.on("error", (e) => debugLogger.log("error", e)); + pipeWrite.on("error", (e) => debugLogger.log("error", e)); + this.onmessage = void 0; + } + get onclose() { + return this._onclose; + } + set onclose(onclose) { + this._onclose = onclose; + if (onclose && !this._pipeRead.readable) + onclose(); + } + send(message) { + if (this._closed) + throw new Error("Pipe has been closed"); + this._pipeWrite.write(JSON.stringify(message)); + this._pipeWrite.write("\0"); + } + close() { + throw new Error("unimplemented"); + } + _dispatch(buffer2) { + let end = buffer2.indexOf("\0"); + if (end === -1) { + this._pendingBuffers.push(buffer2); + return; + } + this._pendingBuffers.push(buffer2.slice(0, end)); + const message = Buffer.concat(this._pendingBuffers).toString(); + this._waitForNextTask(() => { + if (this.onmessage) + this.onmessage.call(null, JSON.parse(message)); + }); + let start = end + 1; + end = buffer2.indexOf("\0", start); + while (end !== -1) { + const message2 = buffer2.toString(void 0, start, end); + this._waitForNextTask(() => { + if (this.onmessage) + this.onmessage.call(null, JSON.parse(message2)); + }); + start = end + 1; + end = buffer2.indexOf("\0", start); + } + this._pendingBuffers = [buffer2.slice(start)]; + } +} +const kNoXServerRunningError = "Looks like you launched a headed browser without having a XServer running.\nSet either 'headless: true' or use 'xvfb-run ' before running Playwright.\n\n<3 Playwright Team"; +class BrowserReadyState { + constructor() { + this._wsEndpoint = new ManualPromise(); + } + onBrowserExit() { + this._wsEndpoint.resolve(void 0); + } + async waitUntilReady() { + const wsEndpoint = await this._wsEndpoint; + return { wsEndpoint }; + } +} +let BrowserType$1 = class BrowserType extends SdkObject { + constructor(parent, browserName) { + super(parent, "browser-type"); + this.attribution.browserType = this; + this._name = browserName; + } + executablePath() { + return registry.findExecutable(this._name).executablePath(this.attribution.playwright.options.sdkLanguage) || ""; + } + name() { + return this._name; + } + async launch(metadata, options2, protocolLogger) { + options2 = this._validateLaunchOptions(options2); + const controller = new ProgressController(metadata, this); + controller.setLogName("browser"); + const browser2 = await controller.run((progress2) => { + const seleniumHubUrl = options2.__testHookSeleniumRemoteURL || define_process_env_default.SELENIUM_REMOTE_URL; + if (seleniumHubUrl) + return this._launchWithSeleniumHub(progress2, seleniumHubUrl, options2); + return this._innerLaunchWithRetries(progress2, options2, void 0, helper.debugProtocolLogger(protocolLogger)).catch((e) => { + throw this._rewriteStartupLog(e); + }); + }, options2.timeout); + return browser2; + } + async launchPersistentContext(metadata, userDataDir, options2) { + const launchOptions = this._validateLaunchOptions(options2); + const controller = new ProgressController(metadata, this); + controller.setLogName("browser"); + const browser2 = await controller.run(async (progress2) => { + var _a2; + let clientCertificatesProxy; + if ((_a2 = options2.clientCertificates) == null ? void 0 : _a2.length) { + clientCertificatesProxy = new ClientCertificatesProxy(options2); + launchOptions.proxyOverride = await (clientCertificatesProxy == null ? void 0 : clientCertificatesProxy.listen()); + options2 = { ...options2 }; + options2.internalIgnoreHTTPSErrors = true; + } + progress2.cleanupWhenAborted(() => clientCertificatesProxy == null ? void 0 : clientCertificatesProxy.close()); + const browser22 = await this._innerLaunchWithRetries(progress2, launchOptions, options2, helper.debugProtocolLogger(), userDataDir).catch((e) => { + throw this._rewriteStartupLog(e); + }); + browser22._defaultContext._clientCertificatesProxy = clientCertificatesProxy; + return browser22; + }, launchOptions.timeout); + return browser2._defaultContext; + } + async _innerLaunchWithRetries(progress2, options2, persistent, protocolLogger, userDataDir) { + try { + return await this._innerLaunch(progress2, options2, persistent, protocolLogger, userDataDir); + } catch (error2) { + const errorMessage = typeof error2 === "object" && typeof error2.message === "string" ? error2.message : ""; + if (errorMessage.includes("Inconsistency detected by ld.so")) { + progress2.log(``); + return this._innerLaunch(progress2, options2, persistent, protocolLogger, userDataDir); + } + throw error2; + } + } + async _innerLaunch(progress2, options2, persistent, protocolLogger, maybeUserDataDir) { + options2.proxy = options2.proxy ? normalizeProxySettings(options2.proxy) : void 0; + const browserLogsCollector = new RecentLogsCollector(); + const { browserProcess, userDataDir, artifactsDir, transport } = await this._launchProcess(progress2, options2, !!persistent, browserLogsCollector, maybeUserDataDir); + if (options2.__testHookBeforeCreateBrowser) + await options2.__testHookBeforeCreateBrowser(); + const browserOptions = { + name: this._name, + isChromium: this._name === "chromium", + channel: options2.channel, + slowMo: options2.slowMo, + persistent, + headful: !options2.headless, + artifactsDir, + downloadsPath: options2.downloadsPath || artifactsDir, + tracesDir: options2.tracesDir || artifactsDir, + browserProcess, + customExecutablePath: options2.executablePath, + proxy: options2.proxy, + protocolLogger, + browserLogsCollector, + wsEndpoint: transport instanceof WebSocketTransport$1 ? transport.wsEndpoint : void 0, + originalLaunchOptions: options2 + }; + if (persistent) + validateBrowserContextOptions(persistent, browserOptions); + copyTestHooks(options2, browserOptions); + const browser2 = await this.connectToTransport(transport, browserOptions, browserLogsCollector); + browser2._userDataDirForTest = userDataDir; + if (persistent && !options2.ignoreAllDefaultArgs) + await browser2._defaultContext._loadDefaultContext(progress2); + return browser2; + } + async _launchProcess(progress2, options2, isPersistent, browserLogsCollector, userDataDir) { + var _a2; + const { + ignoreDefaultArgs, + ignoreAllDefaultArgs, + args = [], + executablePath = null, + handleSIGINT = true, + handleSIGTERM = true, + handleSIGHUP = true + } = options2; + const env = options2.env ? envArrayToObject(options2.env) : define_process_env_default; + await this._createArtifactDirs(options2); + const tempDirectories = []; + const artifactsDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "playwright-artifacts-")); + tempDirectories.push(artifactsDir); + if (userDataDir) { + assert(path.isAbsolute(userDataDir), "userDataDir must be an absolute path"); + if (!await existsAsync(userDataDir)) + await fs.promises.mkdir(userDataDir, { recursive: true, mode: 448 }); + } else { + userDataDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `playwright_${this._name}dev_profile-`)); + tempDirectories.push(userDataDir); + } + await this.prepareUserDataDir(options2, userDataDir); + const browserArguments = []; + if (ignoreAllDefaultArgs) + browserArguments.push(...args); + else if (ignoreDefaultArgs) + browserArguments.push(...this.defaultArgs(options2, isPersistent, userDataDir).filter((arg) => ignoreDefaultArgs.indexOf(arg) === -1)); + else + browserArguments.push(...this.defaultArgs(options2, isPersistent, userDataDir)); + let executable; + if (executablePath) { + if (!await existsAsync(executablePath)) + throw new Error(`Failed to launch ${this._name} because executable doesn't exist at ${executablePath}`); + executable = executablePath; + } else { + const registryExecutable = registry.findExecutable(this.getExecutableName(options2)); + if (!registryExecutable || registryExecutable.browserName !== this._name) + throw new Error(`Unsupported ${this._name} channel "${options2.channel}"`); + executable = registryExecutable.executablePathOrDie(this.attribution.playwright.options.sdkLanguage); + await registry.validateHostRequirementsForExecutablesIfNeeded([registryExecutable], this.attribution.playwright.options.sdkLanguage); + } + const readyState = this.readyState(options2); + let transport = void 0; + let browserProcess = void 0; + const { launchedProcess, gracefullyClose, kill } = await launchProcess({ + command: executable, + args: browserArguments, + env: this.amendEnvironment(env, userDataDir, executable, browserArguments), + handleSIGINT, + handleSIGTERM, + handleSIGHUP, + log: (message) => { + readyState == null ? void 0 : readyState.onBrowserOutput(message); + progress2.log(message); + browserLogsCollector.log(message); + }, + stdio: "pipe", + tempDirectories, + attemptToGracefullyClose: async () => { + if (options2.__testHookGracefullyClose) + await options2.__testHookGracefullyClose(); + this.attemptToGracefullyCloseBrowser(transport); + }, + onExit: (exitCode, signal) => { + readyState == null ? void 0 : readyState.onBrowserExit(); + if (browserProcess && browserProcess.onclose) + browserProcess.onclose(exitCode, signal); + } + }); + async function closeOrKill(timeout) { + let timer; + try { + await Promise.race([ + gracefullyClose(), + new Promise((resolve, reject) => timer = setTimeout(reject, timeout)) + ]); + } catch (ignored) { + await kill().catch((ignored2) => { + }); + } finally { + clearTimeout(timer); + } + } + browserProcess = { + onclose: void 0, + process: launchedProcess, + close: () => closeOrKill(options2.__testHookBrowserCloseTimeout || DEFAULT_PLAYWRIGHT_TIMEOUT), + kill + }; + progress2.cleanupWhenAborted(() => closeOrKill(progress2.timeUntilDeadline())); + const wsEndpoint = (_a2 = await (readyState == null ? void 0 : readyState.waitUntilReady())) == null ? void 0 : _a2.wsEndpoint; + if (options2.cdpPort !== void 0 || !this.supportsPipeTransport()) { + transport = await WebSocketTransport$1.connect(progress2, wsEndpoint); + } else { + const stdio = launchedProcess.stdio; + transport = new PipeTransport2(stdio[3], stdio[4]); + } + return { browserProcess, artifactsDir, userDataDir, transport }; + } + async _createArtifactDirs(options2) { + if (options2.downloadsPath) + await fs.promises.mkdir(options2.downloadsPath, { recursive: true }); + if (options2.tracesDir) + await fs.promises.mkdir(options2.tracesDir, { recursive: true }); + } + async connectOverCDP(metadata, endpointURL, options2) { + throw new Error("CDP connections are only supported by Chromium"); + } + async _launchWithSeleniumHub(progress2, hubUrl, options2) { + throw new Error("Connecting to SELENIUM_REMOTE_URL is only supported by Chromium"); + } + _validateLaunchOptions(options2) { + const { devtools = false } = options2; + let { headless = !devtools, downloadsPath, proxy } = options2; + if (debugMode()) + headless = false; + if (downloadsPath && !path.isAbsolute(downloadsPath)) + downloadsPath = path.join(process.cwd(), downloadsPath); + if (this.attribution.playwright.options.socksProxyPort) + proxy = { server: `socks5://127.0.0.1:${this.attribution.playwright.options.socksProxyPort}` }; + return { ...options2, devtools, headless, downloadsPath, proxy }; + } + _createUserDataDirArgMisuseError(userDataDirArg) { + switch (this.attribution.playwright.options.sdkLanguage) { + case "java": + return new Error(`Pass userDataDir parameter to 'BrowserType.launchPersistentContext(userDataDir, options)' instead of specifying '${userDataDirArg}' argument`); + case "python": + return new Error(`Pass user_data_dir parameter to 'browser_type.launch_persistent_context(user_data_dir, **kwargs)' instead of specifying '${userDataDirArg}' argument`); + case "csharp": + return new Error(`Pass userDataDir parameter to 'BrowserType.LaunchPersistentContextAsync(userDataDir, options)' instead of specifying '${userDataDirArg}' argument`); + default: + return new Error(`Pass userDataDir parameter to 'browserType.launchPersistentContext(userDataDir, options)' instead of specifying '${userDataDirArg}' argument`); + } + } + _rewriteStartupLog(error2) { + if (!isProtocolError(error2)) + return error2; + return this.doRewriteStartupLog(error2); + } + readyState(options2) { + return void 0; + } + async prepareUserDataDir(options2, userDataDir) { + } + supportsPipeTransport() { + return true; + } + getExecutableName(options2) { + return options2.channel || this._name; + } +}; +function copyTestHooks(from2, to) { + for (const [key2, value] of Object.entries(from2)) { + if (key2.startsWith("__testHook")) + to[key2] = value; + } +} +const kBrowserCloseMessageId$2 = 0; +class BidiConnection { + constructor(transport, onDisconnect, protocolLogger, browserLogsCollector) { + this._lastId = 0; + this._closed = false; + this._browsingContextToSession = /* @__PURE__ */ new Map(); + this._transport = transport; + this._onDisconnect = onDisconnect; + this._protocolLogger = protocolLogger; + this._browserLogsCollector = browserLogsCollector; + this.browserSession = new BidiSession(this, "", (message) => { + this.rawSend(message); + }); + this._transport.onmessage = this._dispatchMessage.bind(this); + this._transport.onclose = this._onClose.bind(this); + } + nextMessageId() { + return ++this._lastId; + } + rawSend(message) { + this._protocolLogger("send", message); + this._transport.send(message); + } + _dispatchMessage(message) { + var _a2; + this._protocolLogger("receive", message); + const object = message; + if (object.type === "event") { + let context; + if ("context" in object.params) + context = object.params.context; + else if (object.method === "log.entryAdded" || object.method === "script.message") + context = (_a2 = object.params.source) == null ? void 0 : _a2.context; + if (context) { + const session = this._browsingContextToSession.get(context); + if (session) { + session.dispatchMessage(message); + return; + } + } + } else if (message.id) { + for (const session of this._browsingContextToSession.values()) { + if (session.hasCallback(message.id)) { + session.dispatchMessage(message); + return; + } + } + } + this.browserSession.dispatchMessage(message); + } + _onClose(reason) { + this._closed = true; + this._transport.onmessage = void 0; + this._transport.onclose = void 0; + this._browserDisconnectedLogs = helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason); + this.browserSession.dispose(); + this._onDisconnect(); + } + isClosed() { + return this._closed; + } + close() { + if (!this._closed) + this._transport.close(); + } + createMainFrameBrowsingContextSession(bowsingContextId) { + const result = new BidiSession(this, bowsingContextId, (message) => this.rawSend(message)); + this._browsingContextToSession.set(bowsingContextId, result); + return result; + } +} +class BidiSession extends eventsExports.EventEmitter { + constructor(connection, sessionId, rawSend) { + super(); + this._disposed = false; + this._callbacks = /* @__PURE__ */ new Map(); + this._crashed = false; + this._browsingContexts = /* @__PURE__ */ new Set(); + this.setMaxListeners(0); + this.connection = connection; + this.sessionId = sessionId; + this._rawSend = rawSend; + this.on = super.on; + this.off = super.removeListener; + this.addListener = super.addListener; + this.removeListener = super.removeListener; + this.once = super.once; + } + addFrameBrowsingContext(context) { + this._browsingContexts.add(context); + this.connection._browsingContextToSession.set(context, this); + } + removeFrameBrowsingContext(context) { + this._browsingContexts.delete(context); + this.connection._browsingContextToSession.delete(context); + } + async send(method, params) { + if (this._crashed || this._disposed || this.connection._browserDisconnectedLogs) + throw new ProtocolError(this._crashed ? "crashed" : "closed", void 0, this.connection._browserDisconnectedLogs); + const id = this.connection.nextMessageId(); + const messageObj = { id, method, params }; + this._rawSend(messageObj); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + sendMayFail(method, params) { + return this.send(method, params).catch((error2) => debugLogger.log("error", error2)); + } + markAsCrashed() { + this._crashed = true; + } + isDisposed() { + return this._disposed; + } + dispose() { + this._disposed = true; + this.connection._browsingContextToSession.delete(this.sessionId); + for (const context of this._browsingContexts) + this.connection._browsingContextToSession.delete(context); + this._browsingContexts.clear(); + for (const callback of this._callbacks.values()) { + callback.error.type = this._crashed ? "crashed" : "closed"; + callback.error.logs = this.connection._browserDisconnectedLogs; + callback.reject(callback.error); + } + this._callbacks.clear(); + } + hasCallback(id) { + return this._callbacks.has(id); + } + dispatchMessage(message) { + const object = message; + if (object.id === kBrowserCloseMessageId$2) + return; + if (object.id && this._callbacks.has(object.id)) { + const callback = this._callbacks.get(object.id); + this._callbacks.delete(object.id); + if (object.type === "error") { + callback.error.setMessage(object.error + "\nMessage: " + object.message); + callback.reject(callback.error); + } else if (object.type === "success") { + callback.resolve(object.result); + } else { + callback.error.setMessage("Internal error, unexpected response type: " + JSON.stringify(object)); + callback.reject(callback.error); + } + } else if (object.id) ; + else { + Promise.resolve().then(() => this.emit(object.method, object.params)); + } + } +} +/** + * @license + * Copyright 2024 Google Inc. + * Modifications copyright (c) Microsoft Corporation. + * SPDX-License-Identifier: Apache-2.0 + */ +var Session; +((Session2) => { + ((UserPromptHandlerType2) => { + UserPromptHandlerType2["Accept"] = "accept"; + UserPromptHandlerType2["Dismiss"] = "dismiss"; + UserPromptHandlerType2["Ignore"] = "ignore"; + })(Session2.UserPromptHandlerType || (Session2.UserPromptHandlerType = {})); +})(Session || (Session = {})); +var BrowsingContext; +((BrowsingContext2) => { + ((ReadinessState2) => { + ReadinessState2["None"] = "none"; + ReadinessState2["Interactive"] = "interactive"; + ReadinessState2["Complete"] = "complete"; + })(BrowsingContext2.ReadinessState || (BrowsingContext2.ReadinessState = {})); +})(BrowsingContext || (BrowsingContext = {})); +((BrowsingContext2) => { + ((UserPromptType2) => { + UserPromptType2["Alert"] = "alert"; + UserPromptType2["Beforeunload"] = "beforeunload"; + UserPromptType2["Confirm"] = "confirm"; + UserPromptType2["Prompt"] = "prompt"; + })(BrowsingContext2.UserPromptType || (BrowsingContext2.UserPromptType = {})); +})(BrowsingContext || (BrowsingContext = {})); +((BrowsingContext2) => { + ((CreateType2) => { + CreateType2["Tab"] = "tab"; + CreateType2["Window"] = "window"; + })(BrowsingContext2.CreateType || (BrowsingContext2.CreateType = {})); +})(BrowsingContext || (BrowsingContext = {})); +var Network$1; +((Network2) => { + ((SameSite2) => { + SameSite2["Strict"] = "strict"; + SameSite2["Lax"] = "lax"; + SameSite2["None"] = "none"; + })(Network2.SameSite || (Network2.SameSite = {})); +})(Network$1 || (Network$1 = {})); +((Network2) => { + ((InterceptPhase2) => { + InterceptPhase2["BeforeRequestSent"] = "beforeRequestSent"; + InterceptPhase2["ResponseStarted"] = "responseStarted"; + InterceptPhase2["AuthRequired"] = "authRequired"; + })(Network2.InterceptPhase || (Network2.InterceptPhase = {})); +})(Network$1 || (Network$1 = {})); +var Script; +((Script2) => { + ((ResultOwnership2) => { + ResultOwnership2["Root"] = "root"; + ResultOwnership2["None"] = "none"; + })(Script2.ResultOwnership || (Script2.ResultOwnership = {})); +})(Script || (Script = {})); +var Log; +((Log2) => { + ((Level2) => { + Level2["Debug"] = "debug"; + Level2["Info"] = "info"; + Level2["Warn"] = "warn"; + Level2["Error"] = "error"; + })(Log2.Level || (Log2.Level = {})); +})(Log || (Log = {})); +var Input; +((Input2) => { + ((PointerType2) => { + PointerType2["Mouse"] = "mouse"; + PointerType2["Pen"] = "pen"; + PointerType2["Touch"] = "touch"; + })(Input2.PointerType || (Input2.PointerType = {})); +})(Input || (Input = {})); +/** + * @license + * Copyright 2024 Google Inc. + * Modifications copyright (c) Microsoft Corporation. + * SPDX-License-Identifier: Apache-2.0 + */ +var Permissions; +((Permissions2) => { + ((PermissionState2) => { + PermissionState2["Granted"] = "granted"; + PermissionState2["Denied"] = "denied"; + PermissionState2["Prompt"] = "prompt"; + })(Permissions2.PermissionState || (Permissions2.PermissionState = {})); +})(Permissions || (Permissions = {})); +class BidiNetworkManager { + constructor(bidiSession, page, onNavigationResponseStarted) { + this._userRequestInterceptionEnabled = false; + this._protocolRequestInterceptionEnabled = false; + this._session = bidiSession; + this._requests = /* @__PURE__ */ new Map(); + this._page = page; + this._onNavigationResponseStarted = onNavigationResponseStarted; + this._eventListeners = [ + eventsHelper.addEventListener(bidiSession, "network.beforeRequestSent", this._onBeforeRequestSent.bind(this)), + eventsHelper.addEventListener(bidiSession, "network.responseStarted", this._onResponseStarted.bind(this)), + eventsHelper.addEventListener(bidiSession, "network.responseCompleted", this._onResponseCompleted.bind(this)), + eventsHelper.addEventListener(bidiSession, "network.fetchError", this._onFetchError.bind(this)), + eventsHelper.addEventListener(bidiSession, "network.authRequired", this._onAuthRequired.bind(this)) + ]; + } + dispose() { + eventsHelper.removeEventListeners(this._eventListeners); + } + _onBeforeRequestSent(param) { + var _a2; + if (param.request.url.startsWith("data:")) + return; + const redirectedFrom = param.redirectCount ? this._requests.get(param.request.request) || null : null; + const frame = redirectedFrom ? redirectedFrom.request.frame() : param.context ? this._page.frameManager.frame(param.context) : null; + if (!frame) + return; + if (redirectedFrom) + this._requests.delete(redirectedFrom._id); + let route; + if (param.intercepts) { + if (redirectedFrom) { + let params = {}; + if ((_a2 = redirectedFrom._originalRequestRoute) == null ? void 0 : _a2._alreadyContinuedHeaders) + params = toBidiRequestHeaders(redirectedFrom._originalRequestRoute._alreadyContinuedHeaders ?? []); + this._session.sendMayFail("network.continueRequest", { + request: param.request.request, + ...params + }); + } else { + route = new BidiRouteImpl(this._session, param.request.request); + } + } + const request2 = new BidiRequest(frame, redirectedFrom, param, route); + this._requests.set(request2._id, request2); + this._page.frameManager.requestStarted(request2.request, route); + } + _onResponseStarted(params) { + const request2 = this._requests.get(params.request.request); + if (!request2) + return; + const getResponseBody = async () => { + throw new Error(`Response body is not available for requests in Bidi`); + }; + const timings = params.request.timings; + const startTime = timings.requestTime; + function relativeToStart(time) { + if (!time) + return -1; + return time - startTime; + } + const timing = { + startTime, + requestStart: relativeToStart(timings.requestStart), + responseStart: relativeToStart(timings.responseStart), + domainLookupStart: relativeToStart(timings.dnsStart), + domainLookupEnd: relativeToStart(timings.dnsEnd), + connectStart: relativeToStart(timings.connectStart), + secureConnectionStart: relativeToStart(timings.tlsStart), + connectEnd: relativeToStart(timings.connectEnd) + }; + const response2 = new Response$1(request2.request, params.response.status, params.response.statusText, fromBidiHeaders(params.response.headers), timing, getResponseBody, false); + response2._serverAddrFinished(); + response2._securityDetailsFinished(); + response2.setRawResponseHeaders(null); + response2.setResponseHeadersSize(params.response.headersSize); + this._page.frameManager.requestReceivedResponse(response2); + if (params.navigation) + this._onNavigationResponseStarted(params); + } + _onResponseCompleted(params) { + const request2 = this._requests.get(params.request.request); + if (!request2) + return; + const response2 = request2.request._existingResponse(); + response2.setTransferSize(params.response.bodySize); + response2.setEncodedBodySize(params.response.bodySize); + const isRedirected = response2.status() >= 300 && response2.status() <= 399; + const responseEndTime = params.request.timings.responseEnd - response2.timing().startTime; + if (isRedirected) { + response2._requestFinished(responseEndTime); + } else { + this._requests.delete(request2._id); + response2._requestFinished(responseEndTime); + } + response2._setHttpVersion(params.response.protocol); + this._page.frameManager.reportRequestFinished(request2.request, response2); + } + _onFetchError(params) { + const request2 = this._requests.get(params.request.request); + if (!request2) + return; + this._requests.delete(request2._id); + const response2 = request2.request._existingResponse(); + if (response2) { + response2.setTransferSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(-1); + } + request2.request._setFailureText(params.errorText); + this._page.frameManager.requestFailed(request2.request, params.errorText === "NS_BINDING_ABORTED"); + } + _onAuthRequired(params) { + var _a2; + const isBasic = (_a2 = params.response.authChallenges) == null ? void 0 : _a2.some((challenge) => challenge.scheme.startsWith("Basic")); + const credentials = this._page.browserContext._options.httpCredentials; + if (isBasic && credentials) { + this._session.sendMayFail("network.continueWithAuth", { + request: params.request.request, + action: "provideCredentials", + credentials: { + type: "password", + username: credentials.username, + password: credentials.password + } + }); + } else { + this._session.sendMayFail("network.continueWithAuth", { + request: params.request.request, + action: "default" + }); + } + } + async setRequestInterception(value) { + this._userRequestInterceptionEnabled = value; + await this._updateProtocolRequestInterception(); + } + async setCredentials(credentials) { + this._credentials = credentials; + await this._updateProtocolRequestInterception(); + } + async _updateProtocolRequestInterception(initial) { + const enabled = this._userRequestInterceptionEnabled || !!this._credentials; + if (enabled === this._protocolRequestInterceptionEnabled) + return; + this._protocolRequestInterceptionEnabled = enabled; + if (initial && !enabled) + return; + const cachePromise = this._session.send("network.setCacheBehavior", { cacheBehavior: enabled ? "bypass" : "default" }); + let interceptPromise = Promise.resolve(void 0); + if (enabled) { + interceptPromise = this._session.send("network.addIntercept", { + phases: [Network$1.InterceptPhase.AuthRequired, Network$1.InterceptPhase.BeforeRequestSent], + urlPatterns: [{ type: "pattern" }] + // urlPatterns: [{ type: 'string', pattern: '*' }], + }).then((r) => { + this._intercepId = r.intercept; + }); + } else if (this._intercepId) { + interceptPromise = this._session.send("network.removeIntercept", { intercept: this._intercepId }); + this._intercepId = void 0; + } + await Promise.all([cachePromise, interceptPromise]); + } +} +class BidiRequest { + constructor(frame, redirectedFrom, payload, route) { + this._id = payload.request.request; + if (redirectedFrom) + redirectedFrom._redirectedTo = this; + const postDataBuffer = null; + this.request = new Request$1( + frame._page.browserContext, + frame, + null, + redirectedFrom ? redirectedFrom.request : null, + payload.navigation ?? void 0, + payload.request.url, + "other", + payload.request.method, + postDataBuffer, + fromBidiHeaders(payload.request.headers) + ); + this.request.setRawRequestHeaders(null); + this.request._setBodySize(payload.request.bodySize || 0); + this._originalRequestRoute = route ?? (redirectedFrom == null ? void 0 : redirectedFrom._originalRequestRoute); + route == null ? void 0 : route._setRequest(this.request); + } + _finalRequest() { + let request2 = this; + while (request2._redirectedTo) + request2 = request2._redirectedTo; + return request2; + } +} +class BidiRouteImpl { + constructor(session, requestId) { + this._session = session; + this._requestId = requestId; + } + _setRequest(request2) { + this._request = request2; + } + async continue(overrides) { + let headers = overrides.headers || this._request.headers(); + if (overrides.postData && headers) { + headers = headers.map((header) => { + if (header.name.toLowerCase() === "content-length") + return { name: header.name, value: overrides.postData.byteLength.toString() }; + return header; + }); + } + this._alreadyContinuedHeaders = headers; + await this._session.sendMayFail("network.continueRequest", { + request: this._requestId, + url: overrides.url, + method: overrides.method, + ...toBidiRequestHeaders(this._alreadyContinuedHeaders), + body: overrides.postData ? { type: "base64", value: Buffer.from(overrides.postData).toString("base64") } : void 0 + }); + } + async fulfill(response2) { + const base64body = response2.isBase64 ? response2.body : Buffer.from(response2.body).toString("base64"); + await this._session.sendMayFail("network.provideResponse", { + request: this._requestId, + statusCode: response2.status, + reasonPhrase: statusText(response2.status), + ...toBidiResponseHeaders(response2.headers), + body: { type: "base64", value: base64body } + }); + } + async abort(errorCode) { + await this._session.sendMayFail("network.failRequest", { + request: this._requestId + }); + } +} +function fromBidiHeaders(bidiHeaders) { + const result = []; + for (const { name, value } of bidiHeaders) + result.push({ name, value: bidiBytesValueToString(value) }); + return result; +} +function toBidiRequestHeaders(allHeaders) { + const bidiHeaders = toBidiHeaders(allHeaders); + return { headers: bidiHeaders }; +} +function toBidiResponseHeaders(headers) { + const setCookieHeaders = headers.filter((h) => h.name.toLowerCase() === "set-cookie"); + const otherHeaders = headers.filter((h) => h.name.toLowerCase() !== "set-cookie"); + const rawCookies = setCookieHeaders.map((h) => parseRawCookie(h.value)); + const cookies = rawCookies.filter(Boolean).map((c) => { + return { + ...c, + value: { type: "string", value: c.value }, + sameSite: toBidiSameSite$1(c.sameSite) + }; + }); + return { cookies, headers: toBidiHeaders(otherHeaders) }; +} +function toBidiHeaders(headers) { + return headers.map(({ name, value }) => ({ name, value: { type: "string", value } })); +} +function bidiBytesValueToString(value) { + if (value.type === "string") + return value.value; + if (value.type === "base64") + return Buffer.from(value.type, "base64").toString("binary"); + return "unknown value type: " + value.type; +} +function toBidiSameSite$1(sameSite) { + if (!sameSite) + return void 0; + if (sameSite === "Strict") + return Network$1.SameSite.Strict; + if (sameSite === "Lax") + return Network$1.SameSite.Lax; + return Network$1.SameSite.None; +} +/** + * @license + * Copyright 2024 Google Inc. + * Modifications copyright (c) Microsoft Corporation. + * SPDX-License-Identifier: Apache-2.0 + */ +class BidiDeserializer { + static deserialize(result) { + var _a2, _b2, _c2, _d2; + if (!result) + return void 0; + switch (result.type) { + case "array": + return (_a2 = result.value) == null ? void 0 : _a2.map((value) => { + return BidiDeserializer.deserialize(value); + }); + case "set": + return (_b2 = result.value) == null ? void 0 : _b2.reduce((acc, value) => { + return acc.add(BidiDeserializer.deserialize(value)); + }, /* @__PURE__ */ new Set()); + case "object": + return (_c2 = result.value) == null ? void 0 : _c2.reduce((acc, tuple) => { + const { key: key2, value } = BidiDeserializer._deserializeTuple(tuple); + acc[key2] = value; + return acc; + }, {}); + case "map": + return (_d2 = result.value) == null ? void 0 : _d2.reduce((acc, tuple) => { + const { key: key2, value } = BidiDeserializer._deserializeTuple(tuple); + return acc.set(key2, value); + }, /* @__PURE__ */ new Map()); + case "promise": + return {}; + case "regexp": + return new RegExp(result.value.pattern, result.value.flags); + case "date": + return new Date(result.value); + case "undefined": + return void 0; + case "null": + return null; + case "number": + return BidiDeserializer._deserializeNumber(result.value); + case "bigint": + return BigInt(result.value); + case "boolean": + return Boolean(result.value); + case "string": + return result.value; + } + throw new Error(`Deserialization of type ${result.type} not supported.`); + } + static _deserializeNumber(value) { + switch (value) { + case "-0": + return -0; + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + return value; + } + } + static _deserializeTuple([serializedKey, serializedValue]) { + const key2 = typeof serializedKey === "string" ? serializedKey : BidiDeserializer.deserialize(serializedKey); + const value = BidiDeserializer.deserialize(serializedValue); + return { key: key2, value }; + } +} +/** + * @license + * Copyright 2024 Google Inc. + * Modifications copyright (c) Microsoft Corporation. + * SPDX-License-Identifier: Apache-2.0 + */ +class UnserializableError extends Error { +} +class BidiSerializer { + static serialize(arg) { + switch (typeof arg) { + case "symbol": + case "function": + throw new UnserializableError(`Unable to serializable ${typeof arg}`); + case "object": + return BidiSerializer._serializeObject(arg); + case "undefined": + return { + type: "undefined" + }; + case "number": + return BidiSerializer._serializeNumber(arg); + case "bigint": + return { + type: "bigint", + value: arg.toString() + }; + case "string": + return { + type: "string", + value: arg + }; + case "boolean": + return { + type: "boolean", + value: arg + }; + } + } + static _serializeNumber(arg) { + let value; + if (Object.is(arg, -0)) { + value = "-0"; + } else if (Object.is(arg, Infinity)) { + value = "Infinity"; + } else if (Object.is(arg, -Infinity)) { + value = "-Infinity"; + } else if (Object.is(arg, NaN)) { + value = "NaN"; + } else { + value = arg; + } + return { + type: "number", + value + }; + } + static _serializeObject(arg) { + if (arg === null) { + return { + type: "null" + }; + } else if (Array.isArray(arg)) { + const parsedArray = arg.map((subArg) => { + return BidiSerializer.serialize(subArg); + }); + return { + type: "array", + value: parsedArray + }; + } else if (isPlainObject(arg)) { + try { + JSON.stringify(arg); + } catch (error2) { + if (error2 instanceof TypeError && error2.message.startsWith("Converting circular structure to JSON")) { + error2.message += " Recursive objects are not allowed."; + } + throw error2; + } + const parsedObject = []; + for (const key2 in arg) { + parsedObject.push([BidiSerializer.serialize(key2), BidiSerializer.serialize(arg[key2])]); + } + return { + type: "object", + value: parsedObject + }; + } else if (isRegExp(arg)) { + return { + type: "regexp", + value: { + pattern: arg.source, + flags: arg.flags + } + }; + } else if (isDate(arg)) { + return { + type: "date", + value: arg.toISOString() + }; + } + throw new UnserializableError( + "Custom object serialization not possible. Use plain objects instead." + ); + } +} +const isPlainObject = (obj) => { + return typeof obj === "object" && (obj == null ? void 0 : obj.constructor) === Object; +}; +const isRegExp = (obj) => { + return typeof obj === "object" && (obj == null ? void 0 : obj.constructor) === RegExp; +}; +const isDate = (obj) => { + return typeof obj === "object" && (obj == null ? void 0 : obj.constructor) === Date; +}; +class BidiExecutionContext { + constructor(session, realmInfo) { + this._session = session; + if (realmInfo.type === "window") { + this._target = { + context: realmInfo.context, + sandbox: realmInfo.sandbox + }; + } else { + this._target = { + realm: realmInfo.realm + }; + } + } + async rawEvaluateJSON(expression) { + const response2 = await this._session.send("script.evaluate", { + expression, + target: this._target, + serializationOptions: { + maxObjectDepth: 10, + maxDomDepth: 10 + }, + awaitPromise: true, + userActivation: true + }); + if (response2.type === "success") + return BidiDeserializer.deserialize(response2.result); + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text + "\nFull val: " + JSON.stringify(response2.exceptionDetails)); + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } + async rawEvaluateHandle(context, expression) { + const response2 = await this._session.send("script.evaluate", { + expression, + target: this._target, + resultOwnership: Script.ResultOwnership.Root, + // Necessary for the handle to be returned. + serializationOptions: { maxObjectDepth: 0, maxDomDepth: 0 }, + awaitPromise: true, + userActivation: true + }); + if (response2.type === "success") { + if ("handle" in response2.result) + return createHandle$2(context, response2.result); + throw new JavaScriptErrorInEvaluate("Cannot get handle: " + JSON.stringify(response2.result)); + } + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text + "\nFull val: " + JSON.stringify(response2.exceptionDetails)); + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } + async evaluateWithArguments(functionDeclaration, returnByValue, utilityScript, values, handles) { + const response2 = await this._session.send("script.callFunction", { + functionDeclaration, + target: this._target, + arguments: [ + { handle: utilityScript._objectId }, + ...values.map(BidiSerializer.serialize), + ...handles.map((handle) => ({ handle: handle._objectId })) + ], + resultOwnership: returnByValue ? void 0 : Script.ResultOwnership.Root, + // Necessary for the handle to be returned. + serializationOptions: returnByValue ? {} : { maxObjectDepth: 0, maxDomDepth: 0 }, + awaitPromise: true, + userActivation: true + }); + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text + "\nFull val: " + JSON.stringify(response2.exceptionDetails)); + if (response2.type === "success") { + if (returnByValue) + return parseEvaluationResultValue(BidiDeserializer.deserialize(response2.result)); + return createHandle$2(utilityScript._context, response2.result); + } + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } + async getProperties(handle) { + const names = await handle.evaluate((object) => { + var _a2; + const names2 = []; + const descriptors = Object.getOwnPropertyDescriptors(object); + for (const name in descriptors) { + if ((_a2 = descriptors[name]) == null ? void 0 : _a2.enumerable) + names2.push(name); + } + return names2; + }); + const values = await Promise.all(names.map((name) => handle.evaluateHandle((object, name2) => object[name2], name))); + const map2 = /* @__PURE__ */ new Map(); + for (let i = 0; i < names.length; i++) + map2.set(names[i], values[i]); + return map2; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await this._session.send("script.disown", { + target: this._target, + handles: [handle._objectId] + }); + } + async nodeIdForElementHandle(handle) { + const shared = await this._remoteValueForReference({ handle: handle._objectId }); + if (!("sharedId" in shared)) + throw new Error("Element is not a node"); + return { + sharedId: shared.sharedId + }; + } + async remoteObjectForNodeId(context, nodeId) { + const result = await this._remoteValueForReference(nodeId, true); + if (!("handle" in result)) + throw new Error("Can't get remote object for nodeId"); + return createHandle$2(context, result); + } + async contentFrameIdForFrame(handle) { + const contentWindow = await this._rawCallFunction("e => e.contentWindow", { handle: handle._objectId }); + if ((contentWindow == null ? void 0 : contentWindow.type) === "window") + return contentWindow.value.context; + return null; + } + async frameIdForWindowHandle(handle) { + if (!handle._objectId) + throw new Error("JSHandle is not a DOM node handle"); + const contentWindow = await this._remoteValueForReference({ handle: handle._objectId }); + if (contentWindow.type === "window") + return contentWindow.value.context; + return null; + } + async _remoteValueForReference(reference, createHandle2) { + return await this._rawCallFunction("e => e", reference, createHandle2); + } + async _rawCallFunction(functionDeclaration, arg, createHandle2) { + const response2 = await this._session.send("script.callFunction", { + functionDeclaration, + target: this._target, + arguments: [arg], + // "Root" is necessary for the handle to be returned. + resultOwnership: createHandle2 ? Script.ResultOwnership.Root : Script.ResultOwnership.None, + serializationOptions: { maxObjectDepth: 0, maxDomDepth: 0 }, + awaitPromise: true, + userActivation: true + }); + if (response2.type === "exception") + throw new JavaScriptErrorInEvaluate(response2.exceptionDetails.text + "\nFull val: " + JSON.stringify(response2.exceptionDetails)); + if (response2.type === "success") + return response2.result; + throw new JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response2)); + } +} +function renderPreview$2(remoteObject) { + if (remoteObject.type === "undefined") + return "undefined"; + if (remoteObject.type === "null") + return "null"; + if ("value" in remoteObject) + return String(remoteObject.value); + return `<${remoteObject.type}>`; +} +function remoteObjectValue(remoteObject) { + if (remoteObject.type === "undefined") + return void 0; + if (remoteObject.type === "null") + return null; + if (remoteObject.type === "number" && typeof remoteObject.value === "string") + return parseUnserializableValue(remoteObject.value); + if ("value" in remoteObject) + return remoteObject.value; + return void 0; +} +function createHandle$2(context, remoteObject) { + if (remoteObject.type === "node") { + assert(context instanceof FrameExecutionContext); + return new ElementHandle$1(context, remoteObject.handle); + } + const objectId = "handle" in remoteObject ? remoteObject.handle : void 0; + return new JSHandle$1(context, remoteObject.type, renderPreview$2(remoteObject), objectId, remoteObjectValue(remoteObject)); +} +/** + * @license + * Copyright 2024 Google Inc. + * Modifications copyright (c) Microsoft Corporation. + * SPDX-License-Identifier: Apache-2.0 + */ +const getBidiKeyValue = (keyName) => { + switch (keyName) { + case "\r": + case "\n": + keyName = "Enter"; + break; + } + if ([...keyName].length === 1) { + return keyName; + } + switch (keyName) { + case "Cancel": + return ""; + case "Help": + return ""; + case "Backspace": + return ""; + case "Tab": + return ""; + case "Clear": + return ""; + case "Enter": + return ""; + case "Shift": + case "ShiftLeft": + return ""; + case "Control": + case "ControlLeft": + return ""; + case "Alt": + case "AltLeft": + return ""; + case "Pause": + return ""; + case "Escape": + return ""; + case "PageUp": + return ""; + case "PageDown": + return ""; + case "End": + return ""; + case "Home": + return ""; + case "ArrowLeft": + return ""; + case "ArrowUp": + return ""; + case "ArrowRight": + return ""; + case "ArrowDown": + return ""; + case "Insert": + return ""; + case "Delete": + return ""; + case "NumpadEqual": + return ""; + case "Numpad0": + return ""; + case "Numpad1": + return ""; + case "Numpad2": + return ""; + case "Numpad3": + return ""; + case "Numpad4": + return ""; + case "Numpad5": + return ""; + case "Numpad6": + return ""; + case "Numpad7": + return ""; + case "Numpad8": + return ""; + case "Numpad9": + return ""; + case "NumpadMultiply": + return ""; + case "NumpadAdd": + return ""; + case "NumpadSubtract": + return ""; + case "NumpadDecimal": + return ""; + case "NumpadDivide": + return ""; + case "F1": + return ""; + case "F2": + return ""; + case "F3": + return ""; + case "F4": + return ""; + case "F5": + return ""; + case "F6": + return ""; + case "F7": + return ""; + case "F8": + return ""; + case "F9": + return ""; + case "F10": + return ""; + case "F11": + return ""; + case "F12": + return ""; + case "Meta": + case "MetaLeft": + return ""; + case "ShiftRight": + return ""; + case "ControlRight": + return ""; + case "AltRight": + return ""; + case "MetaRight": + return ""; + case "Space": + return " "; + case "Digit0": + return "0"; + case "Digit1": + return "1"; + case "Digit2": + return "2"; + case "Digit3": + return "3"; + case "Digit4": + return "4"; + case "Digit5": + return "5"; + case "Digit6": + return "6"; + case "Digit7": + return "7"; + case "Digit8": + return "8"; + case "Digit9": + return "9"; + case "KeyA": + return "a"; + case "KeyB": + return "b"; + case "KeyC": + return "c"; + case "KeyD": + return "d"; + case "KeyE": + return "e"; + case "KeyF": + return "f"; + case "KeyG": + return "g"; + case "KeyH": + return "h"; + case "KeyI": + return "i"; + case "KeyJ": + return "j"; + case "KeyK": + return "k"; + case "KeyL": + return "l"; + case "KeyM": + return "m"; + case "KeyN": + return "n"; + case "KeyO": + return "o"; + case "KeyP": + return "p"; + case "KeyQ": + return "q"; + case "KeyR": + return "r"; + case "KeyS": + return "s"; + case "KeyT": + return "t"; + case "KeyU": + return "u"; + case "KeyV": + return "v"; + case "KeyW": + return "w"; + case "KeyX": + return "x"; + case "KeyY": + return "y"; + case "KeyZ": + return "z"; + case "Semicolon": + return ";"; + case "Equal": + return "="; + case "Comma": + return ","; + case "Minus": + return "-"; + case "Period": + return "."; + case "Slash": + return "/"; + case "Backquote": + return "`"; + case "BracketLeft": + return "["; + case "Backslash": + return "\\"; + case "BracketRight": + return "]"; + case "Quote": + return '"'; + default: + throw new Error(`Unknown key: "${keyName}"`); + } +}; +let RawKeyboardImpl$2 = class RawKeyboardImpl2 { + constructor(session) { + this._session = session; + } + setSession(session) { + this._session = session; + } + async keydown(modifiers, keyName, description, autoRepeat) { + keyName = resolveSmartModifierString(keyName); + const actions = []; + actions.push({ type: "keyDown", value: getBidiKeyValue(keyName) }); + await this._performActions(actions); + } + async keyup(modifiers, keyName, description) { + keyName = resolveSmartModifierString(keyName); + const actions = []; + actions.push({ type: "keyUp", value: getBidiKeyValue(keyName) }); + await this._performActions(actions); + } + async sendText(text) { + const actions = []; + for (const char of text) { + const value = getBidiKeyValue(char); + actions.push({ type: "keyDown", value }); + actions.push({ type: "keyUp", value }); + } + await this._performActions(actions); + } + async _performActions(actions) { + await this._session.send("input.performActions", { + context: this._session.sessionId, + actions: [ + { + type: "key", + id: "pw_keyboard", + actions + } + ] + }); + } +}; +let RawMouseImpl$2 = class RawMouseImpl2 { + constructor(session) { + this._session = session; + } + async move(x, y, button, buttons, modifiers, forClick) { + await this._performActions([{ type: "pointerMove", x, y }]); + } + async down(x, y, button, buttons, modifiers, clickCount) { + await this._performActions([{ type: "pointerDown", button: toBidiButton(button) }]); + } + async up(x, y, button, buttons, modifiers, clickCount) { + await this._performActions([{ type: "pointerUp", button: toBidiButton(button) }]); + } + async wheel(x, y, buttons, modifiers, deltaX, deltaY) { + x = Math.floor(x); + y = Math.floor(y); + await this._session.send("input.performActions", { + context: this._session.sessionId, + actions: [ + { + type: "wheel", + id: "pw_mouse_wheel", + actions: [{ type: "scroll", x, y, deltaX, deltaY }] + } + ] + }); + } + async _performActions(actions) { + await this._session.send("input.performActions", { + context: this._session.sessionId, + actions: [ + { + type: "pointer", + id: "pw_mouse", + parameters: { + pointerType: Input.PointerType.Mouse + }, + actions + } + ] + }); + } +}; +let RawTouchscreenImpl$2 = class RawTouchscreenImpl2 { + constructor(session) { + this._session = session; + } + async tap(x, y, modifiers) { + } +}; +function toBidiButton(button) { + switch (button) { + case "left": + return 0; + case "right": + return 2; + case "middle": + return 1; + } + throw new Error("Unknown button: " + button); +} +const PagePaperFormats = { + letter: { width: 8.5, height: 11 }, + legal: { width: 8.5, height: 14 }, + tabloid: { width: 11, height: 17 }, + ledger: { width: 17, height: 11 }, + a0: { width: 33.1, height: 46.8 }, + a1: { width: 23.4, height: 33.1 }, + a2: { width: 16.54, height: 23.4 }, + a3: { width: 11.7, height: 16.54 }, + a4: { width: 8.27, height: 11.7 }, + a5: { width: 5.83, height: 8.27 }, + a6: { width: 4.13, height: 5.83 } +}; +const unitToPixels = { + "px": 1, + "in": 96, + "cm": 37.8, + "mm": 3.78 +}; +function convertPrintParameterToInches(text) { + if (text === void 0) + return void 0; + let unit = text.substring(text.length - 2).toLowerCase(); + let valueText = ""; + if (unitToPixels.hasOwnProperty(unit)) { + valueText = text.substring(0, text.length - 2); + } else { + unit = "px"; + valueText = text; + } + const value = Number(valueText); + assert(!isNaN(value), "Failed to parse parameter value: " + text); + const pixels = value * unitToPixels[unit]; + return pixels / 96; +} +class BidiPDF { + constructor(session) { + this._session = session; + } + async generate(options2) { + const { + scale = 1, + printBackground = false, + landscape = false, + pageRanges = "", + margin = {} + } = options2; + let paperWidth = 8.5; + let paperHeight = 11; + if (options2.format) { + const format = PagePaperFormats[options2.format.toLowerCase()]; + assert(format, "Unknown paper format: " + options2.format); + paperWidth = format.width; + paperHeight = format.height; + } else { + paperWidth = convertPrintParameterToInches(options2.width) || paperWidth; + paperHeight = convertPrintParameterToInches(options2.height) || paperHeight; + } + const { data: data2 } = await this._session.send("browsingContext.print", { + context: this._session.sessionId, + background: printBackground, + margin: { + bottom: convertPrintParameterToInches(margin.bottom) || 0, + left: convertPrintParameterToInches(margin.left) || 0, + right: convertPrintParameterToInches(margin.right) || 0, + top: convertPrintParameterToInches(margin.top) || 0 + }, + orientation: landscape ? "landscape" : "portrait", + page: { + width: paperWidth, + height: paperHeight + }, + pageRanges: pageRanges ? pageRanges.split(",").map((r) => r.trim()) : void 0, + scale + }); + return Buffer.from(data2, "base64"); + } +} +const UTILITY_WORLD_NAME$2 = "__playwright_utility_world__"; +const kPlaywrightBindingChannel = "playwrightChannel"; +class BidiPage { + constructor(browserContext, bidiSession, opener) { + this._sessionListeners = []; + this._initScriptIds = /* @__PURE__ */ new Map(); + this._session = bidiSession; + this._opener = opener; + this.rawKeyboard = new RawKeyboardImpl$2(bidiSession); + this.rawMouse = new RawMouseImpl$2(bidiSession); + this.rawTouchscreen = new RawTouchscreenImpl$2(bidiSession); + this._realmToContext = /* @__PURE__ */ new Map(); + this._page = new Page$1(this, browserContext); + this._browserContext = browserContext; + this._networkManager = new BidiNetworkManager(this._session, this._page, this._onNavigationResponseStarted.bind(this)); + this._pdf = new BidiPDF(this._session); + this._page.on(Page$1.Events.FrameDetached, (frame) => this._removeContextsForFrame(frame, false)); + this._sessionListeners = [ + eventsHelper.addEventListener(bidiSession, "script.realmCreated", this._onRealmCreated.bind(this)), + eventsHelper.addEventListener(bidiSession, "script.message", this._onScriptMessage.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.contextDestroyed", this._onBrowsingContextDestroyed.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.navigationStarted", this._onNavigationStarted.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.navigationAborted", this._onNavigationAborted.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.navigationFailed", this._onNavigationFailed.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.fragmentNavigated", this._onFragmentNavigated.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.domContentLoaded", this._onDomContentLoaded.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.load", this._onLoad.bind(this)), + eventsHelper.addEventListener(bidiSession, "browsingContext.userPromptOpened", this._onUserPromptOpened.bind(this)), + eventsHelper.addEventListener(bidiSession, "log.entryAdded", this._onLogEntryAdded.bind(this)) + ]; + this._initialize().then( + () => { + var _a2; + return this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page); + }, + (error2) => { + var _a2; + return this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page, error2); + } + ); + } + async _initialize() { + this._onFrameAttached(this._session.sessionId, null); + await Promise.all([ + this.updateHttpCredentials(), + this.updateRequestInterception(), + // If the page is created by the Playwright client's call, some initialization + // may be pending. Wait for it to complete before reporting the page as new. + // + // TODO: ideally we'd wait only for the commands that created this page, but currently + // there is no way in Bidi to track which command created this page. + this._browserContext.waitForBlockingPageCreations() + ]); + } + didClose() { + this._session.dispose(); + eventsHelper.removeEventListeners(this._sessionListeners); + this._page._didClose(); + } + _onFrameAttached(frameId, parentFrameId) { + return this._page.frameManager.frameAttached(frameId, parentFrameId); + } + _removeContextsForFrame(frame, notifyFrame) { + for (const [contextId, context] of this._realmToContext) { + if (context.frame === frame) { + this._realmToContext.delete(contextId); + if (notifyFrame) + frame._contextDestroyed(context); + } + } + } + _onRealmCreated(realmInfo) { + if (this._realmToContext.has(realmInfo.realm)) + return; + if (realmInfo.type !== "window") + return; + const frame = this._page.frameManager.frame(realmInfo.context); + if (!frame) + return; + let worldName; + if (!realmInfo.sandbox) { + worldName = "main"; + this._touchUtilityWorld(realmInfo.context); + } else if (realmInfo.sandbox === UTILITY_WORLD_NAME$2) { + worldName = "utility"; + } else { + return; + } + const delegate = new BidiExecutionContext(this._session, realmInfo); + const context = new FrameExecutionContext(delegate, frame, worldName); + frame._contextCreated(worldName, context); + this._realmToContext.set(realmInfo.realm, context); + } + async _touchUtilityWorld(context) { + await this._session.sendMayFail("script.evaluate", { + expression: "1 + 1", + target: { + context, + sandbox: UTILITY_WORLD_NAME$2 + }, + serializationOptions: { + maxObjectDepth: 10, + maxDomDepth: 10 + }, + awaitPromise: true, + userActivation: true + }); + } + _onRealmDestroyed(params) { + const context = this._realmToContext.get(params.realm); + if (!context) + return false; + this._realmToContext.delete(params.realm); + context.frame._contextDestroyed(context); + return true; + } + // TODO: route the message directly to the browser + _onBrowsingContextDestroyed(params) { + this._browserContext._browser._onBrowsingContextDestroyed(params); + } + _onNavigationStarted(params) { + const frameId = params.context; + this._page.frameManager.frameRequestedNavigation(frameId, params.navigation); + const url2 = params.url.toLowerCase(); + if (url2.startsWith("file:") || url2.startsWith("data:") || url2 === "about:blank") { + const frame = this._page.frameManager.frame(frameId); + if (frame) + this._page.frameManager.frameCommittedNewDocumentNavigation( + frameId, + params.url, + "", + params.navigation, + /* initial */ + false + ); + } + } + // TODO: there is no separate event for committed navigation, so we approximate it with responseStarted. + _onNavigationResponseStarted(params) { + const frameId = params.context; + const frame = this._page.frameManager.frame(frameId); + assert(frame); + this._page.frameManager.frameCommittedNewDocumentNavigation( + frameId, + params.response.url, + "", + params.navigation, + /* initial */ + false + ); + } + _onDomContentLoaded(params) { + const frameId = params.context; + this._page.frameManager.frameLifecycleEvent(frameId, "domcontentloaded"); + } + _onLoad(params) { + this._page.frameManager.frameLifecycleEvent(params.context, "load"); + } + _onNavigationAborted(params) { + this._page.frameManager.frameAbortedNavigation(params.context, "Navigation aborted", params.navigation || void 0); + } + _onNavigationFailed(params) { + this._page.frameManager.frameAbortedNavigation(params.context, "Navigation failed", params.navigation || void 0); + } + _onFragmentNavigated(params) { + this._page.frameManager.frameCommittedSameDocumentNavigation(params.context, params.url); + } + _onUserPromptOpened(event) { + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog$1( + this._page, + event.type, + event.message, + async (accept, userText) => { + await this._session.send("browsingContext.handleUserPrompt", { context: event.context, accept, userText }); + }, + event.defaultValue + )); + } + _onLogEntryAdded(params) { + var _a2; + if (params.type !== "console") + return; + const entry = params; + const context = this._realmToContext.get(params.source.realm); + if (!context) + return; + const callFrame = (_a2 = params.stackTrace) == null ? void 0 : _a2.callFrames[0]; + const location2 = callFrame ?? { url: "", lineNumber: 1, columnNumber: 1 }; + this._page.addConsoleMessage(entry.method, entry.args.map((arg) => createHandle$2(context, arg)), location2, params.text || void 0); + } + async navigateFrame(frame, url2, referrer) { + const { navigation } = await this._session.send("browsingContext.navigate", { + context: frame._id, + url: url2 + }); + return { newDocumentId: navigation || void 0 }; + } + async updateExtraHTTPHeaders() { + } + async updateEmulateMedia() { + } + async updateUserAgent() { + } + async bringToFront() { + await this._session.send("browsingContext.activate", { + context: this._session.sessionId + }); + } + async updateEmulatedViewportSize() { + const options2 = this._browserContext._options; + const emulatedSize = this._page.emulatedSize(); + if (!emulatedSize) + return; + const viewportSize = emulatedSize.viewport; + await this._session.send("browsingContext.setViewport", { + context: this._session.sessionId, + viewport: { + width: viewportSize.width, + height: viewportSize.height + }, + devicePixelRatio: options2.deviceScaleFactor || 1 + }); + } + async updateRequestInterception() { + await this._networkManager.setRequestInterception(this._page.needsRequestInterception()); + } + async updateOffline() { + } + async updateHttpCredentials() { + await this._networkManager.setCredentials(this._browserContext._options.httpCredentials); + } + async updateFileChooserInterception() { + } + async reload() { + await this._session.send("browsingContext.reload", { + context: this._session.sessionId, + // ignoreCache: true, + wait: BrowsingContext.ReadinessState.Interactive + }); + } + async goBack() { + return await this._session.send("browsingContext.traverseHistory", { + context: this._session.sessionId, + delta: -1 + }).then(() => true).catch(() => false); + } + async goForward() { + return await this._session.send("browsingContext.traverseHistory", { + context: this._session.sessionId, + delta: 1 + }).then(() => true).catch(() => false); + } + async requestGC() { + throw new Error("Method not implemented."); + } + async _onScriptMessage(event) { + if (event.channel !== kPlaywrightBindingChannel) + return; + const pageOrError = await this._page.waitForInitializedOrError(); + if (pageOrError instanceof Error) + return; + const context = this._realmToContext.get(event.source.realm); + if (!context) + return; + if (event.data.type !== "string") + return; + await this._page.onBindingCalled(event.data.value, context); + } + async addInitScript(initScript) { + const { script } = await this._session.send("script.addPreloadScript", { + // TODO: remove function call from the source. + functionDeclaration: `() => { return ${initScript.source} }`, + // TODO: push to iframes? + contexts: [this._session.sessionId] + }); + this._initScriptIds.set(initScript, script); + } + async removeInitScripts(initScripts) { + const ids = []; + for (const script of initScripts) { + const id = this._initScriptIds.get(script); + if (id) + ids.push(id); + this._initScriptIds.delete(script); + } + await Promise.all(ids.map((script) => this._session.send("script.removePreloadScript", { script }))); + } + async closePage(runBeforeUnload) { + await this._session.send("browsingContext.close", { + context: this._session.sessionId, + promptUnload: runBeforeUnload + }); + } + async setBackgroundColor(color) { + } + async takeScreenshot(progress2, format, documentRect, viewportRect, quality, fitsViewport, scale) { + const rect = documentRect || viewportRect; + const { data: data2 } = await this._session.send("browsingContext.captureScreenshot", { + context: this._session.sessionId, + format: { + type: `image/${format === "png" ? "png" : "jpeg"}`, + quality: quality ? quality / 100 : 0.8 + }, + origin: documentRect ? "document" : "viewport", + clip: { + type: "box", + ...rect + } + }); + return Buffer.from(data2, "base64"); + } + async getContentFrame(handle) { + const executionContext = toBidiExecutionContext(handle._context); + const frameId = await executionContext.contentFrameIdForFrame(handle); + if (!frameId) + return null; + return this._page.frameManager.frame(frameId); + } + async getOwnerFrame(handle) { + const windowHandle = await handle.evaluateHandle((node2) => { + const doc = node2.ownerDocument ?? node2; + return doc.defaultView; + }); + if (!windowHandle) + return null; + const executionContext = toBidiExecutionContext(handle._context); + return executionContext.frameIdForWindowHandle(windowHandle); + } + async getBoundingBox(handle) { + const box = await handle.evaluate((element) => { + if (!(element instanceof Element)) + return null; + const rect = element.getBoundingClientRect(); + return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; + }); + if (!box) + return null; + const position = await this._framePosition(handle._frame); + if (!position) + return null; + box.x += position.x; + box.y += position.y; + return box; + } + // TODO: move to Frame. + async _framePosition(frame) { + if (frame === this._page.mainFrame()) + return { x: 0, y: 0 }; + const element = await frame.frameElement(); + const box = await element.boundingBox(); + if (!box) + return null; + const style = await element.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch((e) => "error:notconnected"); + if (style === "error:notconnected" || style === "transformed") + return null; + box.x += style.left; + box.y += style.top; + return box; + } + async scrollRectIntoViewIfNeeded(handle, rect) { + return await handle.evaluateInUtility(([injected, node2]) => { + node2.scrollIntoView({ + block: "center", + inline: "center", + behavior: "instant" + }); + }, null).then(() => "done").catch((e) => { + if (e instanceof Error && e.message.includes("Node is detached from document")) + return "error:notconnected"; + if (e instanceof Error && e.message.includes("Node does not have a layout object")) + return "error:notvisible"; + throw e; + }); + } + async setScreencastOptions(options2) { + } + rafCountForStablePosition() { + return 1; + } + async getContentQuads(handle) { + const quads = await handle.evaluateInUtility(([injected, node2]) => { + if (!node2.isConnected) + return "error:notconnected"; + const rects = node2.getClientRects(); + if (!rects) + return null; + return [...rects].map((rect) => [ + { x: rect.left, y: rect.top }, + { x: rect.right, y: rect.top }, + { x: rect.right, y: rect.bottom }, + { x: rect.left, y: rect.bottom } + ]); + }, null); + if (!quads || quads === "error:notconnected") + return quads; + const position = await this._framePosition(handle._frame); + if (!position) + return null; + quads.forEach((quad) => quad.forEach((point) => { + point.x += position.x; + point.y += position.y; + })); + return quads; + } + async setInputFilePaths(handle, paths) { + const fromContext = toBidiExecutionContext(handle._context); + await this._session.send("input.setFiles", { + context: this._session.sessionId, + element: await fromContext.nodeIdForElementHandle(handle), + files: paths + }); + } + async adoptElementHandle(handle, to) { + const fromContext = toBidiExecutionContext(handle._context); + const nodeId = await fromContext.nodeIdForElementHandle(handle); + const executionContext = toBidiExecutionContext(to); + return await executionContext.remoteObjectForNodeId(to, nodeId); + } + async getAccessibilityTree(needle) { + throw new Error("Method not implemented."); + } + async inputActionEpilogue() { + } + async resetForReuse() { + } + async pdf(options2) { + return this._pdf.generate(options2); + } + async getFrameElement(frame) { + const parent = frame.parentFrame(); + if (!parent) + throw new Error("Frame has been detached."); + const parentContext = await parent._mainContext(); + const list = await parentContext.evaluateHandle(() => { + return [...document.querySelectorAll("iframe,frame")]; + }); + const length = await list.evaluate((list2) => list2.length); + let foundElement = null; + for (let i = 0; i < length; i++) { + const element = await list.evaluateHandle((list2, i2) => list2[i2], i); + const candidate = await element.contentFrame(); + if (frame === candidate) { + foundElement = element; + break; + } else { + element.dispose(); + } + } + list.dispose(); + if (!foundElement) + throw new Error("Frame has been detached."); + return foundElement; + } + shouldToggleStyleSheetToSyncAnimations() { + return true; + } +} +function toBidiExecutionContext(executionContext) { + return executionContext.delegate; +} +class BidiBrowser extends Browser$1 { + constructor(parent, transport, options2) { + super(parent, options2); + this._contexts = /* @__PURE__ */ new Map(); + this._bidiPages = /* @__PURE__ */ new Map(); + this._connection = new BidiConnection(transport, this._onDisconnect.bind(this), options2.protocolLogger, options2.browserLogsCollector); + this._browserSession = this._connection.browserSession; + this._eventListeners = [ + eventsHelper.addEventListener(this._browserSession, "browsingContext.contextCreated", this._onBrowsingContextCreated.bind(this)), + eventsHelper.addEventListener(this._browserSession, "script.realmDestroyed", this._onScriptRealmDestroyed.bind(this)) + ]; + } + static async connect(parent, transport, options2) { + const browser2 = new BidiBrowser(parent, transport, options2); + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + let proxy; + if (options2.proxy) { + proxy = { + proxyType: "manual" + }; + const url2 = new URL(options2.proxy.server); + switch (url2.protocol) { + case "http:": + proxy.httpProxy = url2.host; + break; + case "https:": + proxy.httpsProxy = url2.host; + break; + case "socks4:": + proxy.socksProxy = url2.host; + proxy.socksVersion = 4; + break; + case "socks5:": + proxy.socksProxy = url2.host; + proxy.socksVersion = 5; + break; + default: + throw new Error("Invalid proxy server protocol: " + options2.proxy.server); + } + if (options2.proxy.bypass) + proxy.noProxy = options2.proxy.bypass.split(","); + } + browser2._bidiSessionInfo = await browser2._browserSession.send("session.new", { + capabilities: { + alwaysMatch: { + acceptInsecureCerts: false, + proxy, + unhandledPromptBehavior: { + default: Session.UserPromptHandlerType.Ignore + }, + webSocketUrl: true + } + } + }); + await browser2._browserSession.send("session.subscribe", { + events: [ + "browsingContext", + "network", + "log", + "script" + ] + }); + if (options2.persistent) { + const context = new BidiBrowserContext(browser2, void 0, options2.persistent); + browser2._defaultContext = context; + await context._initialize(); + const page = await browser2._defaultContext.doCreateNewPage(); + await page.waitForInitializedOrError(); + } + return browser2; + } + _onDisconnect() { + this._didClose(); + } + async doCreateNewContext(options2) { + const { userContext } = await this._browserSession.send("browser.createUserContext", { + acceptInsecureCerts: options2.ignoreHTTPSErrors + }); + const context = new BidiBrowserContext(this, userContext, options2); + await context._initialize(); + this._contexts.set(userContext, context); + return context; + } + contexts() { + return Array.from(this._contexts.values()); + } + version() { + return this._bidiSessionInfo.capabilities.browserVersion; + } + userAgent() { + return this._bidiSessionInfo.capabilities.userAgent; + } + isConnected() { + return !this._connection.isClosed(); + } + _onBrowsingContextCreated(event) { + if (event.parent) { + const parentFrameId = event.parent; + for (const page2 of this._bidiPages.values()) { + const parentFrame = page2._page.frameManager.frame(parentFrameId); + if (!parentFrame) + continue; + page2._session.addFrameBrowsingContext(event.context); + page2._page.frameManager.frameAttached(event.context, parentFrameId); + const frame = page2._page.frameManager.frame(event.context); + if (frame) + frame._url = event.url; + return; + } + return; + } + let context = this._contexts.get(event.userContext); + if (!context) + context = this._defaultContext; + if (!context) + return; + const session = this._connection.createMainFrameBrowsingContextSession(event.context); + const opener = event.originalOpener && this._bidiPages.get(event.originalOpener); + const page = new BidiPage(context, session, opener || null); + page._page.mainFrame()._url = event.url; + this._bidiPages.set(event.context, page); + } + _onBrowsingContextDestroyed(event) { + if (event.parent) { + this._browserSession.removeFrameBrowsingContext(event.context); + const parentFrameId = event.parent; + for (const page of this._bidiPages.values()) { + const parentFrame = page._page.frameManager.frame(parentFrameId); + if (!parentFrame) + continue; + page._page.frameManager.frameDetached(event.context); + return; + } + return; + } + const bidiPage = this._bidiPages.get(event.context); + if (!bidiPage) + return; + bidiPage.didClose(); + this._bidiPages.delete(event.context); + } + _onScriptRealmDestroyed(event) { + for (const page of this._bidiPages.values()) { + if (page._onRealmDestroyed(event)) + return; + } + } +} +class BidiBrowserContext extends BrowserContext$1 { + constructor(browser2, browserContextId, options2) { + super(browser2, options2, browserContextId); + this._originToPermissions = /* @__PURE__ */ new Map(); + this._blockingPageCreations = /* @__PURE__ */ new Set(); + this._initScriptIds = /* @__PURE__ */ new Map(); + this._authenticateProxyViaHeader(); + } + _bidiPages() { + return [...this._browser._bidiPages.values()].filter((bidiPage) => bidiPage._browserContext === this); + } + async _initialize() { + const promises2 = [ + super._initialize() + ]; + if (this._options.viewport) { + promises2.push(this._browser._browserSession.send("browsingContext.setViewport", { + viewport: { + width: this._options.viewport.width, + height: this._options.viewport.height + }, + devicePixelRatio: this._options.deviceScaleFactor || 1, + userContexts: [this._userContextId()] + })); + } + if (this._options.geolocation) + promises2.push(this.setGeolocation(this._options.geolocation)); + await Promise.all(promises2); + } + possiblyUninitializedPages() { + return this._bidiPages().map((bidiPage) => bidiPage._page); + } + async doCreateNewPage(markAsServerSideOnly) { + const promise = this._createNewPageImpl(markAsServerSideOnly); + if (markAsServerSideOnly) + this._blockingPageCreations.add(promise); + try { + return await promise; + } finally { + this._blockingPageCreations.delete(promise); + } + } + async _createNewPageImpl(markAsServerSideOnly) { + const { context } = await this._browser._browserSession.send("browsingContext.create", { + type: BrowsingContext.CreateType.Window, + userContext: this._browserContextId + }); + const page = this._browser._bidiPages.get(context)._page; + if (markAsServerSideOnly) + page.markAsServerSideOnly(); + return page; + } + async waitForBlockingPageCreations() { + await Promise.all([...this._blockingPageCreations].map((command2) => command2.catch(() => { + }))); + } + async doGetCookies(urls) { + const { cookies } = await this._browser._browserSession.send( + "storage.getCookies", + { partition: { type: "storageKey", userContext: this._browserContextId } } + ); + return filterCookies(cookies.map((c) => { + const copy = { + name: c.name, + value: bidiBytesValueToString(c.value), + domain: c.domain, + path: c.path, + httpOnly: c.httpOnly, + secure: c.secure, + expires: c.expiry ?? -1, + sameSite: c.sameSite ? fromBidiSameSite(c.sameSite) : "None" + }; + return copy; + }), urls); + } + async addCookies(cookies) { + cookies = rewriteCookies(cookies); + const promises2 = cookies.map((c) => { + const cookie = { + name: c.name, + value: { type: "string", value: c.value }, + domain: c.domain, + path: c.path, + httpOnly: c.httpOnly, + secure: c.secure, + sameSite: c.sameSite && toBidiSameSite(c.sameSite), + expiry: c.expires === -1 || c.expires === void 0 ? void 0 : Math.round(c.expires) + }; + return this._browser._browserSession.send( + "storage.setCookie", + { cookie, partition: { type: "storageKey", userContext: this._browserContextId } } + ); + }); + await Promise.all(promises2); + } + async doClearCookies() { + await this._browser._browserSession.send( + "storage.deleteCookies", + { partition: { type: "storageKey", userContext: this._browserContextId } } + ); + } + async doGrantPermissions(origin, permissions) { + const currentPermissions = this._originToPermissions.get(origin) || []; + const toGrant = permissions.filter((permission) => !currentPermissions.includes(permission)); + this._originToPermissions.set(origin, [...currentPermissions, ...toGrant]); + await Promise.all(toGrant.map((permission) => this._setPermission(origin, permission, Permissions.PermissionState.Granted))); + } + async doClearPermissions() { + const currentPermissions = [...this._originToPermissions.entries()]; + this._originToPermissions = /* @__PURE__ */ new Map(); + await Promise.all(currentPermissions.map(([origin, permissions]) => permissions.map( + (p) => this._setPermission(origin, p, Permissions.PermissionState.Prompt) + ))); + } + async _setPermission(origin, permission, state2) { + await this._browser._browserSession.send("permissions.setPermission", { + descriptor: { + name: permission + }, + state: state2, + origin, + userContext: this._browserContextId || "default" + }); + } + async setGeolocation(geolocation) { + verifyGeolocation(geolocation); + this._options.geolocation = geolocation; + await this._browser._browserSession.send("emulation.setGeolocationOverride", { + coordinates: geolocation ? { + latitude: geolocation.latitude, + longitude: geolocation.longitude, + accuracy: geolocation.accuracy + } : null, + userContexts: [this._browserContextId || "default"] + }); + } + async setExtraHTTPHeaders(headers) { + } + async setUserAgent(userAgent) { + } + async setOffline(offline) { + } + async doSetHTTPCredentials(httpCredentials) { + this._options.httpCredentials = httpCredentials; + for (const page of this.pages()) + await page.delegate.updateHttpCredentials(); + } + async doAddInitScript(initScript) { + const { script } = await this._browser._browserSession.send("script.addPreloadScript", { + // TODO: remove function call from the source. + functionDeclaration: `() => { return ${initScript.source} }`, + userContexts: [this._browserContextId || "default"] + }); + this._initScriptIds.set(initScript, script); + } + async doRemoveInitScripts(initScripts) { + const ids = []; + for (const script of initScripts) { + const id = this._initScriptIds.get(script); + if (id) + ids.push(id); + this._initScriptIds.delete(script); + } + await Promise.all(ids.map((script) => this._browser._browserSession.send("script.removePreloadScript", { script }))); + } + async doUpdateRequestInterception() { + } + async doExposePlaywrightBinding() { + const args = [{ + type: "channel", + value: { + channel: kPlaywrightBindingChannel, + ownership: Script.ResultOwnership.Root + } + }]; + const functionDeclaration = `function addMainBinding(callback) { globalThis['${PageBinding.kBindingName}'] = callback; }`; + const promises2 = []; + promises2.push(this._browser._browserSession.send("script.addPreloadScript", { + functionDeclaration, + arguments: args, + userContexts: [this._userContextId()] + })); + promises2.push(...this._bidiPages().map((page) => { + const realms = [...page._realmToContext].filter(([realm, context]) => context.world === "main").map(([realm, context]) => realm); + return Promise.all(realms.map((realm) => { + return page._session.send("script.callFunction", { + functionDeclaration, + arguments: args, + target: { realm }, + awaitPromise: false, + userActivation: false + }); + })); + })); + await Promise.all(promises2); + } + onClosePersistent() { + } + async clearCache() { + } + async doClose(reason) { + if (!this._browserContextId) { + await this._browser.close({ reason }); + return; + } + await this._browser._browserSession.send("browser.removeUserContext", { + userContext: this._browserContextId + }); + this._browser._contexts.delete(this._browserContextId); + } + async cancelDownload(uuid) { + } + _userContextId() { + if (this._browserContextId) + return this._browserContextId; + return "default"; + } +} +function fromBidiSameSite(sameSite) { + switch (sameSite) { + case "strict": + return "Strict"; + case "lax": + return "Lax"; + case "none": + return "None"; + } + return "None"; +} +function toBidiSameSite(sameSite) { + switch (sameSite) { + case "Strict": + return Network$1.SameSite.Strict; + case "Lax": + return Network$1.SameSite.Lax; + case "None": + return Network$1.SameSite.None; + } + return Network$1.SameSite.None; +} +var Network; +((Network2) => { + ((SameSite2) => { + SameSite2["Strict"] = "strict"; + SameSite2["Lax"] = "lax"; + SameSite2["None"] = "none"; + })(Network2.SameSite || (Network2.SameSite = {})); +})(Network || (Network = {})); +class BidiChromium extends BrowserType$1 { + constructor(parent) { + super(parent, "bidi"); + } + async connectToTransport(transport, options2, browserLogsCollector) { + const bidiTransport = await require("./bidiOverCdp").connectBidiOverCdp(transport); + transport[kBidiOverCdpWrapper] = bidiTransport; + try { + return BidiBrowser.connect(this.attribution.playwright, bidiTransport, options2); + } catch (e) { + if (browserLogsCollector.recentLogs().some((log) => log.includes("Failed to create a ProcessSingleton for your profile directory."))) { + throw new Error( + "Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium." + ); + } + throw e; + } + } + doRewriteStartupLog(error2) { + if (!error2.logs) + return error2; + if (error2.logs.includes("Missing X server")) + error2.logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + if (!error2.logs.includes("crbug.com/357670") && !error2.logs.includes("No usable sandbox!") && !error2.logs.includes("crbug.com/638180")) + return error2; + error2.logs = [ + `Chromium sandboxing failed!`, + `================================`, + `To avoid the sandboxing issue, do either of the following:`, + ` - (preferred): Configure your environment to support sandboxing`, + ` - (alternative): Launch Chromium without sandbox using 'chromiumSandbox: false' option`, + `================================`, + `` + ].join("\n"); + return error2; + } + amendEnvironment(env, userDataDir, executable, browserArguments) { + return env; + } + attemptToGracefullyCloseBrowser(transport) { + const bidiTransport = transport[kBidiOverCdpWrapper]; + if (bidiTransport) + transport = bidiTransport; + transport.send({ method: "browser.close", params: {}, id: kBrowserCloseMessageId$2 }); + } + supportsPipeTransport() { + return false; + } + defaultArgs(options2, isPersistent, userDataDir) { + const chromeArguments = this._innerDefaultArgs(options2); + chromeArguments.push(`--user-data-dir=${userDataDir}`); + chromeArguments.push("--remote-debugging-port=0"); + if (isPersistent) + chromeArguments.push("about:blank"); + else + chromeArguments.push("--no-startup-window"); + return chromeArguments; + } + readyState(options2) { + return new ChromiumReadyState$1(); + } + _innerDefaultArgs(options2) { + const { args = [] } = options2; + const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir")); + if (userDataDirArg) + throw this._createUserDataDirArgMisuseError("--user-data-dir"); + if (args.find((arg) => arg.startsWith("--remote-debugging-pipe"))) + throw new Error("Playwright manages remote debugging connection itself."); + if (args.find((arg) => !arg.startsWith("-"))) + throw new Error("Arguments can not specify page to be opened"); + const chromeArguments = [...chromiumSwitches(options2.assistantMode)]; + if (os.platform() === "darwin") { + chromeArguments.push("--enable-use-zoom-for-dsf=false"); + if (options2.headless) + chromeArguments.push("--use-angle"); + } + if (options2.devtools) + chromeArguments.push("--auto-open-devtools-for-tabs"); + if (options2.headless) { + chromeArguments.push("--headless"); + chromeArguments.push( + "--hide-scrollbars", + "--mute-audio", + "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4" + ); + } + if (options2.chromiumSandbox !== true) + chromeArguments.push("--no-sandbox"); + const proxy = options2.proxyOverride || options2.proxy; + if (proxy) { + const proxyURL = new URL(proxy.server); + const isSocks = proxyURL.protocol === "socks5:"; + if (isSocks && !this.attribution.playwright.options.socksProxyPort) { + chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`); + } + chromeArguments.push(`--proxy-server=${proxy.server}`); + const proxyBypassRules = []; + if (this.attribution.playwright.options.socksProxyPort) + proxyBypassRules.push("<-loopback>"); + if (proxy.bypass) + proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t)); + if (!define_process_env_default.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>")) + proxyBypassRules.push("<-loopback>"); + if (proxyBypassRules.length > 0) + chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`); + } + chromeArguments.push(...args); + return chromeArguments; + } +} +let ChromiumReadyState$1 = class ChromiumReadyState extends BrowserReadyState { + onBrowserOutput(message) { + if (message.includes("Failed to create a ProcessSingleton for your profile directory.")) { + this._wsEndpoint.reject(new Error("Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium.")); + } + const match = message.match(/DevTools listening on (.*)/); + if (match) + this._wsEndpoint.resolve(match[1]); + } +}; +const kBidiOverCdpWrapper = Symbol("kBidiConnectionWrapper"); +/** + * @license + * Copyright 2023 Google Inc. + * SPDX-License-Identifier: Apache-2.0 + */ +async function createProfile(options2) { + if (!fs.existsSync(options2.path)) { + await fs.promises.mkdir(options2.path, { + recursive: true + }); + } + await writePreferences({ + preferences: { + ...defaultProfilePreferences(options2.preferences), + ...options2.preferences + }, + path: options2.path + }); +} +function defaultProfilePreferences(extraPrefs) { + const server = "dummy.test"; + const defaultPrefs = { + // Make sure Shield doesn't hit the network. + "app.normandy.api_url": "", + // Disable Firefox old build background check + "app.update.checkInstallTime": false, + // Disable automatically upgrading Firefox + "app.update.disabledForTesting": true, + // Increase the APZ content response timeout to 1 minute + "apz.content_response_timeout": 6e4, + // Prevent various error message on the console + // jest-puppeteer asserts that no error message is emitted by the console + "browser.contentblocking.features.standard": "-tp,tpPrivate,cookieBehavior0,-cm,-fp", + // Enable the dump function: which sends messages to the system + // console + // https://bugzilla.mozilla.org/show_bug.cgi?id=1543115 + "browser.dom.window.dump.enabled": true, + // Make sure newtab weather doesn't hit the network to retrieve weather data. + "browser.newtabpage.activity-stream.discoverystream.region-weather-config": "", + // Make sure newtab wallpapers don't hit the network to retrieve wallpaper data. + "browser.newtabpage.activity-stream.newtabWallpapers.enabled": false, + "browser.newtabpage.activity-stream.newtabWallpapers.v2.enabled": false, + // Make sure Topsites doesn't hit the network to retrieve sponsored tiles. + "browser.newtabpage.activity-stream.showSponsoredTopSites": false, + // Disable topstories + "browser.newtabpage.activity-stream.feeds.system.topstories": false, + // Always display a blank page + "browser.newtabpage.enabled": false, + // Background thumbnails in particular cause grief: and disabling + // thumbnails in general cannot hurt + "browser.pagethumbnails.capturing_disabled": true, + // Disable safebrowsing components. + "browser.safebrowsing.blockedURIs.enabled": false, + "browser.safebrowsing.downloads.enabled": false, + "browser.safebrowsing.malware.enabled": false, + "browser.safebrowsing.phishing.enabled": false, + // Disable updates to search engines. + "browser.search.update": false, + // Do not restore the last open set of tabs if the browser has crashed + "browser.sessionstore.resume_from_crash": false, + // Skip check for default browser on startup + "browser.shell.checkDefaultBrowser": false, + // Disable newtabpage + "browser.startup.homepage": "about:blank", + // Do not redirect user when a milstone upgrade of Firefox is detected + "browser.startup.homepage_override.mstone": "ignore", + // Start with a blank page about:blank + "browser.startup.page": 0, + // Do not allow background tabs to be zombified on Android: otherwise for + // tests that open additional tabs: the test harness tab itself might get + // unloaded + "browser.tabs.disableBackgroundZombification": false, + // Do not warn when closing all other open tabs + "browser.tabs.warnOnCloseOtherTabs": false, + // Do not warn when multiple tabs will be opened + "browser.tabs.warnOnOpen": false, + // Do not automatically offer translations, as tests do not expect this. + "browser.translations.automaticallyPopup": false, + // Disable the UI tour. + "browser.uitour.enabled": false, + // Turn off search suggestions in the location bar so as not to trigger + // network connections. + "browser.urlbar.suggest.searches": false, + // Disable first run splash page on Windows 10 + "browser.usedOnWindows10.introURL": "", + // Do not warn on quitting Firefox + "browser.warnOnQuit": false, + // Defensively disable data reporting systems + "datareporting.healthreport.documentServerURI": `http://${server}/dummy/healthreport/`, + "datareporting.healthreport.logging.consoleEnabled": false, + "datareporting.healthreport.service.enabled": false, + "datareporting.healthreport.service.firstRun": false, + "datareporting.healthreport.uploadEnabled": false, + // Do not show datareporting policy notifications which can interfere with tests + "datareporting.policy.dataSubmissionEnabled": false, + "datareporting.policy.dataSubmissionPolicyBypassNotification": true, + // DevTools JSONViewer sometimes fails to load dependencies with its require.js. + // This doesn't affect Puppeteer but spams console (Bug 1424372) + "devtools.jsonview.enabled": false, + // Disable popup-blocker + "dom.disable_open_during_load": false, + // Enable the support for File object creation in the content process + // Required for |Page.setFileInputFiles| protocol method. + "dom.file.createInChild": true, + // Disable the ProcessHangMonitor + "dom.ipc.reportProcessHangs": false, + // Disable slow script dialogues + "dom.max_chrome_script_run_time": 0, + "dom.max_script_run_time": 0, + // Disable background timer throttling to allow tests to run in parallel + // without a decrease in performance. + "dom.min_background_timeout_value": 0, + "dom.min_background_timeout_value_without_budget_throttling": 0, + "dom.timeout.enable_budget_timer_throttling": false, + // Disable HTTPS-First upgrades + "dom.security.https_first": false, + // Only load extensions from the application and user profile + // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION + "extensions.autoDisableScopes": 0, + "extensions.enabledScopes": 5, + // Disable metadata caching for installed add-ons by default + "extensions.getAddons.cache.enabled": false, + // Disable installing any distribution extensions or add-ons. + "extensions.installDistroAddons": false, + // Disabled screenshots extension + "extensions.screenshots.disabled": true, + // Turn off extension updates so they do not bother tests + "extensions.update.enabled": false, + // Turn off extension updates so they do not bother tests + "extensions.update.notifyUser": false, + // Make sure opening about:addons will not hit the network + "extensions.webservice.discoverURL": `http://${server}/dummy/discoveryURL`, + // Allow the application to have focus even it runs in the background + "focusmanager.testmode": true, + // Disable useragent updates + "general.useragent.updates.enabled": false, + // Always use network provider for geolocation tests so we bypass the + // macOS dialog raised by the corelocation provider + "geo.provider.testing": true, + // Do not scan Wifi + "geo.wifi.scan": false, + // No hang monitor + "hangmonitor.timeout": 0, + // Show chrome errors and warnings in the error console + "javascript.options.showInConsole": true, + // Do not throttle rendering (requestAnimationFrame) in background tabs + "layout.testing.top-level-always-active": true, + // Disable download and usage of OpenH264: and Widevine plugins + "media.gmp-manager.updateEnabled": false, + // Disable the GFX sanity window + "media.sanity-test.disabled": true, + // Disable connectivity service pings + "network.connectivity-service.enabled": false, + // Disable experimental feature that is only available in Nightly + "network.cookie.sameSite.laxByDefault": false, + // Do not prompt for temporary redirects + "network.http.prompt-temp-redirect": false, + // Disable speculative connections so they are not reported as leaking + // when they are hanging around + "network.http.speculative-parallel-limit": 0, + // Do not automatically switch between offline and online + "network.manage-offline-status": false, + // Make sure SNTP requests do not hit the network + "network.sntp.pools": server, + // Disable Flash. + "plugin.state.flash": 0, + "privacy.trackingprotection.enabled": false, + // Can be removed once Firefox 89 is no longer supported + // https://bugzilla.mozilla.org/show_bug.cgi?id=1710839 + "remote.enabled": true, + // Don't do network connections for mitm priming + "security.certerrors.mitm.priming.enabled": false, + // Local documents have access to all other local documents, + // including directory listings + "security.fileuri.strict_origin_policy": false, + // Do not wait for the notification button security delay + "security.notification_enable_delay": 0, + // Do not automatically fill sign-in forms with known usernames and + // passwords + "signon.autofillForms": false, + // Disable password capture, so that tests that include forms are not + // influenced by the presence of the persistent doorhanger notification + "signon.rememberSignons": false, + // Disable first-run welcome page + "startup.homepage_welcome_url": "about:blank", + // Disable first-run welcome page + "startup.homepage_welcome_url.additional": "", + // Disable browser animations (tabs, fullscreen, sliding alerts) + "toolkit.cosmeticAnimations.enabled": false, + // Prevent starting into safe mode after application crashes + "toolkit.startup.max_resumed_crashes": -1 + }; + return Object.assign(defaultPrefs, extraPrefs); +} +async function writePreferences(options2) { + const prefsPath = path.join(options2.path, "prefs.js"); + const lines = Object.entries(options2.preferences).map(([key2, value]) => { + return `user_pref(${JSON.stringify(key2)}, ${JSON.stringify(value)});`; + }); + const result = await Promise.allSettled([ + fs.promises.writeFile(path.join(options2.path, "user.js"), lines.join("\n")), + // Create a backup of the preferences file if it already exitsts. + fs.promises.access(prefsPath, fs.constants.F_OK).then( + async () => { + await fs.promises.copyFile( + prefsPath, + path.join(options2.path, "prefs.js.playwright") + ); + }, + // Swallow only if file does not exist + () => { + } + ) + ]); + for (const command2 of result) { + if (command2.status === "rejected") { + throw command2.reason; + } + } +} +class BidiFirefox extends BrowserType$1 { + constructor(parent) { + super(parent, "bidi"); + } + async connectToTransport(transport, options2) { + return BidiBrowser.connect(this.attribution.playwright, transport, options2); + } + doRewriteStartupLog(error2) { + if (!error2.logs) + return error2; + if (error2.logs.includes(`as root in a regular user's session is not supported.`)) + error2.logs = "\n" + wrapInASCIIBox(`Firefox is unable to launch if the $HOME folder isn't owned by the current user. +Workaround: Set the HOME=/root environment variable${define_process_env_default.GITHUB_ACTION ? " in your GitHub Actions workflow file" : ""} when running Playwright.`, 1); + if (error2.logs.includes("no DISPLAY environment variable specified")) + error2.logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + return error2; + } + amendEnvironment(env, userDataDir, executable, browserArguments) { + if (!path.isAbsolute(os.homedir())) + throw new Error(`Cannot launch Firefox with relative home directory. Did you set ${os.platform() === "win32" ? "USERPROFILE" : "HOME"} to a relative path?`); + env = { + ...env, + "MOZ_CRASHREPORTER": "1", + "MOZ_CRASHREPORTER_NO_REPORT": "1", + "MOZ_CRASHREPORTER_SHUTDOWN": "1" + }; + if (os.platform() === "linux") { + return { ...env, SNAP_NAME: void 0, SNAP_INSTANCE_NAME: void 0 }; + } + return env; + } + attemptToGracefullyCloseBrowser(transport) { + transport.send({ method: "browser.close", params: {}, id: kBrowserCloseMessageId$2 }); + } + supportsPipeTransport() { + return false; + } + async prepareUserDataDir(options2, userDataDir) { + await createProfile({ + path: userDataDir, + preferences: options2.firefoxUserPrefs || {} + }); + } + defaultArgs(options2, isPersistent, userDataDir) { + const { args = [], headless } = options2; + const userDataDirArg = args.find((arg) => arg.startsWith("-profile") || arg.startsWith("--profile")); + if (userDataDirArg) + throw this._createUserDataDirArgMisuseError("--profile"); + const firefoxArguments = ["--remote-debugging-port=0"]; + if (headless) + firefoxArguments.push("--headless"); + else + firefoxArguments.push("--foreground"); + firefoxArguments.push(`--profile`, userDataDir); + firefoxArguments.push(...args); + return firefoxArguments; + } + readyState(options2) { + return new FirefoxReadyState(); + } +} +class FirefoxReadyState extends BrowserReadyState { + onBrowserOutput(message) { + const match = message.match(/WebDriver BiDi listening on (ws:\/\/.*)$/); + if (match) + this._wsEndpoint.resolve(match[1] + "/session"); + } +} +const kBindingName = "__pw_devtools__"; +class CRDevTools { + constructor(preferencesPath) { + this._preferencesPath = preferencesPath; + this._savePromise = Promise.resolve(); + } + install(session) { + session.on("Runtime.bindingCalled", async (event) => { + if (event.name !== kBindingName) + return; + const parsed = JSON.parse(event.payload); + let result = void 0; + if (this.__testHookOnBinding) + this.__testHookOnBinding(parsed); + if (parsed.method === "getPreferences") { + if (this._prefs === void 0) { + try { + const json = await fs.promises.readFile(this._preferencesPath, "utf8"); + this._prefs = JSON.parse(json); + } catch (e) { + this._prefs = {}; + } + } + result = this._prefs; + } else if (parsed.method === "setPreference") { + this._prefs[parsed.params[0]] = parsed.params[1]; + this._save(); + } else if (parsed.method === "removePreference") { + delete this._prefs[parsed.params[0]]; + this._save(); + } else if (parsed.method === "clearPreferences") { + this._prefs = {}; + this._save(); + } + session.send("Runtime.evaluate", { + expression: `window.DevToolsAPI.embedderMessageAck(${parsed.id}, ${JSON.stringify(result)})`, + contextId: event.executionContextId + }).catch((e) => null); + }); + Promise.all([ + session.send("Runtime.enable"), + session.send("Runtime.addBinding", { name: kBindingName }), + session.send("Page.enable"), + session.send("Page.addScriptToEvaluateOnNewDocument", { source: ` + (() => { + const init = () => { + // Lazy init happens when InspectorFrontendHost is initialized. + // At this point DevToolsHost is ready to be used. + const host = window.DevToolsHost; + const old = host.sendMessageToEmbedder.bind(host); + host.sendMessageToEmbedder = message => { + if (['getPreferences', 'setPreference', 'removePreference', 'clearPreferences'].includes(JSON.parse(message).method)) + window.${kBindingName}(message); + else + old(message); + }; + }; + let value; + Object.defineProperty(window, 'InspectorFrontendHost', { + configurable: true, + enumerable: true, + get() { return value; }, + set(v) { value = v; init(); }, + }); + })() + ` }), + session.send("Runtime.runIfWaitingForDebugger") + ]).catch((e) => null); + } + _save() { + this._savePromise = this._savePromise.then(async () => { + await fs.promises.writeFile(this._preferencesPath, JSON.stringify(this._prefs)).catch((e) => null); + }); + } +} +const ARTIFACTS_FOLDER = path.join(os.tmpdir(), "playwright-artifacts-"); +class Chromium extends BrowserType$1 { + constructor(parent) { + super(parent, "chromium"); + if (debugMode()) + this._devtools = this._createDevTools(); + } + async connectOverCDP(metadata, endpointURL, options2) { + const controller = new ProgressController(metadata, this); + controller.setLogName("browser"); + return controller.run(async (progress2) => { + return await this._connectOverCDPInternal(progress2, endpointURL, options2); + }, options2.timeout); + } + async _connectOverCDPInternal(progress2, endpointURL, options2, onClose) { + let headersMap; + if (options2.headers) + headersMap = headersArrayToObject(options2.headers, false); + if (!headersMap) + headersMap = { "User-Agent": getUserAgent() }; + else if (headersMap && !Object.keys(headersMap).some((key2) => key2.toLowerCase() === "user-agent")) + headersMap["User-Agent"] = getUserAgent(); + const artifactsDir = await fs.promises.mkdtemp(ARTIFACTS_FOLDER); + const wsEndpoint = await urlToWSEndpoint(progress2, endpointURL, headersMap); + progress2.throwIfAborted(); + const chromeTransport = await WebSocketTransport$1.connect(progress2, wsEndpoint, { headers: headersMap }); + const cleanedUp = new ManualPromise(); + const doCleanup = async () => { + await removeFolders([artifactsDir]); + await (onClose == null ? void 0 : onClose()); + cleanedUp.resolve(); + }; + const doClose = async () => { + await chromeTransport.closeAndWait(); + await cleanedUp; + }; + const browserProcess = { close: doClose, kill: doClose }; + const persistent = { noDefaultViewport: true }; + const browserOptions = { + slowMo: options2.slowMo, + name: "chromium", + isChromium: true, + persistent, + browserProcess, + protocolLogger: helper.debugProtocolLogger(), + browserLogsCollector: new RecentLogsCollector(), + artifactsDir, + downloadsPath: options2.downloadsPath || artifactsDir, + tracesDir: options2.tracesDir || artifactsDir, + originalLaunchOptions: { timeout: options2.timeout } + }; + validateBrowserContextOptions(persistent, browserOptions); + progress2.throwIfAborted(); + const browser2 = await CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions); + browser2._isCollocatedWithServer = false; + browser2.on(Browser$1.Events.Disconnected, doCleanup); + return browser2; + } + _createDevTools() { + const directory = registry.findExecutable("chromium").directory; + return directory ? new CRDevTools(path.join(directory, "devtools-preferences.json")) : void 0; + } + async connectToTransport(transport, options2, browserLogsCollector) { + let devtools = this._devtools; + if (options2.__testHookForDevTools) { + devtools = this._createDevTools(); + await options2.__testHookForDevTools(devtools); + } + try { + return await CRBrowser.connect(this.attribution.playwright, transport, options2, devtools); + } catch (e) { + if (browserLogsCollector.recentLogs().some((log) => log.includes("Failed to create a ProcessSingleton for your profile directory."))) { + throw new Error( + "Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium." + ); + } + throw e; + } + } + doRewriteStartupLog(error2) { + if (!error2.logs) + return error2; + if (error2.logs.includes("Missing X server")) + error2.logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + if (!error2.logs.includes("crbug.com/357670") && !error2.logs.includes("No usable sandbox!") && !error2.logs.includes("crbug.com/638180")) + return error2; + error2.logs = [ + `Chromium sandboxing failed!`, + `================================`, + `To avoid the sandboxing issue, do either of the following:`, + ` - (preferred): Configure your environment to support sandboxing`, + ` - (alternative): Launch Chromium without sandbox using 'chromiumSandbox: false' option`, + `================================`, + `` + ].join("\n"); + return error2; + } + amendEnvironment(env, userDataDir, executable, browserArguments) { + return env; + } + attemptToGracefullyCloseBrowser(transport) { + const message = { method: "Browser.close", id: kBrowserCloseMessageId$3, params: {} }; + transport.send(message); + } + async _launchWithSeleniumHub(progress2, hubUrl, options2) { + await this._createArtifactDirs(options2); + if (!hubUrl.endsWith("/")) + hubUrl = hubUrl + "/"; + const args = this._innerDefaultArgs(options2); + args.push("--remote-debugging-port=0"); + const isEdge = options2.channel && options2.channel.startsWith("msedge"); + let desiredCapabilities = { + "browserName": isEdge ? "MicrosoftEdge" : "chrome", + [isEdge ? "ms:edgeOptions" : "goog:chromeOptions"]: { args } + }; + if (define_process_env_default.SELENIUM_REMOTE_CAPABILITIES) { + const remoteCapabilities = parseSeleniumRemoteParams({ name: "capabilities", value: define_process_env_default.SELENIUM_REMOTE_CAPABILITIES }, progress2); + if (remoteCapabilities) + desiredCapabilities = { ...desiredCapabilities, ...remoteCapabilities }; + } + let headers = {}; + if (define_process_env_default.SELENIUM_REMOTE_HEADERS) { + const remoteHeaders = parseSeleniumRemoteParams({ name: "headers", value: define_process_env_default.SELENIUM_REMOTE_HEADERS }, progress2); + if (remoteHeaders) + headers = remoteHeaders; + } + progress2.log(` connecting to ${hubUrl}`); + const response2 = await fetchData({ + url: hubUrl + "session", + method: "POST", + headers: { + "Content-Type": "application/json; charset=utf-8", + ...headers + }, + data: JSON.stringify({ + capabilities: { alwaysMatch: desiredCapabilities } + }), + timeout: progress2.timeUntilDeadline() + }, seleniumErrorHandler); + const value = JSON.parse(response2).value; + const sessionId = value.sessionId; + progress2.log(` connected to sessionId=${sessionId}`); + const disconnectFromSelenium = async () => { + progress2.log(` disconnecting from sessionId=${sessionId}`); + await fetchData({ + url: hubUrl + "session/" + sessionId, + method: "DELETE", + headers + }).catch((error2) => progress2.log(`: ${error2}`)); + progress2.log(` disconnected from sessionId=${sessionId}`); + gracefullyCloseSet.delete(disconnectFromSelenium); + }; + gracefullyCloseSet.add(disconnectFromSelenium); + try { + const capabilities = value.capabilities; + let endpointURL; + if (capabilities["se:cdp"]) { + progress2.log(` using selenium v4`); + const endpointURLString = addProtocol(capabilities["se:cdp"]); + endpointURL = new URL(endpointURLString); + if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1") + endpointURL.hostname = new URL(hubUrl).hostname; + progress2.log(` retrieved endpoint ${endpointURL.toString()} for sessionId=${sessionId}`); + } else { + progress2.log(` using selenium v3`); + const maybeChromeOptions = capabilities["goog:chromeOptions"]; + const chromeOptions = maybeChromeOptions && typeof maybeChromeOptions === "object" ? maybeChromeOptions : void 0; + const debuggerAddress = chromeOptions && typeof chromeOptions.debuggerAddress === "string" ? chromeOptions.debuggerAddress : void 0; + const chromeOptionsURL = typeof maybeChromeOptions === "string" ? maybeChromeOptions : void 0; + const endpointURLString = addProtocol(debuggerAddress || chromeOptionsURL).replace("localhost", "127.0.0.1"); + progress2.log(` retrieved endpoint ${endpointURLString} for sessionId=${sessionId}`); + endpointURL = new URL(endpointURLString); + if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1") { + const sessionInfoUrl = new URL(hubUrl).origin + "/grid/api/testsession?session=" + sessionId; + try { + const sessionResponse = await fetchData({ + url: sessionInfoUrl, + method: "GET", + timeout: progress2.timeUntilDeadline(), + headers + }, seleniumErrorHandler); + const proxyId = JSON.parse(sessionResponse).proxyId; + endpointURL.hostname = new URL(proxyId).hostname; + progress2.log(` resolved endpoint ip ${endpointURL.toString()} for sessionId=${sessionId}`); + } catch (e) { + progress2.log(` unable to resolve endpoint ip for sessionId=${sessionId}, running in standalone?`); + } + } + } + return await this._connectOverCDPInternal(progress2, endpointURL.toString(), { + ...options2, + headers: headersObjectToArray(headers) + }, disconnectFromSelenium); + } catch (e) { + await disconnectFromSelenium(); + throw e; + } + } + defaultArgs(options2, isPersistent, userDataDir) { + const chromeArguments = this._innerDefaultArgs(options2); + chromeArguments.push(`--user-data-dir=${userDataDir}`); + if (options2.cdpPort !== void 0) + chromeArguments.push(`--remote-debugging-port=${options2.cdpPort}`); + else + chromeArguments.push("--remote-debugging-pipe"); + if (isPersistent) + chromeArguments.push("about:blank"); + else + chromeArguments.push("--no-startup-window"); + return chromeArguments; + } + _innerDefaultArgs(options2) { + const { args = [] } = options2; + const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir")); + if (userDataDirArg) + throw this._createUserDataDirArgMisuseError("--user-data-dir"); + if (args.find((arg) => arg.startsWith("--remote-debugging-pipe"))) + throw new Error("Playwright manages remote debugging connection itself."); + if (args.find((arg) => !arg.startsWith("-"))) + throw new Error("Arguments can not specify page to be opened"); + const chromeArguments = [...chromiumSwitches(options2.assistantMode, options2.channel)]; + if (os.platform() === "darwin") { + chromeArguments.push("--enable-use-zoom-for-dsf=false"); + if (options2.headless && (!options2.channel || options2.channel === "chromium-headless-shell")) + chromeArguments.push("--use-angle"); + } + if (options2.devtools) + chromeArguments.push("--auto-open-devtools-for-tabs"); + if (options2.headless) { + chromeArguments.push("--headless"); + chromeArguments.push( + "--hide-scrollbars", + "--mute-audio", + "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4" + ); + } + if (options2.chromiumSandbox !== true) + chromeArguments.push("--no-sandbox"); + const proxy = options2.proxyOverride || options2.proxy; + if (proxy) { + const proxyURL = new URL(proxy.server); + const isSocks = proxyURL.protocol === "socks5:"; + if (isSocks && !this.attribution.playwright.options.socksProxyPort) { + chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`); + } + chromeArguments.push(`--proxy-server=${proxy.server}`); + const proxyBypassRules = []; + if (this.attribution.playwright.options.socksProxyPort) + proxyBypassRules.push("<-loopback>"); + if (proxy.bypass) + proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t)); + if (!define_process_env_default.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>")) + proxyBypassRules.push("<-loopback>"); + if (proxyBypassRules.length > 0) + chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`); + } + chromeArguments.push(...args); + return chromeArguments; + } + readyState(options2) { + var _a2; + if (options2.cdpPort !== void 0 || ((_a2 = options2.args) == null ? void 0 : _a2.some((a) => a.startsWith("--remote-debugging-port")))) + return new ChromiumReadyState2(); + return void 0; + } + getExecutableName(options2) { + if (options2.channel) + return options2.channel; + return options2.headless ? "chromium-headless-shell" : "chromium"; + } +} +class ChromiumReadyState2 extends BrowserReadyState { + onBrowserOutput(message) { + if (message.includes("Failed to create a ProcessSingleton for your profile directory.")) { + this._wsEndpoint.reject(new Error("Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium.")); + } + const match = message.match(/DevTools listening on (.*)/); + if (match) + this._wsEndpoint.resolve(match[1]); + } +} +async function urlToWSEndpoint(progress2, endpointURL, headers) { + if (endpointURL.startsWith("ws")) + return endpointURL; + progress2.log(` retrieving websocket url from ${endpointURL}`); + const url2 = new URL(endpointURL); + url2.pathname += "json/version/"; + const httpURL = url2.toString(); + const json = await fetchData( + { + url: httpURL, + headers + }, + async (_, resp) => new Error(`Unexpected status ${resp.statusCode} when connecting to ${httpURL}. +This does not look like a DevTools server, try connecting via ws://.`) + ); + return JSON.parse(json).webSocketDebuggerUrl; +} +async function seleniumErrorHandler(params, response2) { + const body = await streamToString(response2); + let message = body; + try { + const json = JSON.parse(body); + message = json.value.localizedMessage || json.value.message; + } catch (e) { + } + return new Error(`Error connecting to Selenium at ${params.url}: ${message}`); +} +function addProtocol(url2) { + if (!["ws://", "wss://", "http://", "https://"].some((protocol) => url2.startsWith(protocol))) + return "http://" + url2; + return url2; +} +function streamToString(stream2) { + return new Promise((resolve, reject) => { + const chunks = []; + stream2.on("data", (chunk) => chunks.push(Buffer.from(chunk))); + stream2.on("error", reject); + stream2.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + }); +} +function parseSeleniumRemoteParams(env, progress2) { + try { + const parsed = JSON.parse(env.value); + progress2.log(` using additional ${env.name} "${env.value}"`); + return parsed; + } catch (e) { + progress2.log(` ignoring additional ${env.name} "${env.value}": ${e}`); + } +} +const internalMetadata = serverSideCallMetadata(); +const _DebugController = class _DebugController2 extends SdkObject { + constructor(playwright2) { + super({ attribution: { isInternalPlaywright: true }, instrumentation: createInstrumentation$1() }, void 0, "DebugController"); + this._sdkLanguage = "javascript"; + this._codegenId = "playwright-test"; + this._playwright = playwright2; + } + initialize(codegenId, sdkLanguage) { + this._codegenId = codegenId; + this._sdkLanguage = sdkLanguage; + } + dispose() { + this.setReportStateChanged(false); + } + setReportStateChanged(enabled) { + if (enabled && !this._trackHierarchyListener) { + this._trackHierarchyListener = { + onPageOpen: () => this._emitSnapshot(false), + onPageClose: () => this._emitSnapshot(false) + }; + this._playwright.instrumentation.addListener(this._trackHierarchyListener, null); + this._emitSnapshot(true); + } else if (!enabled && this._trackHierarchyListener) { + this._playwright.instrumentation.removeListener(this._trackHierarchyListener); + this._trackHierarchyListener = void 0; + } + } + async resetForReuse() { + const contexts = /* @__PURE__ */ new Set(); + for (const page of this._playwright.allPages()) + contexts.add(page.browserContext); + for (const context of contexts) + await context.resetForReuse(internalMetadata, null); + } + async navigate(url2) { + for (const p of this._playwright.allPages()) + await p.mainFrame().goto(internalMetadata, url2, { timeout: DEFAULT_PLAYWRIGHT_TIMEOUT }); + } + async setRecorderMode(params) { + await this._closeBrowsersWithoutPages(); + if (params.mode === "none") { + for (const recorder of await this._allRecorders()) { + recorder.hideHighlightedSelector(); + recorder.setMode("none"); + } + return; + } + if (!this._playwright.allBrowsers().length) + await this._playwright.chromium.launch(internalMetadata, { headless: !!define_process_env_default.PW_DEBUG_CONTROLLER_HEADLESS, timeout: DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT }); + const pages = this._playwright.allPages(); + if (!pages.length) { + const [browser2] = this._playwright.allBrowsers(); + const { context } = await browser2.newContextForReuse({}, internalMetadata); + await context.newPage(internalMetadata); + } + if (params.testIdAttributeName) { + for (const page of this._playwright.allPages()) + page.browserContext.selectors().setTestIdAttributeName(params.testIdAttributeName); + } + for (const recorder of await this._allRecorders()) { + recorder.hideHighlightedSelector(); + if (params.mode !== "inspecting") + recorder.setOutput(this._codegenId, params.file); + recorder.setMode(params.mode); + } + } + async highlight(params) { + if (params.selector) + unsafeLocatorOrSelectorAsSelector(this._sdkLanguage, params.selector, "data-testid"); + const ariaTemplate = params.ariaTemplate ? parseAriaSnapshotUnsafe(yaml, params.ariaTemplate) : void 0; + for (const recorder of await this._allRecorders()) { + if (ariaTemplate) + recorder.setHighlightedAriaTemplate(ariaTemplate); + else if (params.selector) + recorder.setHighlightedSelector(this._sdkLanguage, params.selector); + } + } + async hideHighlight() { + for (const recorder of await this._allRecorders()) + recorder.hideHighlightedSelector(); + await this._playwright.hideHighlight(); + } + allBrowsers() { + return [...this._playwright.allBrowsers()]; + } + async resume() { + for (const recorder of await this._allRecorders()) + recorder.resume(); + } + async kill() { + gracefullyProcessExitDoNotHang(0); + } + async closeAllBrowsers() { + await Promise.all(this.allBrowsers().map((browser2) => browser2.close({ reason: "Close all browsers requested" }))); + } + _emitSnapshot(initial) { + const pageCount = this._playwright.allPages().length; + if (initial && !pageCount) + return; + this.emit(_DebugController2.Events.StateChanged, { pageCount }); + } + async _allRecorders() { + const contexts = /* @__PURE__ */ new Set(); + for (const page of this._playwright.allPages()) + contexts.add(page.browserContext); + const result = await Promise.all([...contexts].map((c) => Recorder.showInspector(c, { omitCallTracking: true }, () => Promise.resolve(new InspectingRecorderApp(this))))); + return result.filter(Boolean); + } + async _closeBrowsersWithoutPages() { + for (const browser2 of this._playwright.allBrowsers()) { + for (const context of browser2.contexts()) { + if (!context.pages().length) + await context.close({ reason: "Browser collected" }); + } + if (!browser2.contexts()) + await browser2.close({ reason: "Browser collected" }); + } + } +}; +_DebugController.Events = { + StateChanged: "stateChanged", + InspectRequested: "inspectRequested", + SourceChanged: "sourceChanged", + Paused: "paused", + SetModeRequested: "setModeRequested" +}; +let DebugController = _DebugController; +class InspectingRecorderApp extends EmptyRecorderApp { + constructor(debugController) { + super(); + this._debugController = debugController; + } + async elementPicked(elementInfo) { + const locator = asLocator(this._debugController._sdkLanguage, elementInfo.selector); + this._debugController.emit(DebugController.Events.InspectRequested, { selector: elementInfo.selector, locator, ariaSnapshot: elementInfo.ariaSnapshot }); + } + async setSources(sources) { + const source2 = sources.find((s) => s.id === this._debugController._codegenId); + const { text, header, footer, actions } = source2 || { text: "" }; + this._debugController.emit(DebugController.Events.SourceChanged, { text, header, footer, actions }); + } + async setPaused(paused) { + this._debugController.emit(DebugController.Events.Paused, { paused }); + } + async setMode(mode) { + this._debugController.emit(DebugController.Events.SetModeRequested, { mode }); + } +} +const ConnectionEvents = { + Disconnected: Symbol("Disconnected") +}; +const kBrowserCloseMessageId$1 = -9999; +class FFConnection extends eventsExports.EventEmitter { + constructor(transport, protocolLogger, browserLogsCollector) { + super(); + this.setMaxListeners(0); + this._transport = transport; + this._protocolLogger = protocolLogger; + this._browserLogsCollector = browserLogsCollector; + this._lastId = 0; + this._sessions = /* @__PURE__ */ new Map(); + this._closed = false; + this.rootSession = new FFSession(this, "", (message) => this._rawSend(message)); + this._sessions.set("", this.rootSession); + this._transport.onmessage = this._onMessage.bind(this); + this._transport.onclose = this._onClose.bind(this); + } + nextMessageId() { + return ++this._lastId; + } + _rawSend(message) { + this._protocolLogger("send", message); + this._transport.send(message); + } + async _onMessage(message) { + this._protocolLogger("receive", message); + if (message.id === kBrowserCloseMessageId$1) + return; + const session = this._sessions.get(message.sessionId || ""); + if (session) + session.dispatchMessage(message); + } + _onClose(reason) { + this._closed = true; + this._transport.onmessage = void 0; + this._transport.onclose = void 0; + this._browserDisconnectedLogs = helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason); + this.rootSession.dispose(); + Promise.resolve().then(() => this.emit(ConnectionEvents.Disconnected)); + } + close() { + if (!this._closed) + this._transport.close(); + } + createSession(sessionId) { + const session = new FFSession(this, sessionId, (message) => this._rawSend({ ...message, sessionId })); + this._sessions.set(sessionId, session); + return session; + } +} +class FFSession extends eventsExports.EventEmitter { + constructor(connection, sessionId, rawSend) { + super(); + this._disposed = false; + this._crashed = false; + this.setMaxListeners(0); + this._callbacks = /* @__PURE__ */ new Map(); + this._connection = connection; + this._sessionId = sessionId; + this._rawSend = rawSend; + this.on = super.on; + this.addListener = super.addListener; + this.off = super.removeListener; + this.removeListener = super.removeListener; + this.once = super.once; + } + markAsCrashed() { + this._crashed = true; + } + async send(method, params) { + if (this._crashed || this._disposed || this._connection._closed || this._connection._browserDisconnectedLogs) + throw new ProtocolError(this._crashed ? "crashed" : "closed", void 0, this._connection._browserDisconnectedLogs); + const id = this._connection.nextMessageId(); + this._rawSend({ method, params, id }); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + sendMayFail(method, params) { + return this.send(method, params).catch((error2) => debugLogger.log("error", error2)); + } + dispatchMessage(object) { + if (object.id) { + const callback = this._callbacks.get(object.id); + if (callback) { + this._callbacks.delete(object.id); + if (object.error) { + callback.error.setMessage(object.error.message); + callback.reject(callback.error); + } else { + callback.resolve(object.result); + } + } + } else { + Promise.resolve().then(() => this.emit(object.method, object.params)); + } + } + dispose() { + this._disposed = true; + this._connection._sessions.delete(this._sessionId); + for (const callback of this._callbacks.values()) { + callback.error.type = this._crashed ? "crashed" : "closed"; + callback.error.logs = this._connection._browserDisconnectedLogs; + callback.reject(callback.error); + } + this._callbacks.clear(); + } +} +async function getAccessibilityTree$1(session, needle) { + const objectId = needle ? needle._objectId : void 0; + const { tree } = await session.send("Accessibility.getFullAXTree", { objectId }); + const axNode = new FFAXNode(tree); + return { + tree: axNode, + needle: needle ? axNode._findNeedle() : null + }; +} +const FFRoleToARIARole = new Map(Object.entries({ + "pushbutton": "button", + "checkbutton": "checkbox", + "editcombobox": "combobox", + "content deletion": "deletion", + "footnote": "doc-footnote", + "non-native document": "document", + "grouping": "group", + "graphic": "img", + "content insertion": "insertion", + "animation": "marquee", + "flat equation": "math", + "menupopup": "menu", + "check menu item": "menuitemcheckbox", + "radio menu item": "menuitemradio", + "listbox option": "option", + "radiobutton": "radio", + "statusbar": "status", + "pagetab": "tab", + "pagetablist": "tablist", + "propertypage": "tabpanel", + "entry": "textbox", + "outline": "tree", + "tree table": "treegrid", + "outlineitem": "treeitem" +})); +class FFAXNode { + constructor(payload) { + this._payload = payload; + this._children = (payload.children || []).map((x) => new FFAXNode(x)); + this._editable = !!payload.editable; + this._richlyEditable = this._editable && (payload.tag !== "textarea" && payload.tag !== "input"); + this._focusable = !!payload.focusable; + this._expanded = !!payload.expanded; + this._name = this._payload.name; + this._role = this._payload.role; + } + _isPlainTextField() { + if (this._richlyEditable) + return false; + if (this._editable) + return true; + return this._role === "entry"; + } + _isTextOnlyObject() { + const role = this._role; + return role === "text leaf" || role === "text" || role === "statictext"; + } + _hasFocusableChild() { + if (this._cachedHasFocusableChild === void 0) { + this._cachedHasFocusableChild = false; + for (const child of this._children) { + if (child._focusable || child._hasFocusableChild()) { + this._cachedHasFocusableChild = true; + break; + } + } + } + return this._cachedHasFocusableChild; + } + children() { + return this._children; + } + _findNeedle() { + if (this._payload.foundObject) + return this; + for (const child of this._children) { + const found = child._findNeedle(); + if (found) + return found; + } + return null; + } + isLeafNode() { + if (!this._children.length) + return true; + if (this._isPlainTextField() || this._isTextOnlyObject()) + return true; + switch (this._role) { + case "graphic": + case "scrollbar": + case "slider": + case "separator": + case "progressbar": + return true; + } + if (this._hasFocusableChild()) + return false; + if (this._focusable && this._role !== "document" && this._name) + return true; + if (this._role === "heading" && this._name) + return true; + return false; + } + isControl() { + switch (this._role) { + case "checkbutton": + case "check menu item": + case "check rich option": + case "combobox": + case "combobox option": + case "color chooser": + case "listbox": + case "listbox option": + case "listbox rich option": + case "popup menu": + case "menupopup": + case "menuitem": + case "menubar": + case "button": + case "pushbutton": + case "radiobutton": + case "radio menuitem": + case "scrollbar": + case "slider": + case "spinbutton": + case "switch": + case "pagetab": + case "entry": + case "tree table": + return true; + default: + return false; + } + } + isInteresting(insideControl) { + if (this._focusable || this._richlyEditable) + return true; + if (this.isControl()) + return true; + if (insideControl) + return false; + return this.isLeafNode() && !!this._name.trim(); + } + serialize() { + const node2 = { + role: FFRoleToARIARole.get(this._role) || this._role, + name: this._name || "" + }; + const userStringProperties = [ + "name", + "description", + "roledescription", + "valuetext", + "keyshortcuts" + ]; + for (const userStringProperty of userStringProperties) { + if (!(userStringProperty in this._payload)) + continue; + node2[userStringProperty] = this._payload[userStringProperty]; + } + const booleanProperties = [ + "disabled", + "expanded", + "focused", + "modal", + "multiline", + "multiselectable", + "readonly", + "required", + "selected" + ]; + for (const booleanProperty of booleanProperties) { + if (this._role === "document" && booleanProperty === "focused") + continue; + const value = this._payload[booleanProperty]; + if (!value) + continue; + node2[booleanProperty] = value; + } + const numericalProperties = [ + "level" + ]; + for (const numericalProperty of numericalProperties) { + if (!(numericalProperty in this._payload)) + continue; + node2[numericalProperty] = this._payload[numericalProperty]; + } + const tokenProperties = [ + "autocomplete", + "haspopup", + "orientation" + ]; + for (const tokenProperty of tokenProperties) { + const value = this._payload[tokenProperty]; + if (!value || value === "false") + continue; + node2[tokenProperty] = value; + } + const axNode = node2; + axNode.valueString = this._payload.value; + if ("checked" in this._payload) + axNode.checked = this._payload.checked === true ? "checked" : this._payload.checked === "mixed" ? "mixed" : "unchecked"; + if ("pressed" in this._payload) + axNode.pressed = this._payload.pressed === true ? "pressed" : "released"; + if ("invalid" in this._payload) + axNode.invalid = this._payload.invalid === true ? "true" : "false"; + return axNode; + } +} +class FFExecutionContext { + constructor(session, executionContextId) { + this._session = session; + this._executionContextId = executionContextId; + } + async rawEvaluateJSON(expression) { + const payload = await this._session.send("Runtime.evaluate", { + expression, + returnByValue: true, + executionContextId: this._executionContextId + }).catch(rewriteError$1); + checkException(payload.exceptionDetails); + return payload.result.value; + } + async rawEvaluateHandle(context, expression) { + const payload = await this._session.send("Runtime.evaluate", { + expression, + returnByValue: false, + executionContextId: this._executionContextId + }).catch(rewriteError$1); + checkException(payload.exceptionDetails); + return createHandle$1(context, payload.result); + } + async evaluateWithArguments(expression, returnByValue, utilityScript, values, handles) { + const payload = await this._session.send("Runtime.callFunction", { + functionDeclaration: expression, + args: [ + { objectId: utilityScript._objectId, value: void 0 }, + ...values.map((value) => ({ value })), + ...handles.map((handle) => ({ objectId: handle._objectId, value: void 0 })) + ], + returnByValue, + executionContextId: this._executionContextId + }).catch(rewriteError$1); + checkException(payload.exceptionDetails); + if (returnByValue) + return parseEvaluationResultValue(payload.result.value); + return createHandle$1(utilityScript._context, payload.result); + } + async getProperties(object) { + const response2 = await this._session.send("Runtime.getObjectProperties", { + executionContextId: this._executionContextId, + objectId: object._objectId + }); + const result = /* @__PURE__ */ new Map(); + for (const property of response2.properties) + result.set(property.name, createHandle$1(object._context, property.value)); + return result; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await this._session.send("Runtime.disposeObject", { + executionContextId: this._executionContextId, + objectId: handle._objectId + }); + } +} +function checkException(exceptionDetails) { + if (!exceptionDetails) + return; + if (exceptionDetails.value) + throw new JavaScriptErrorInEvaluate(JSON.stringify(exceptionDetails.value)); + else + throw new JavaScriptErrorInEvaluate(exceptionDetails.text + (exceptionDetails.stack ? "\n" + exceptionDetails.stack : "")); +} +function rewriteError$1(error2) { + if (error2.message.includes("cyclic object value") || error2.message.includes("Object is not serializable")) + return { result: { type: "undefined", value: void 0 } }; + if (error2 instanceof TypeError && error2.message.startsWith("Converting circular structure to JSON")) + rewriteErrorMessage(error2, error2.message + " Are you passing a nested JSHandle?"); + if (!isJavaScriptErrorInEvaluate(error2) && !isSessionClosedError(error2)) + throw new Error("Execution context was destroyed, most likely because of a navigation."); + throw error2; +} +function potentiallyUnserializableValue$1(remoteObject) { + const value = remoteObject.value; + const unserializableValue = remoteObject.unserializableValue; + return unserializableValue ? parseUnserializableValue(unserializableValue) : value; +} +function renderPreview$1(object) { + if (object.type === "undefined") + return "undefined"; + if (object.unserializableValue) + return String(object.unserializableValue); + if (object.type === "symbol") + return "Symbol()"; + if (object.subtype === "regexp") + return "RegExp"; + if (object.subtype === "weakmap") + return "WeakMap"; + if (object.subtype === "weakset") + return "WeakSet"; + if (object.subtype) + return object.subtype[0].toUpperCase() + object.subtype.slice(1); + if ("value" in object) + return String(object.value); +} +function createHandle$1(context, remoteObject) { + if (remoteObject.subtype === "node") { + assert(context instanceof FrameExecutionContext); + return new ElementHandle$1(context, remoteObject.objectId); + } + return new JSHandle$1(context, remoteObject.subtype || remoteObject.type || "", renderPreview$1(remoteObject), remoteObject.objectId, potentiallyUnserializableValue$1(remoteObject)); +} +function toModifiersMask$1(modifiers) { + let mask = 0; + if (modifiers.has("Alt")) + mask |= 1; + if (modifiers.has("Control")) + mask |= 2; + if (modifiers.has("Shift")) + mask |= 4; + if (modifiers.has("Meta")) + mask |= 8; + return mask; +} +function toButtonNumber(button) { + if (button === "left") + return 0; + if (button === "middle") + return 1; + if (button === "right") + return 2; + return 0; +} +function toButtonsMask$1(buttons) { + let mask = 0; + if (buttons.has("left")) + mask |= 1; + if (buttons.has("right")) + mask |= 2; + if (buttons.has("middle")) + mask |= 4; + return mask; +} +let RawKeyboardImpl$1 = class RawKeyboardImpl3 { + constructor(client) { + this._client = client; + } + async keydown(modifiers, keyName, description, autoRepeat) { + let text = description.text; + if (text === "\r") + text = ""; + const { code, key: key2, location: location2 } = description; + await this._client.send("Page.dispatchKeyEvent", { + type: "keydown", + keyCode: description.keyCodeWithoutLocation, + code, + key: key2, + repeat: autoRepeat, + location: location2, + text + }); + } + async keyup(modifiers, keyName, description) { + const { code, key: key2, location: location2 } = description; + await this._client.send("Page.dispatchKeyEvent", { + type: "keyup", + key: key2, + keyCode: description.keyCodeWithoutLocation, + code, + location: location2, + repeat: false + }); + } + async sendText(text) { + await this._client.send("Page.insertText", { text }); + } +}; +let RawMouseImpl$1 = class RawMouseImpl3 { + constructor(client) { + this._client = client; + } + async move(x, y, button, buttons, modifiers, forClick) { + await this._client.send("Page.dispatchMouseEvent", { + type: "mousemove", + button: 0, + buttons: toButtonsMask$1(buttons), + x: Math.floor(x), + y: Math.floor(y), + modifiers: toModifiersMask$1(modifiers) + }); + } + async down(x, y, button, buttons, modifiers, clickCount) { + await this._client.send("Page.dispatchMouseEvent", { + type: "mousedown", + button: toButtonNumber(button), + buttons: toButtonsMask$1(buttons), + x: Math.floor(x), + y: Math.floor(y), + modifiers: toModifiersMask$1(modifiers), + clickCount + }); + } + async up(x, y, button, buttons, modifiers, clickCount) { + await this._client.send("Page.dispatchMouseEvent", { + type: "mouseup", + button: toButtonNumber(button), + buttons: toButtonsMask$1(buttons), + x: Math.floor(x), + y: Math.floor(y), + modifiers: toModifiersMask$1(modifiers), + clickCount + }); + } + async wheel(x, y, buttons, modifiers, deltaX, deltaY) { + await this._page.mainFrame().evaluateExpression(`new Promise(requestAnimationFrame)`, { world: "utility" }); + await this._client.send("Page.dispatchWheelEvent", { + deltaX, + deltaY, + x: Math.floor(x), + y: Math.floor(y), + deltaZ: 0, + modifiers: toModifiersMask$1(modifiers) + }); + } + setPage(page) { + this._page = page; + } +}; +let RawTouchscreenImpl$1 = class RawTouchscreenImpl3 { + constructor(client) { + this._client = client; + } + async tap(x, y, modifiers) { + await this._client.send("Page.dispatchTapEvent", { + x, + y, + modifiers: toModifiersMask$1(modifiers) + }); + } +}; +class FFNetworkManager { + constructor(session, page) { + this._session = session; + this._requests = /* @__PURE__ */ new Map(); + this._page = page; + this._eventListeners = [ + eventsHelper.addEventListener(session, "Network.requestWillBeSent", this._onRequestWillBeSent.bind(this)), + eventsHelper.addEventListener(session, "Network.responseReceived", this._onResponseReceived.bind(this)), + eventsHelper.addEventListener(session, "Network.requestFinished", this._onRequestFinished.bind(this)), + eventsHelper.addEventListener(session, "Network.requestFailed", this._onRequestFailed.bind(this)) + ]; + } + dispose() { + eventsHelper.removeEventListeners(this._eventListeners); + } + async setRequestInterception(enabled) { + await Promise.all([ + this._session.send("Network.setRequestInterception", { enabled }), + this._session.send("Page.setCacheDisabled", { cacheDisabled: enabled }) + ]); + } + _onRequestWillBeSent(event) { + const redirectedFrom = event.redirectedFrom ? this._requests.get(event.redirectedFrom) || null : null; + const frame = redirectedFrom ? redirectedFrom.request.frame() : event.frameId ? this._page.frameManager.frame(event.frameId) : null; + if (!frame) + return; + if (redirectedFrom) + this._requests.delete(redirectedFrom._id); + const request2 = new InterceptableRequest2(frame, redirectedFrom, event); + let route; + if (event.isIntercepted) + route = new FFRouteImpl(this._session, request2); + this._requests.set(request2._id, request2); + this._page.frameManager.requestStarted(request2.request, route); + } + _onResponseReceived(event) { + var _a2, _b2, _c2, _d2, _e2; + const request2 = this._requests.get(event.requestId); + if (!request2) + return; + const getResponseBody = async () => { + const response22 = await this._session.send("Network.getResponseBody", { + requestId: request2._id + }); + if (response22.evicted) + throw new Error(`Response body for ${request2.request.method()} ${request2.request.url()} was evicted!`); + return Buffer.from(response22.base64body, "base64"); + }; + const startTime = event.timing.startTime; + function relativeToStart(time) { + if (!time) + return -1; + return (time - startTime) / 1e3; + } + const timing = { + startTime: startTime / 1e3, + domainLookupStart: relativeToStart(event.timing.domainLookupStart), + domainLookupEnd: relativeToStart(event.timing.domainLookupEnd), + connectStart: relativeToStart(event.timing.connectStart), + secureConnectionStart: relativeToStart(event.timing.secureConnectionStart), + connectEnd: relativeToStart(event.timing.connectEnd), + requestStart: relativeToStart(event.timing.requestStart), + responseStart: relativeToStart(event.timing.responseStart) + }; + const response2 = new Response$1(request2.request, event.status, event.statusText, parseMultivalueHeaders(event.headers), timing, getResponseBody, event.fromServiceWorker); + if ((event == null ? void 0 : event.remoteIPAddress) && typeof (event == null ? void 0 : event.remotePort) === "number") { + response2._serverAddrFinished({ + ipAddress: event.remoteIPAddress, + port: event.remotePort + }); + } else { + response2._serverAddrFinished(); + } + response2._securityDetailsFinished({ + protocol: (_a2 = event == null ? void 0 : event.securityDetails) == null ? void 0 : _a2.protocol, + subjectName: (_b2 = event == null ? void 0 : event.securityDetails) == null ? void 0 : _b2.subjectName, + issuer: (_c2 = event == null ? void 0 : event.securityDetails) == null ? void 0 : _c2.issuer, + validFrom: (_d2 = event == null ? void 0 : event.securityDetails) == null ? void 0 : _d2.validFrom, + validTo: (_e2 = event == null ? void 0 : event.securityDetails) == null ? void 0 : _e2.validTo + }); + response2.setRawResponseHeaders(null); + response2.setResponseHeadersSize(null); + this._page.frameManager.requestReceivedResponse(response2); + } + _onRequestFinished(event) { + const request2 = this._requests.get(event.requestId); + if (!request2) + return; + const response2 = request2.request._existingResponse(); + response2.setTransferSize(event.transferSize); + response2.setEncodedBodySize(event.encodedBodySize); + const isRedirected = response2.status() >= 300 && response2.status() <= 399; + const responseEndTime = event.responseEndTime ? event.responseEndTime / 1e3 - response2.timing().startTime : -1; + if (isRedirected) { + response2._requestFinished(responseEndTime); + } else { + this._requests.delete(request2._id); + response2._requestFinished(responseEndTime); + } + if (event.protocolVersion) + response2._setHttpVersion(event.protocolVersion); + this._page.frameManager.reportRequestFinished(request2.request, response2); + } + _onRequestFailed(event) { + const request2 = this._requests.get(event.requestId); + if (!request2) + return; + this._requests.delete(request2._id); + const response2 = request2.request._existingResponse(); + if (response2) { + response2.setTransferSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(-1); + } + request2.request._setFailureText(event.errorCode); + this._page.frameManager.requestFailed(request2.request, event.errorCode === "NS_BINDING_ABORTED"); + } +} +const causeToResourceType = { + TYPE_INVALID: "other", + TYPE_OTHER: "other", + TYPE_SCRIPT: "script", + TYPE_IMAGE: "image", + TYPE_STYLESHEET: "stylesheet", + TYPE_OBJECT: "other", + TYPE_DOCUMENT: "document", + TYPE_SUBDOCUMENT: "document", + TYPE_REFRESH: "document", + TYPE_XBL: "other", + TYPE_PING: "other", + TYPE_XMLHTTPREQUEST: "xhr", + TYPE_OBJECT_SUBREQUEST: "other", + TYPE_DTD: "other", + TYPE_FONT: "font", + TYPE_MEDIA: "media", + TYPE_WEBSOCKET: "websocket", + TYPE_CSP_REPORT: "other", + TYPE_XSLT: "other", + TYPE_BEACON: "other", + TYPE_FETCH: "fetch", + TYPE_IMAGESET: "image", + TYPE_WEB_MANIFEST: "manifest" +}; +const internalCauseToResourceType = { + TYPE_INTERNAL_EVENTSOURCE: "eventsource" +}; +class InterceptableRequest2 { + constructor(frame, redirectedFrom, payload) { + this._id = payload.requestId; + if (redirectedFrom) + redirectedFrom._redirectedTo = this; + let postDataBuffer = null; + if (payload.postData) + postDataBuffer = Buffer.from(payload.postData, "base64"); + this.request = new Request$1( + frame._page.browserContext, + frame, + null, + redirectedFrom ? redirectedFrom.request : null, + payload.navigationId, + payload.url, + internalCauseToResourceType[payload.internalCause] || causeToResourceType[payload.cause] || "other", + payload.method, + postDataBuffer, + payload.headers + ); + this.request.setRawRequestHeaders(null); + } + _finalRequest() { + let request2 = this; + while (request2._redirectedTo) + request2 = request2._redirectedTo; + return request2; + } +} +class FFRouteImpl { + constructor(session, request2) { + this._session = session; + this._request = request2; + } + async continue(overrides) { + await this._session.sendMayFail("Network.resumeInterceptedRequest", { + requestId: this._request._id, + url: overrides.url, + method: overrides.method, + headers: overrides.headers, + postData: overrides.postData ? Buffer.from(overrides.postData).toString("base64") : void 0 + }); + } + async fulfill(response2) { + const base64body = response2.isBase64 ? response2.body : Buffer.from(response2.body).toString("base64"); + await this._session.sendMayFail("Network.fulfillInterceptedRequest", { + requestId: this._request._id, + status: response2.status, + statusText: statusText(response2.status), + headers: response2.headers, + base64body + }); + } + async abort(errorCode) { + await this._session.sendMayFail("Network.abortInterceptedRequest", { + requestId: this._request._id, + errorCode + }); + } +} +function parseMultivalueHeaders(headers) { + const result = []; + for (const header of headers) { + const separator = header.name.toLowerCase() === "set-cookie" ? "\n" : ","; + const tokens = header.value.split(separator).map((s) => s.trim()); + for (const token of tokens) + result.push({ name: header.name, value: token }); + } + return result; +} +const UTILITY_WORLD_NAME$1 = "__playwright_utility_world__"; +class FFPage { + constructor(session, browserContext, opener) { + this.cspErrorsAsynchronousForInlineScripts = true; + this._reportedAsNew = false; + this._workers = /* @__PURE__ */ new Map(); + this._initScripts = []; + this._session = session; + this._opener = opener; + this.rawKeyboard = new RawKeyboardImpl$1(session); + this.rawMouse = new RawMouseImpl$1(session); + this.rawTouchscreen = new RawTouchscreenImpl$1(session); + this._contextIdToContext = /* @__PURE__ */ new Map(); + this._browserContext = browserContext; + this._page = new Page$1(this, browserContext); + this.rawMouse.setPage(this._page); + this._networkManager = new FFNetworkManager(session, this._page); + this._page.on(Page$1.Events.FrameDetached, (frame) => this._removeContextsForFrame(frame)); + this._eventListeners = [ + eventsHelper.addEventListener(this._session, "Page.eventFired", this._onEventFired.bind(this)), + eventsHelper.addEventListener(this._session, "Page.frameAttached", this._onFrameAttached.bind(this)), + eventsHelper.addEventListener(this._session, "Page.frameDetached", this._onFrameDetached.bind(this)), + eventsHelper.addEventListener(this._session, "Page.navigationAborted", this._onNavigationAborted.bind(this)), + eventsHelper.addEventListener(this._session, "Page.navigationCommitted", this._onNavigationCommitted.bind(this)), + eventsHelper.addEventListener(this._session, "Page.navigationStarted", this._onNavigationStarted.bind(this)), + eventsHelper.addEventListener(this._session, "Page.sameDocumentNavigation", this._onSameDocumentNavigation.bind(this)), + eventsHelper.addEventListener(this._session, "Runtime.executionContextCreated", this._onExecutionContextCreated.bind(this)), + eventsHelper.addEventListener(this._session, "Runtime.executionContextDestroyed", this._onExecutionContextDestroyed.bind(this)), + eventsHelper.addEventListener(this._session, "Runtime.executionContextsCleared", this._onExecutionContextsCleared.bind(this)), + eventsHelper.addEventListener(this._session, "Page.linkClicked", (event) => this._onLinkClicked(event.phase)), + eventsHelper.addEventListener(this._session, "Page.uncaughtError", this._onUncaughtError.bind(this)), + eventsHelper.addEventListener(this._session, "Runtime.console", this._onConsole.bind(this)), + eventsHelper.addEventListener(this._session, "Page.dialogOpened", this._onDialogOpened.bind(this)), + eventsHelper.addEventListener(this._session, "Page.bindingCalled", this._onBindingCalled.bind(this)), + eventsHelper.addEventListener(this._session, "Page.fileChooserOpened", this._onFileChooserOpened.bind(this)), + eventsHelper.addEventListener(this._session, "Page.workerCreated", this._onWorkerCreated.bind(this)), + eventsHelper.addEventListener(this._session, "Page.workerDestroyed", this._onWorkerDestroyed.bind(this)), + eventsHelper.addEventListener(this._session, "Page.dispatchMessageFromWorker", this._onDispatchMessageFromWorker.bind(this)), + eventsHelper.addEventListener(this._session, "Page.crashed", this._onCrashed.bind(this)), + eventsHelper.addEventListener(this._session, "Page.videoRecordingStarted", this._onVideoRecordingStarted.bind(this)), + eventsHelper.addEventListener(this._session, "Page.webSocketCreated", this._onWebSocketCreated.bind(this)), + eventsHelper.addEventListener(this._session, "Page.webSocketClosed", this._onWebSocketClosed.bind(this)), + eventsHelper.addEventListener(this._session, "Page.webSocketFrameReceived", this._onWebSocketFrameReceived.bind(this)), + eventsHelper.addEventListener(this._session, "Page.webSocketFrameSent", this._onWebSocketFrameSent.bind(this)), + eventsHelper.addEventListener(this._session, "Page.screencastFrame", this._onScreencastFrame.bind(this)) + ]; + this._session.once("Page.ready", () => { + var _a2; + if (this._reportedAsNew) + return; + this._reportedAsNew = true; + this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page); + }); + this.addInitScript(new InitScript(""), UTILITY_WORLD_NAME$1).catch((e) => this._markAsError(e)); + } + async _markAsError(error2) { + var _a2; + if (this._reportedAsNew) + return; + this._reportedAsNew = true; + this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page, error2); + } + _onWebSocketCreated(event) { + this._page.frameManager.onWebSocketCreated(webSocketId(event.frameId, event.wsid), event.requestURL); + this._page.frameManager.onWebSocketRequest(webSocketId(event.frameId, event.wsid)); + } + _onWebSocketClosed(event) { + if (event.error) + this._page.frameManager.webSocketError(webSocketId(event.frameId, event.wsid), event.error); + this._page.frameManager.webSocketClosed(webSocketId(event.frameId, event.wsid)); + } + _onWebSocketFrameReceived(event) { + this._page.frameManager.webSocketFrameReceived(webSocketId(event.frameId, event.wsid), event.opcode, event.data); + } + _onWebSocketFrameSent(event) { + this._page.frameManager.onWebSocketFrameSent(webSocketId(event.frameId, event.wsid), event.opcode, event.data); + } + _onExecutionContextCreated(payload) { + const { executionContextId, auxData } = payload; + const frame = this._page.frameManager.frame(auxData.frameId); + if (!frame) + return; + const delegate = new FFExecutionContext(this._session, executionContextId); + let worldName = null; + if (auxData.name === UTILITY_WORLD_NAME$1) + worldName = "utility"; + else if (!auxData.name) + worldName = "main"; + const context = new FrameExecutionContext(delegate, frame, worldName); + if (worldName) + frame._contextCreated(worldName, context); + this._contextIdToContext.set(executionContextId, context); + } + _onExecutionContextDestroyed(payload) { + const { executionContextId } = payload; + const context = this._contextIdToContext.get(executionContextId); + if (!context) + return; + this._contextIdToContext.delete(executionContextId); + context.frame._contextDestroyed(context); + } + _onExecutionContextsCleared() { + for (const executionContextId of Array.from(this._contextIdToContext.keys())) + this._onExecutionContextDestroyed({ executionContextId }); + } + _removeContextsForFrame(frame) { + for (const [contextId, context] of this._contextIdToContext) { + if (context.frame === frame) + this._contextIdToContext.delete(contextId); + } + } + _onLinkClicked(phase) { + if (phase === "before") + this._page.frameManager.frameWillPotentiallyRequestNavigation(); + else + this._page.frameManager.frameDidPotentiallyRequestNavigation(); + } + _onNavigationStarted(params) { + this._page.frameManager.frameRequestedNavigation(params.frameId, params.navigationId); + } + _onNavigationAborted(params) { + this._page.frameManager.frameAbortedNavigation(params.frameId, params.errorText, params.navigationId); + } + _onNavigationCommitted(params) { + for (const [workerId, worker] of this._workers) { + if (worker.frameId === params.frameId) + this._onWorkerDestroyed({ workerId }); + } + this._page.frameManager.frameCommittedNewDocumentNavigation(params.frameId, params.url, params.name || "", params.navigationId || "", false); + } + _onSameDocumentNavigation(params) { + this._page.frameManager.frameCommittedSameDocumentNavigation(params.frameId, params.url); + } + _onFrameAttached(params) { + this._page.frameManager.frameAttached(params.frameId, params.parentFrameId); + } + _onFrameDetached(params) { + this._page.frameManager.frameDetached(params.frameId); + } + _onEventFired(payload) { + const { frameId, name } = payload; + if (name === "load") + this._page.frameManager.frameLifecycleEvent(frameId, "load"); + if (name === "DOMContentLoaded") + this._page.frameManager.frameLifecycleEvent(frameId, "domcontentloaded"); + } + _onUncaughtError(params) { + const { name, message } = splitErrorMessage(params.message); + const error2 = new Error(message); + error2.stack = params.message + "\n" + params.stack.split("\n").filter(Boolean).map((a) => a.replace(/([^@]*)@(.*)/, " at $1 ($2)")).join("\n"); + error2.name = name; + this._page.emitOnContextOnceInitialized(BrowserContext$1.Events.PageError, error2, this._page); + } + _onConsole(payload) { + const { type: type2, args, executionContextId, location: location2 } = payload; + const context = this._contextIdToContext.get(executionContextId); + if (!context) + return; + this._page.addConsoleMessage(type2 === "warn" ? "warning" : type2, args.map((arg) => createHandle$1(context, arg)), location2); + } + _onDialogOpened(params) { + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog$1( + this._page, + params.type, + params.message, + async (accept, promptText) => { + await this._session.sendMayFail("Page.handleDialog", { dialogId: params.dialogId, accept, promptText }); + }, + params.defaultValue + )); + } + async _onBindingCalled(event) { + const pageOrError = await this._page.waitForInitializedOrError(); + if (!(pageOrError instanceof Error)) { + const context = this._contextIdToContext.get(event.executionContextId); + if (context) + await this._page.onBindingCalled(event.payload, context); + } + } + async _onFileChooserOpened(payload) { + const { executionContextId, element } = payload; + const context = this._contextIdToContext.get(executionContextId); + if (!context) + return; + const handle = createHandle$1(context, element).asElement(); + await this._page._onFileChooserOpened(handle); + } + async _onWorkerCreated(event) { + const workerId = event.workerId; + const worker = new Worker$1(this._page, event.url); + const workerSession = new FFSession(this._session._connection, workerId, (message) => { + this._session.send("Page.sendMessageToWorker", { + frameId: event.frameId, + workerId, + message: JSON.stringify(message) + }).catch((e) => { + workerSession.dispatchMessage({ id: message.id, method: "", params: {}, error: { message: e.message, data: void 0 } }); + }); + }); + this._workers.set(workerId, { session: workerSession, frameId: event.frameId }); + this._page.addWorker(workerId, worker); + workerSession.once("Runtime.executionContextCreated", (event2) => { + worker.createExecutionContext(new FFExecutionContext(workerSession, event2.executionContextId)); + }); + workerSession.on("Runtime.console", (event2) => { + const { type: type2, args, location: location2 } = event2; + const context = worker.existingExecutionContext; + this._page.addConsoleMessage(type2, args.map((arg) => createHandle$1(context, arg)), location2); + }); + } + _onWorkerDestroyed(event) { + const workerId = event.workerId; + const worker = this._workers.get(workerId); + if (!worker) + return; + worker.session.dispose(); + this._workers.delete(workerId); + this._page.removeWorker(workerId); + } + async _onDispatchMessageFromWorker(event) { + const worker = this._workers.get(event.workerId); + if (!worker) + return; + worker.session.dispatchMessage(JSON.parse(event.message)); + } + async _onCrashed(event) { + this._session.markAsCrashed(); + this._page._didCrash(); + } + _onVideoRecordingStarted(event) { + this._browserContext._browser._videoStarted(this._browserContext, event.screencastId, event.file, this._page.waitForInitializedOrError()); + } + didClose() { + this._markAsError(new TargetClosedError$1()); + this._session.dispose(); + eventsHelper.removeEventListeners(this._eventListeners); + this._networkManager.dispose(); + this._page._didClose(); + } + async navigateFrame(frame, url2, referer) { + const response2 = await this._session.send("Page.navigate", { url: url2, referer, frameId: frame._id }); + return { newDocumentId: response2.navigationId || void 0 }; + } + async updateExtraHTTPHeaders() { + await this._session.send("Network.setExtraHTTPHeaders", { headers: this._page.extraHTTPHeaders() || [] }); + } + async updateEmulatedViewportSize() { + var _a2; + const viewportSize = ((_a2 = this._page.emulatedSize()) == null ? void 0 : _a2.viewport) ?? null; + await this._session.send("Page.setViewportSize", { viewportSize }); + } + async bringToFront() { + await this._session.send("Page.bringToFront", {}); + } + async updateEmulateMedia() { + const emulatedMedia = this._page.emulatedMedia(); + const colorScheme = emulatedMedia.colorScheme === "no-override" ? void 0 : emulatedMedia.colorScheme; + const reducedMotion = emulatedMedia.reducedMotion === "no-override" ? void 0 : emulatedMedia.reducedMotion; + const forcedColors = emulatedMedia.forcedColors === "no-override" ? void 0 : emulatedMedia.forcedColors; + const contrast = emulatedMedia.contrast === "no-override" ? void 0 : emulatedMedia.contrast; + await this._session.send("Page.setEmulatedMedia", { + // Empty string means reset. + type: emulatedMedia.media === "no-override" ? "" : emulatedMedia.media, + colorScheme, + reducedMotion, + forcedColors, + contrast + }); + } + async updateRequestInterception() { + await this._networkManager.setRequestInterception(this._page.needsRequestInterception()); + } + async updateFileChooserInterception() { + const enabled = this._page.fileChooserIntercepted(); + await this._session.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => { + }); + } + async reload() { + await this._session.send("Page.reload"); + } + async goBack() { + const { success } = await this._session.send("Page.goBack", { frameId: this._page.mainFrame()._id }); + return success; + } + async goForward() { + const { success } = await this._session.send("Page.goForward", { frameId: this._page.mainFrame()._id }); + return success; + } + async requestGC() { + await this._session.send("Heap.collectGarbage"); + } + async addInitScript(initScript, worldName) { + this._initScripts.push({ initScript, worldName }); + await this._updateInitScripts(); + } + async removeInitScripts(initScripts) { + const set2 = new Set(initScripts); + this._initScripts = this._initScripts.filter((s) => !set2.has(s.initScript)); + await this._updateInitScripts(); + } + async _updateInitScripts() { + await this._session.send("Page.setInitScripts", { scripts: this._initScripts.map((s) => ({ script: s.initScript.source, worldName: s.worldName })) }); + } + async closePage(runBeforeUnload) { + await this._session.send("Page.close", { runBeforeUnload }); + } + async setBackgroundColor(color) { + if (color) + throw new Error("Not implemented"); + } + async takeScreenshot(progress2, format, documentRect, viewportRect, quality, fitsViewport, scale) { + if (!documentRect) { + const scrollOffset = await this._page.mainFrame().waitForFunctionValueInUtility(progress2, () => ({ x: window.scrollX, y: window.scrollY })); + documentRect = { + x: viewportRect.x + scrollOffset.x, + y: viewportRect.y + scrollOffset.y, + width: viewportRect.width, + height: viewportRect.height + }; + } + progress2.throwIfAborted(); + const { data: data2 } = await this._session.send("Page.screenshot", { + mimeType: "image/" + format, + clip: documentRect, + quality, + omitDeviceScaleFactor: scale === "css" + }); + return Buffer.from(data2, "base64"); + } + async getContentFrame(handle) { + const { contentFrameId } = await this._session.send("Page.describeNode", { + frameId: handle._context.frame._id, + objectId: handle._objectId + }); + if (!contentFrameId) + return null; + return this._page.frameManager.frame(contentFrameId); + } + async getOwnerFrame(handle) { + const { ownerFrameId } = await this._session.send("Page.describeNode", { + frameId: handle._context.frame._id, + objectId: handle._objectId + }); + return ownerFrameId || null; + } + async getBoundingBox(handle) { + const quads = await this.getContentQuads(handle); + if (!quads || !quads.length) + return null; + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + for (const quad of quads) { + for (const point of quad) { + minX = Math.min(minX, point.x); + maxX = Math.max(maxX, point.x); + minY = Math.min(minY, point.y); + maxY = Math.max(maxY, point.y); + } + } + return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; + } + async scrollRectIntoViewIfNeeded(handle, rect) { + return await this._session.send("Page.scrollIntoViewIfNeeded", { + frameId: handle._context.frame._id, + objectId: handle._objectId, + rect + }).then(() => "done").catch((e) => { + if (e instanceof Error && e.message.includes("Node is detached from document")) + return "error:notconnected"; + if (e instanceof Error && e.message.includes("Node does not have a layout object")) + return "error:notvisible"; + throw e; + }); + } + async setScreencastOptions(options2) { + if (options2) { + const { screencastId } = await this._session.send("Page.startScreencast", options2); + this._screencastId = screencastId; + } else { + await this._session.send("Page.stopScreencast"); + } + } + _onScreencastFrame(event) { + if (!this._screencastId) + return; + const screencastId = this._screencastId; + this._page.throttleScreencastFrameAck(() => { + this._session.send("Page.screencastFrameAck", { screencastId }).catch((e) => debugLogger.log("error", e)); + }); + const buffer2 = Buffer.from(event.data, "base64"); + this._page.emit(Page$1.Events.ScreencastFrame, { + buffer: buffer2, + width: event.deviceWidth, + height: event.deviceHeight + }); + } + rafCountForStablePosition() { + return 1; + } + async getContentQuads(handle) { + const result = await this._session.sendMayFail("Page.getContentQuads", { + frameId: handle._context.frame._id, + objectId: handle._objectId + }); + if (!result) + return null; + return result.quads.map((quad) => [quad.p1, quad.p2, quad.p3, quad.p4]); + } + async setInputFilePaths(handle, files) { + await this._session.send("Page.setFileInputFiles", { + frameId: handle._context.frame._id, + objectId: handle._objectId, + files + }); + } + async adoptElementHandle(handle, to) { + const result = await this._session.send("Page.adoptNode", { + frameId: handle._context.frame._id, + objectId: handle._objectId, + executionContextId: to.delegate._executionContextId + }); + if (!result.remoteObject) + throw new Error(kUnableToAdoptErrorMessage); + return createHandle$1(to, result.remoteObject); + } + async getAccessibilityTree(needle) { + return getAccessibilityTree$1(this._session, needle); + } + async inputActionEpilogue() { + } + async resetForReuse() { + await this.rawMouse.move(-1, -1, "none", /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), false); + } + async getFrameElement(frame) { + const parent = frame.parentFrame(); + if (!parent) + throw new Error("Frame has been detached."); + const context = await parent._mainContext(); + const result = await this._session.send("Page.adoptNode", { + frameId: frame._id, + executionContextId: context.delegate._executionContextId + }); + if (!result.remoteObject) + throw new Error("Frame has been detached."); + return createHandle$1(context, result.remoteObject); + } + shouldToggleStyleSheetToSyncAnimations() { + return false; + } +} +function webSocketId(frameId, wsid) { + return `${frameId}---${wsid}`; +} +class FFBrowser extends Browser$1 { + constructor(parent, connection, options2) { + super(parent, options2); + this._version = ""; + this._userAgent = ""; + this._connection = connection; + this.session = connection.rootSession; + this._ffPages = /* @__PURE__ */ new Map(); + this._contexts = /* @__PURE__ */ new Map(); + this._connection.on(ConnectionEvents.Disconnected, () => this._onDisconnect()); + this.session.on("Browser.attachedToTarget", this._onAttachedToTarget.bind(this)); + this.session.on("Browser.detachedFromTarget", this._onDetachedFromTarget.bind(this)); + this.session.on("Browser.downloadCreated", this._onDownloadCreated.bind(this)); + this.session.on("Browser.downloadFinished", this._onDownloadFinished.bind(this)); + this.session.on("Browser.videoRecordingFinished", this._onVideoRecordingFinished.bind(this)); + } + static async connect(parent, transport, options2) { + const connection = new FFConnection(transport, options2.protocolLogger, options2.browserLogsCollector); + const browser2 = new FFBrowser(parent, connection, options2); + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + let firefoxUserPrefs = options2.originalLaunchOptions.firefoxUserPrefs ?? {}; + if (Object.keys(kBandaidFirefoxUserPrefs).length) + firefoxUserPrefs = { ...kBandaidFirefoxUserPrefs, ...firefoxUserPrefs }; + const promises2 = [ + browser2.session.send("Browser.enable", { + attachToDefaultContext: !!options2.persistent, + userPrefs: Object.entries(firefoxUserPrefs).map(([name, value]) => ({ name, value })) + }), + browser2._initVersion() + ]; + if (options2.persistent) { + browser2._defaultContext = new FFBrowserContext(browser2, void 0, options2.persistent); + promises2.push(browser2._defaultContext._initialize()); + } + const proxy = options2.originalLaunchOptions.proxyOverride || options2.proxy; + if (proxy) + promises2.push(browser2.session.send("Browser.setBrowserProxy", toJugglerProxyOptions(proxy))); + await Promise.all(promises2); + return browser2; + } + async _initVersion() { + const result = await this.session.send("Browser.getInfo"); + this._version = result.version.substring(result.version.indexOf("/") + 1); + this._userAgent = result.userAgent; + } + isConnected() { + return !this._connection._closed; + } + async doCreateNewContext(options2) { + if (options2.isMobile) + throw new Error("options.isMobile is not supported in Firefox"); + const { browserContextId } = await this.session.send("Browser.createBrowserContext", { removeOnDetach: true }); + const context = new FFBrowserContext(this, browserContextId, options2); + await context._initialize(); + this._contexts.set(browserContextId, context); + return context; + } + contexts() { + return Array.from(this._contexts.values()); + } + version() { + return this._version; + } + userAgent() { + return this._userAgent; + } + _onDetachedFromTarget(payload) { + const ffPage = this._ffPages.get(payload.targetId); + this._ffPages.delete(payload.targetId); + ffPage.didClose(); + } + _onAttachedToTarget(payload) { + const { targetId, browserContextId, openerId, type: type2 } = payload.targetInfo; + assert(type2 === "page"); + const context = browserContextId ? this._contexts.get(browserContextId) : this._defaultContext; + assert(context, `Unknown context id:${browserContextId}, _defaultContext: ${this._defaultContext}`); + const session = this._connection.createSession(payload.sessionId); + const opener = openerId ? this._ffPages.get(openerId) : null; + const ffPage = new FFPage(session, context, opener); + this._ffPages.set(targetId, ffPage); + } + _onDownloadCreated(payload) { + const ffPage = this._ffPages.get(payload.pageTargetId); + if (!ffPage) + return; + ffPage._page.frameManager.frameAbortedNavigation(payload.frameId, "Download is starting"); + let originPage = ffPage._page.initializedOrUndefined(); + if (!originPage) { + ffPage._markAsError(new Error("Starting new page download")); + if (ffPage._opener) + originPage = ffPage._opener._page.initializedOrUndefined(); + } + if (!originPage) + return; + this._downloadCreated(originPage, payload.uuid, payload.url, payload.suggestedFileName); + } + _onDownloadFinished(payload) { + const error2 = payload.canceled ? "canceled" : payload.error; + this._downloadFinished(payload.uuid, error2); + } + _onVideoRecordingFinished(payload) { + var _a2; + (_a2 = this._takeVideo(payload.screencastId)) == null ? void 0 : _a2.reportFinished(); + } + _onDisconnect() { + for (const video of this._idToVideo.values()) + video.artifact.reportFinished(new TargetClosedError$1()); + this._idToVideo.clear(); + for (const ffPage of this._ffPages.values()) + ffPage.didClose(); + this._ffPages.clear(); + this._didClose(); + } +} +class FFBrowserContext extends BrowserContext$1 { + constructor(browser2, browserContextId, options2) { + super(browser2, options2, browserContextId); + } + async _initialize() { + assert(!this._ffPages().length); + const browserContextId = this._browserContextId; + const promises2 = [ + super._initialize(), + this._updateInitScripts() + ]; + if (this._options.acceptDownloads !== "internal-browser-default") { + promises2.push(this._browser.session.send("Browser.setDownloadOptions", { + browserContextId, + downloadOptions: { + behavior: this._options.acceptDownloads === "accept" ? "saveToDisk" : "cancel", + downloadsDir: this._browser.options.downloadsPath + } + })); + } + if (this._options.viewport) { + const viewport = { + viewportSize: { width: this._options.viewport.width, height: this._options.viewport.height }, + deviceScaleFactor: this._options.deviceScaleFactor || 1 + }; + promises2.push(this._browser.session.send("Browser.setDefaultViewport", { browserContextId, viewport })); + } + if (this._options.hasTouch) + promises2.push(this._browser.session.send("Browser.setTouchOverride", { browserContextId, hasTouch: true })); + if (this._options.userAgent) + promises2.push(this._browser.session.send("Browser.setUserAgentOverride", { browserContextId, userAgent: this._options.userAgent })); + if (this._options.bypassCSP) + promises2.push(this._browser.session.send("Browser.setBypassCSP", { browserContextId, bypassCSP: true })); + if (this._options.ignoreHTTPSErrors || this._options.internalIgnoreHTTPSErrors) + promises2.push(this._browser.session.send("Browser.setIgnoreHTTPSErrors", { browserContextId, ignoreHTTPSErrors: true })); + if (this._options.javaScriptEnabled === false) + promises2.push(this._browser.session.send("Browser.setJavaScriptDisabled", { browserContextId, javaScriptDisabled: true })); + if (this._options.locale) + promises2.push(this._browser.session.send("Browser.setLocaleOverride", { browserContextId, locale: this._options.locale })); + if (this._options.timezoneId) + promises2.push(this._browser.session.send("Browser.setTimezoneOverride", { browserContextId, timezoneId: this._options.timezoneId })); + if (this._options.extraHTTPHeaders || this._options.locale) + promises2.push(this.setExtraHTTPHeaders(this._options.extraHTTPHeaders || [])); + if (this._options.httpCredentials) + promises2.push(this.setHTTPCredentials(this._options.httpCredentials)); + if (this._options.geolocation) + promises2.push(this.setGeolocation(this._options.geolocation)); + if (this._options.offline) + promises2.push(this.setOffline(this._options.offline)); + if (this._options.colorScheme !== "no-override") { + promises2.push(this._browser.session.send("Browser.setColorScheme", { + browserContextId, + colorScheme: this._options.colorScheme !== void 0 ? this._options.colorScheme : "light" + })); + } + if (this._options.reducedMotion !== "no-override") { + promises2.push(this._browser.session.send("Browser.setReducedMotion", { + browserContextId, + reducedMotion: this._options.reducedMotion !== void 0 ? this._options.reducedMotion : "no-preference" + })); + } + if (this._options.forcedColors !== "no-override") { + promises2.push(this._browser.session.send("Browser.setForcedColors", { + browserContextId, + forcedColors: this._options.forcedColors !== void 0 ? this._options.forcedColors : "none" + })); + } + if (this._options.contrast !== "no-override") { + promises2.push(this._browser.session.send("Browser.setContrast", { + browserContextId, + contrast: this._options.contrast !== void 0 ? this._options.contrast : "no-preference" + })); + } + if (this._options.recordVideo) { + promises2.push(this._ensureVideosPath().then(() => { + return this._browser.session.send("Browser.setVideoRecordingOptions", { + // validateBrowserContextOptions ensures correct video size. + options: { + ...this._options.recordVideo.size, + dir: this._options.recordVideo.dir + }, + browserContextId: this._browserContextId + }); + })); + } + const proxy = this._options.proxyOverride || this._options.proxy; + if (proxy) { + promises2.push(this._browser.session.send("Browser.setContextProxy", { + browserContextId: this._browserContextId, + ...toJugglerProxyOptions(proxy) + })); + } + await Promise.all(promises2); + } + _ffPages() { + return Array.from(this._browser._ffPages.values()).filter((ffPage) => ffPage._browserContext === this); + } + possiblyUninitializedPages() { + return this._ffPages().map((ffPage) => ffPage._page); + } + async doCreateNewPage(markAsServerSideOnly) { + const { targetId } = await this._browser.session.send("Browser.newPage", { + browserContextId: this._browserContextId + }).catch((e) => { + if (e.message.includes("Failed to override timezone")) + throw new Error(`Invalid timezone ID: ${this._options.timezoneId}`); + throw e; + }); + const page = this._browser._ffPages.get(targetId)._page; + if (markAsServerSideOnly) + page.markAsServerSideOnly(); + return page; + } + async doGetCookies(urls) { + const { cookies } = await this._browser.session.send("Browser.getCookies", { browserContextId: this._browserContextId }); + return filterCookies(cookies.map((c) => { + const copy = { ...c }; + delete copy.size; + delete copy.session; + return copy; + }), urls); + } + async addCookies(cookies) { + const cc = rewriteCookies(cookies).map((c) => ({ + ...c, + expires: c.expires === -1 ? void 0 : c.expires + })); + await this._browser.session.send("Browser.setCookies", { browserContextId: this._browserContextId, cookies: cc }); + } + async doClearCookies() { + await this._browser.session.send("Browser.clearCookies", { browserContextId: this._browserContextId }); + } + async doGrantPermissions(origin, permissions) { + const webPermissionToProtocol = /* @__PURE__ */ new Map([ + ["geolocation", "geo"], + ["persistent-storage", "persistent-storage"], + ["push", "push"], + ["notifications", "desktop-notification"] + ]); + const filtered = permissions.map((permission) => { + const protocolPermission = webPermissionToProtocol.get(permission); + if (!protocolPermission) + throw new Error("Unknown permission: " + permission); + return protocolPermission; + }); + await this._browser.session.send("Browser.grantPermissions", { origin, browserContextId: this._browserContextId, permissions: filtered }); + } + async doClearPermissions() { + await this._browser.session.send("Browser.resetPermissions", { browserContextId: this._browserContextId }); + } + async setGeolocation(geolocation) { + verifyGeolocation(geolocation); + this._options.geolocation = geolocation; + await this._browser.session.send("Browser.setGeolocationOverride", { browserContextId: this._browserContextId, geolocation: geolocation || null }); + } + async setExtraHTTPHeaders(headers) { + this._options.extraHTTPHeaders = headers; + let allHeaders = this._options.extraHTTPHeaders; + if (this._options.locale) + allHeaders = mergeHeaders([allHeaders, singleHeader("Accept-Language", this._options.locale)]); + await this._browser.session.send("Browser.setExtraHTTPHeaders", { browserContextId: this._browserContextId, headers: allHeaders }); + } + async setUserAgent(userAgent) { + await this._browser.session.send("Browser.setUserAgentOverride", { browserContextId: this._browserContextId, userAgent: userAgent || null }); + } + async setOffline(offline) { + this._options.offline = offline; + await this._browser.session.send("Browser.setOnlineOverride", { browserContextId: this._browserContextId, override: offline ? "offline" : "online" }); + } + async doSetHTTPCredentials(httpCredentials) { + this._options.httpCredentials = httpCredentials; + let credentials = null; + if (httpCredentials) { + const { username, password, origin } = httpCredentials; + credentials = { username, password, origin }; + } + await this._browser.session.send("Browser.setHTTPCredentials", { browserContextId: this._browserContextId, credentials }); + } + async doAddInitScript(initScript) { + await this._updateInitScripts(); + } + async doRemoveInitScripts(initScripts) { + await this._updateInitScripts(); + } + async _updateInitScripts() { + const bindingScripts = [...this._pageBindings.values()].map((binding2) => binding2.initScript.source); + if (this.bindingsInitScript) + bindingScripts.unshift(this.bindingsInitScript.source); + const initScripts = this.initScripts.map((script) => script.source); + await this._browser.session.send("Browser.setInitScripts", { browserContextId: this._browserContextId, scripts: [...bindingScripts, ...initScripts].map((script) => ({ script })) }); + } + async doUpdateRequestInterception() { + await Promise.all([ + this._browser.session.send("Browser.setRequestInterception", { browserContextId: this._browserContextId, enabled: this.requestInterceptors.length > 0 }), + this._browser.session.send("Browser.setCacheDisabled", { browserContextId: this._browserContextId, cacheDisabled: this.requestInterceptors.length > 0 }) + ]); + } + async doExposePlaywrightBinding() { + this._browser.session.send("Browser.addBinding", { browserContextId: this._browserContextId, name: PageBinding.kBindingName, script: "" }); + } + onClosePersistent() { + } + async clearCache() { + await this._browser.session.send("Browser.clearCache"); + } + async doClose(reason) { + if (!this._browserContextId) { + if (this._options.recordVideo) { + await this._browser.session.send("Browser.setVideoRecordingOptions", { + options: void 0, + browserContextId: this._browserContextId + }); + } + await this._browser.close({ reason }); + } else { + await this._browser.session.send("Browser.removeBrowserContext", { browserContextId: this._browserContextId }); + this._browser._contexts.delete(this._browserContextId); + } + } + async cancelDownload(uuid) { + await this._browser.session.send("Browser.cancelDownload", { uuid }); + } +} +function toJugglerProxyOptions(proxy) { + const proxyServer = new URL(proxy.server); + let port = parseInt(proxyServer.port, 10); + let type2 = "http"; + if (proxyServer.protocol === "socks5:") + type2 = "socks"; + else if (proxyServer.protocol === "socks4:") + type2 = "socks4"; + else if (proxyServer.protocol === "https:") + type2 = "https"; + if (proxyServer.port === "") { + if (proxyServer.protocol === "http:") + port = 80; + else if (proxyServer.protocol === "https:") + port = 443; + } + return { + type: type2, + bypass: proxy.bypass ? proxy.bypass.split(",").map((domain) => domain.trim()) : [], + host: proxyServer.hostname, + port, + username: proxy.username, + password: proxy.password + }; +} +const kBandaidFirefoxUserPrefs = {}; +class Firefox extends BrowserType$1 { + constructor(parent) { + super(parent, "firefox"); + } + connectToTransport(transport, options2) { + return FFBrowser.connect(this.attribution.playwright, transport, options2); + } + doRewriteStartupLog(error2) { + if (!error2.logs) + return error2; + if (error2.logs.includes(`as root in a regular user's session is not supported.`)) + error2.logs = "\n" + wrapInASCIIBox(`Firefox is unable to launch if the $HOME folder isn't owned by the current user. +Workaround: Set the HOME=/root environment variable${define_process_env_default.GITHUB_ACTION ? " in your GitHub Actions workflow file" : ""} when running Playwright.`, 1); + if (error2.logs.includes("no DISPLAY environment variable specified")) + error2.logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + return error2; + } + amendEnvironment(env, userDataDir, executable, browserArguments) { + if (!path.isAbsolute(os.homedir())) + throw new Error(`Cannot launch Firefox with relative home directory. Did you set ${os.platform() === "win32" ? "USERPROFILE" : "HOME"} to a relative path?`); + if (os.platform() === "linux") { + return { ...env, SNAP_NAME: void 0, SNAP_INSTANCE_NAME: void 0 }; + } + return env; + } + attemptToGracefullyCloseBrowser(transport) { + const message = { method: "Browser.close", params: {}, id: kBrowserCloseMessageId$1 }; + transport.send(message); + } + defaultArgs(options2, isPersistent, userDataDir) { + const { args = [], headless } = options2; + const userDataDirArg = args.find((arg) => arg.startsWith("-profile") || arg.startsWith("--profile")); + if (userDataDirArg) + throw this._createUserDataDirArgMisuseError("--profile"); + if (args.find((arg) => arg.startsWith("-juggler"))) + throw new Error("Use the port parameter instead of -juggler argument"); + const firefoxArguments = ["-no-remote"]; + if (headless) { + firefoxArguments.push("-headless"); + } else { + firefoxArguments.push("-wait-for-browser"); + firefoxArguments.push("-foreground"); + } + firefoxArguments.push(`-profile`, userDataDir); + firefoxArguments.push("-juggler-pipe"); + firefoxArguments.push(...args); + if (isPersistent) + firefoxArguments.push("about:blank"); + else + firefoxArguments.push("-silent"); + return firefoxArguments; + } + readyState(options2) { + return new JugglerReadyState(); + } +} +class JugglerReadyState extends BrowserReadyState { + onBrowserOutput(message) { + if (message.includes("Juggler listening to the pipe")) + this._wsEndpoint.resolve(void 0); + } +} +const kBrowserCloseMessageId = -9999; +const kPageProxyMessageReceived = Symbol("kPageProxyMessageReceived"); +class WKConnection { + constructor(transport, onDisconnect, protocolLogger, browserLogsCollector) { + this._lastId = 0; + this._closed = false; + this._transport = transport; + this._onDisconnect = onDisconnect; + this._protocolLogger = protocolLogger; + this._browserLogsCollector = browserLogsCollector; + this.browserSession = new WKSession(this, "", (message) => { + this.rawSend(message); + }); + this._transport.onmessage = this._dispatchMessage.bind(this); + this._transport.onclose = this._onClose.bind(this); + } + nextMessageId() { + return ++this._lastId; + } + rawSend(message) { + this._protocolLogger("send", message); + this._transport.send(message); + } + _dispatchMessage(message) { + this._protocolLogger("receive", message); + if (message.id === kBrowserCloseMessageId) + return; + if (message.pageProxyId) { + const payload = { message, pageProxyId: message.pageProxyId }; + this.browserSession.dispatchMessage({ method: kPageProxyMessageReceived, params: payload }); + return; + } + this.browserSession.dispatchMessage(message); + } + _onClose(reason) { + this._closed = true; + this._transport.onmessage = void 0; + this._transport.onclose = void 0; + this._browserDisconnectedLogs = helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason); + this.browserSession.dispose(); + this._onDisconnect(); + } + isClosed() { + return this._closed; + } + close() { + if (!this._closed) + this._transport.close(); + } +} +class WKSession extends eventsExports.EventEmitter { + constructor(connection, sessionId, rawSend) { + super(); + this._disposed = false; + this._callbacks = /* @__PURE__ */ new Map(); + this._crashed = false; + this.setMaxListeners(0); + this.connection = connection; + this.sessionId = sessionId; + this._rawSend = rawSend; + this.on = super.on; + this.off = super.removeListener; + this.addListener = super.addListener; + this.removeListener = super.removeListener; + this.once = super.once; + } + async send(method, params) { + if (this._crashed || this._disposed || this.connection._browserDisconnectedLogs) + throw new ProtocolError(this._crashed ? "crashed" : "closed", void 0, this.connection._browserDisconnectedLogs); + const id = this.connection.nextMessageId(); + const messageObj = { id, method, params }; + this._rawSend(messageObj); + return new Promise((resolve, reject) => { + this._callbacks.set(id, { resolve, reject, error: new ProtocolError("error", method) }); + }); + } + sendMayFail(method, params) { + return this.send(method, params).catch((error2) => debugLogger.log("error", error2)); + } + markAsCrashed() { + this._crashed = true; + } + isDisposed() { + return this._disposed; + } + dispose() { + for (const callback of this._callbacks.values()) { + callback.error.type = this._crashed ? "crashed" : "closed"; + callback.error.logs = this.connection._browserDisconnectedLogs; + callback.reject(callback.error); + } + this._callbacks.clear(); + this._disposed = true; + } + dispatchMessage(object) { + if (object.id && this._callbacks.has(object.id)) { + const callback = this._callbacks.get(object.id); + this._callbacks.delete(object.id); + if (object.error) { + callback.error.setMessage(object.error.message); + callback.reject(callback.error); + } else { + callback.resolve(object.result); + } + } else if (object.id && !object.error) { + assert(this.isDisposed()); + } else { + Promise.resolve().then(() => this.emit(object.method, object.params)); + } + } +} +async function getAccessibilityTree(session, needle) { + const objectId = needle ? needle._objectId : void 0; + const { axNode } = await session.send("Page.accessibilitySnapshot", { objectId }); + const tree = new WKAXNode(axNode); + return { + tree, + needle: needle ? tree._findNeedle() : null + }; +} +const WKRoleToARIARole = new Map(Object.entries({ + "TextField": "textbox" +})); +const WKUnhelpfulRoleDescriptions = new Map(Object.entries({ + "WebArea": "HTML content", + "Summary": "summary", + "DescriptionList": "description list", + "ImageMap": "image map", + "ListMarker": "list marker", + "Video": "video playback", + "Mark": "highlighted", + "contentinfo": "content information", + "Details": "details", + "DescriptionListDetail": "description", + "DescriptionListTerm": "term", + "alertdialog": "web alert dialog", + "dialog": "web dialog", + "status": "application status", + "tabpanel": "tab panel", + "application": "web application" +})); +class WKAXNode { + constructor(payload) { + this._payload = payload; + this._children = []; + for (const payload2 of this._payload.children || []) + this._children.push(new WKAXNode(payload2)); + } + children() { + return this._children; + } + _findNeedle() { + if (this._payload.found) + return this; + for (const child of this._children) { + const found = child._findNeedle(); + if (found) + return found; + } + return null; + } + isControl() { + switch (this._payload.role) { + case "button": + case "checkbox": + case "ColorWell": + case "combobox": + case "DisclosureTriangle": + case "listbox": + case "menu": + case "menubar": + case "menuitem": + case "menuitemcheckbox": + case "menuitemradio": + case "radio": + case "scrollbar": + case "searchbox": + case "slider": + case "spinbutton": + case "switch": + case "tab": + case "textbox": + case "TextField": + case "tree": + return true; + default: + return false; + } + } + _isTextControl() { + switch (this._payload.role) { + case "combobox": + case "searchfield": + case "textbox": + case "TextField": + return true; + } + return false; + } + _name() { + if (this._payload.role === "text") + return this._payload.value || ""; + return this._payload.name || ""; + } + isInteresting(insideControl) { + const { role, focusable } = this._payload; + const name = this._name(); + if (role === "ScrollArea") + return false; + if (role === "WebArea") + return true; + if (focusable || role === "MenuListOption") + return true; + if (this.isControl()) + return true; + if (insideControl) + return false; + return this.isLeafNode() && !!name; + } + _hasRedundantTextChild() { + if (this._children.length !== 1) + return false; + const child = this._children[0]; + return child._payload.role === "text" && this._payload.name === child._payload.value; + } + isLeafNode() { + if (!this._children.length) + return true; + if (this._isTextControl()) + return true; + if (this._hasRedundantTextChild()) + return true; + return false; + } + serialize() { + const node2 = { + role: WKRoleToARIARole.get(this._payload.role) || this._payload.role, + name: this._name() + }; + if ("description" in this._payload && this._payload.description !== node2.name) + node2.description = this._payload.description; + if ("roledescription" in this._payload) { + const roledescription = this._payload.roledescription; + if (roledescription !== this._payload.role && WKUnhelpfulRoleDescriptions.get(this._payload.role) !== roledescription) + node2.roledescription = roledescription; + } + if ("value" in this._payload && this._payload.role !== "text") { + if (typeof this._payload.value === "string") + node2.valueString = this._payload.value; + else if (typeof this._payload.value === "number") + node2.valueNumber = this._payload.value; + } + if ("checked" in this._payload) + node2.checked = this._payload.checked === "true" ? "checked" : this._payload.checked === "false" ? "unchecked" : "mixed"; + if ("pressed" in this._payload) + node2.pressed = this._payload.pressed === "true" ? "pressed" : this._payload.pressed === "false" ? "released" : "mixed"; + const userStringProperties = [ + "keyshortcuts", + "valuetext" + ]; + for (const userStringProperty of userStringProperties) { + if (!(userStringProperty in this._payload)) + continue; + node2[userStringProperty] = this._payload[userStringProperty]; + } + const booleanProperties = [ + "disabled", + "expanded", + "focused", + "modal", + "multiselectable", + "readonly", + "required", + "selected" + ]; + for (const booleanProperty of booleanProperties) { + if (booleanProperty === "focused" && (this._payload.role === "WebArea" || this._payload.role === "ScrollArea")) + continue; + const value = this._payload[booleanProperty]; + if (!value) + continue; + node2[booleanProperty] = value; + } + const numericalProperties = [ + "level", + "valuemax", + "valuemin" + ]; + for (const numericalProperty of numericalProperties) { + if (!(numericalProperty in this._payload)) + continue; + node2[numericalProperty] = this._payload[numericalProperty]; + } + const tokenProperties = [ + "autocomplete", + "haspopup", + "invalid" + ]; + for (const tokenProperty of tokenProperties) { + const value = this._payload[tokenProperty]; + if (!value || value === "false") + continue; + node2[tokenProperty] = value; + } + const orientationIsApplicable = /* @__PURE__ */ new Set([ + "ScrollArea", + "scrollbar", + "listbox", + "combobox", + "menu", + "tree", + "separator", + "slider", + "tablist", + "toolbar" + ]); + if (this._payload.orientation && orientationIsApplicable.has(this._payload.role)) + node2.orientation = this._payload.orientation; + return node2; + } +} +class WKExecutionContext { + constructor(session, contextId) { + this._session = session; + this._contextId = contextId; + } + async rawEvaluateJSON(expression) { + try { + const response2 = await this._session.send("Runtime.evaluate", { + expression, + contextId: this._contextId, + returnByValue: true + }); + if (response2.wasThrown) + throw new JavaScriptErrorInEvaluate(response2.result.description); + return response2.result.value; + } catch (error2) { + throw rewriteError(error2); + } + } + async rawEvaluateHandle(context, expression) { + try { + const response2 = await this._session.send("Runtime.evaluate", { + expression, + contextId: this._contextId, + returnByValue: false + }); + if (response2.wasThrown) + throw new JavaScriptErrorInEvaluate(response2.result.description); + return createHandle(context, response2.result); + } catch (error2) { + throw rewriteError(error2); + } + } + async evaluateWithArguments(expression, returnByValue, utilityScript, values, handles) { + try { + const response2 = await this._session.send("Runtime.callFunctionOn", { + functionDeclaration: expression, + objectId: utilityScript._objectId, + arguments: [ + { objectId: utilityScript._objectId }, + ...values.map((value) => ({ value })), + ...handles.map((handle) => ({ objectId: handle._objectId })) + ], + returnByValue, + emulateUserGesture: true, + awaitPromise: true + }); + if (response2.wasThrown) + throw new JavaScriptErrorInEvaluate(response2.result.description); + if (returnByValue) + return parseEvaluationResultValue(response2.result.value); + return createHandle(utilityScript._context, response2.result); + } catch (error2) { + throw rewriteError(error2); + } + } + async getProperties(object) { + const response2 = await this._session.send("Runtime.getProperties", { + objectId: object._objectId, + ownProperties: true + }); + const result = /* @__PURE__ */ new Map(); + for (const property of response2.properties) { + if (!property.enumerable || !property.value) + continue; + result.set(property.name, createHandle(object._context, property.value)); + } + return result; + } + async releaseHandle(handle) { + if (!handle._objectId) + return; + await this._session.send("Runtime.releaseObject", { objectId: handle._objectId }); + } +} +function potentiallyUnserializableValue(remoteObject) { + const value = remoteObject.value; + const isUnserializable = remoteObject.type === "number" && ["NaN", "-Infinity", "Infinity", "-0"].includes(remoteObject.description); + return isUnserializable ? parseUnserializableValue(remoteObject.description) : value; +} +function rewriteError(error2) { + if (error2.message.includes("Object has too long reference chain")) + throw new Error("Cannot serialize result: object reference chain is too long."); + if (!isJavaScriptErrorInEvaluate(error2) && !isSessionClosedError(error2)) + return new Error("Execution context was destroyed, most likely because of a navigation."); + return error2; +} +function renderPreview(object) { + if (object.type === "undefined") + return "undefined"; + if ("value" in object) + return String(object.value); + if (object.description === "Object" && object.preview) { + const tokens = []; + for (const { name, value } of object.preview.properties) + tokens.push(`${name}: ${value}`); + return `{${tokens.join(", ")}}`; + } + if (object.subtype === "array" && object.preview) + return sparseArrayToString(object.preview.properties); + return object.description; +} +function createHandle(context, remoteObject) { + if (remoteObject.subtype === "node") { + assert(context instanceof FrameExecutionContext); + return new ElementHandle$1(context, remoteObject.objectId); + } + const isPromise = remoteObject.className === "Promise"; + return new JSHandle$1(context, isPromise ? "promise" : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject)); +} +function toModifiersMask(modifiers) { + let mask = 0; + if (modifiers.has("Shift")) + mask |= 1; + if (modifiers.has("Control")) + mask |= 2; + if (modifiers.has("Alt")) + mask |= 4; + if (modifiers.has("Meta")) + mask |= 8; + return mask; +} +function toButtonsMask(buttons) { + let mask = 0; + if (buttons.has("left")) + mask |= 1; + if (buttons.has("right")) + mask |= 2; + if (buttons.has("middle")) + mask |= 4; + return mask; +} +class RawKeyboardImpl4 { + constructor(session) { + this._pageProxySession = session; + } + setSession(session) { + this._session = session; + } + async keydown(modifiers, keyName, description, autoRepeat) { + const parts = []; + for (const modifier of ["Shift", "Control", "Alt", "Meta"]) { + if (modifiers.has(modifier)) + parts.push(modifier); + } + const { code, keyCode, key: key2, text } = description; + parts.push(code); + const shortcut = parts.join("+"); + let commands = macEditingCommands[shortcut]; + if (isString(commands)) + commands = [commands]; + await this._pageProxySession.send("Input.dispatchKeyEvent", { + type: "keyDown", + modifiers: toModifiersMask(modifiers), + windowsVirtualKeyCode: keyCode, + code, + key: key2, + text, + unmodifiedText: text, + autoRepeat, + macCommands: commands, + isKeypad: description.location === keypadLocation + }); + } + async keyup(modifiers, keyName, description) { + const { code, key: key2 } = description; + await this._pageProxySession.send("Input.dispatchKeyEvent", { + type: "keyUp", + modifiers: toModifiersMask(modifiers), + key: key2, + windowsVirtualKeyCode: description.keyCode, + code, + isKeypad: description.location === keypadLocation + }); + } + async sendText(text) { + await this._session.send("Page.insertText", { text }); + } +} +class RawMouseImpl4 { + constructor(session) { + this._pageProxySession = session; + } + setSession(session) { + this._session = session; + } + async move(x, y, button, buttons, modifiers, forClick) { + await this._pageProxySession.send("Input.dispatchMouseEvent", { + type: "move", + button, + buttons: toButtonsMask(buttons), + x, + y, + modifiers: toModifiersMask(modifiers) + }); + } + async down(x, y, button, buttons, modifiers, clickCount) { + await this._pageProxySession.send("Input.dispatchMouseEvent", { + type: "down", + button, + buttons: toButtonsMask(buttons), + x, + y, + modifiers: toModifiersMask(modifiers), + clickCount + }); + } + async up(x, y, button, buttons, modifiers, clickCount) { + await this._pageProxySession.send("Input.dispatchMouseEvent", { + type: "up", + button, + buttons: toButtonsMask(buttons), + x, + y, + modifiers: toModifiersMask(modifiers), + clickCount + }); + } + async wheel(x, y, buttons, modifiers, deltaX, deltaY) { + var _a2; + if ((_a2 = this._page) == null ? void 0 : _a2.browserContext._options.isMobile) + throw new Error("Mouse wheel is not supported in mobile WebKit"); + await this._session.send("Page.updateScrollingState"); + await this._page.mainFrame().evaluateExpression(`new Promise(requestAnimationFrame)`, { world: "utility" }); + await this._pageProxySession.send("Input.dispatchWheelEvent", { + x, + y, + deltaX, + deltaY, + modifiers: toModifiersMask(modifiers) + }); + } + setPage(page) { + this._page = page; + } +} +class RawTouchscreenImpl4 { + constructor(session) { + this._pageProxySession = session; + } + async tap(x, y, modifiers) { + await this._pageProxySession.send("Input.dispatchTapEvent", { + x, + y, + modifiers: toModifiersMask(modifiers) + }); + } +} +const errorReasons = { + "aborted": "Cancellation", + "accessdenied": "AccessControl", + "addressunreachable": "General", + "blockedbyclient": "Cancellation", + "blockedbyresponse": "General", + "connectionaborted": "General", + "connectionclosed": "General", + "connectionfailed": "General", + "connectionrefused": "General", + "connectionreset": "General", + "internetdisconnected": "General", + "namenotresolved": "General", + "timedout": "Timeout", + "failed": "General" +}; +class WKInterceptableRequest { + constructor(session, frame, event, redirectedFrom, documentId) { + this._session = session; + this._requestId = event.requestId; + const resourceType = event.type ? event.type.toLowerCase() : redirectedFrom ? redirectedFrom.request.resourceType() : "other"; + let postDataBuffer = null; + this._timestamp = event.timestamp; + this._wallTime = event.walltime * 1e3; + if (event.request.postData) + postDataBuffer = Buffer.from(event.request.postData, "base64"); + this.request = new Request$1( + frame._page.browserContext, + frame, + null, + (redirectedFrom == null ? void 0 : redirectedFrom.request) || null, + documentId, + event.request.url, + resourceType, + event.request.method, + postDataBuffer, + headersObjectToArray(event.request.headers) + ); + } + adoptRequestFromNewProcess(newSession, requestId) { + this._session = newSession; + this._requestId = requestId; + } + createResponse(responsePayload) { + const getResponseBody = async () => { + const response22 = await this._session.send("Network.getResponseBody", { requestId: this._requestId }); + return Buffer.from(response22.body, response22.base64Encoded ? "base64" : "utf8"); + }; + const timingPayload = responsePayload.timing; + const timing = { + startTime: this._wallTime, + domainLookupStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.domainLookupStart) : -1, + domainLookupEnd: timingPayload ? wkMillisToRoundishMillis(timingPayload.domainLookupEnd) : -1, + connectStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.connectStart) : -1, + secureConnectionStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.secureConnectionStart) : -1, + connectEnd: timingPayload ? wkMillisToRoundishMillis(timingPayload.connectEnd) : -1, + requestStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.requestStart) : -1, + responseStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.responseStart) : -1 + }; + const setCookieSeparator = process.platform === "darwin" ? "," : "playwright-set-cookie-separator"; + const response2 = new Response$1(this.request, responsePayload.status, responsePayload.statusText, headersObjectToArray(responsePayload.headers, ",", setCookieSeparator), timing, getResponseBody, responsePayload.source === "service-worker"); + response2.setRawResponseHeaders(null); + response2.setTransferSize(null); + if (responsePayload.requestHeaders && Object.keys(responsePayload.requestHeaders).length) { + const headers = { ...responsePayload.requestHeaders }; + if (!headers["host"]) + headers["Host"] = new URL(this.request.url()).host; + this.request.setRawRequestHeaders(headersObjectToArray(headers)); + } else { + this.request.setRawRequestHeaders(null); + } + return response2; + } +} +class WKRouteImpl { + constructor(session, requestId) { + this._session = session; + this._requestId = requestId; + } + async abort(errorCode) { + const errorType = errorReasons[errorCode]; + assert(errorType, "Unknown error code: " + errorCode); + await this._session.sendMayFail("Network.interceptRequestWithError", { requestId: this._requestId, errorType }); + } + async fulfill(response2) { + if (300 <= response2.status && response2.status < 400) + throw new Error("Cannot fulfill with redirect status: " + response2.status); + let mimeType = response2.isBase64 ? "application/octet-stream" : "text/plain"; + const headers = headersArrayToObject( + response2.headers, + true + /* lowerCase */ + ); + const contentType = headers["content-type"]; + if (contentType) + mimeType = contentType.split(";")[0].trim(); + await this._session.sendMayFail("Network.interceptRequestWithResponse", { + requestId: this._requestId, + status: response2.status, + statusText: statusText(response2.status), + mimeType, + headers, + base64Encoded: response2.isBase64, + content: response2.body + }); + } + async continue(overrides) { + await this._session.sendMayFail("Network.interceptWithRequest", { + requestId: this._requestId, + url: overrides.url, + method: overrides.method, + headers: overrides.headers ? headersArrayToObject( + overrides.headers, + false + /* lowerCase */ + ) : void 0, + postData: overrides.postData ? Buffer.from(overrides.postData).toString("base64") : void 0 + }); + } +} +function wkMillisToRoundishMillis(value) { + if (value === -1e3) + return -1; + if (value <= 0) { + return -1; + } + return (value * 1e3 | 0) / 1e3; +} +class WKProvisionalPage { + constructor(session, page) { + var _a2; + this._sessionListeners = []; + this._mainFrameId = null; + this._session = session; + this._wkPage = page; + this._coopNavigationRequest = (_a2 = page._page.mainFrame().pendingDocument()) == null ? void 0 : _a2.request; + const overrideFrameId = (handler) => { + return (payload) => { + if (payload.frameId) + payload.frameId = this._wkPage._page.frameManager.mainFrame()._id; + handler(payload); + }; + }; + const wkPage = this._wkPage; + this._sessionListeners = [ + eventsHelper.addEventListener(session, "Network.requestWillBeSent", overrideFrameId((e) => this._onRequestWillBeSent(e))), + eventsHelper.addEventListener(session, "Network.requestIntercepted", overrideFrameId((e) => wkPage._onRequestIntercepted(session, e))), + eventsHelper.addEventListener(session, "Network.responseReceived", overrideFrameId((e) => wkPage._onResponseReceived(session, e))), + eventsHelper.addEventListener(session, "Network.loadingFinished", overrideFrameId((e) => this._onLoadingFinished(e))), + eventsHelper.addEventListener(session, "Network.loadingFailed", overrideFrameId((e) => this._onLoadingFailed(e))) + ]; + this.initializationPromise = this._wkPage._initializeSession(session, true, ({ frameTree }) => this._handleFrameTree(frameTree)); + } + coopNavigationRequest() { + return this._coopNavigationRequest; + } + dispose() { + eventsHelper.removeEventListeners(this._sessionListeners); + } + commit() { + assert(this._mainFrameId); + this._wkPage._onFrameAttached(this._mainFrameId, null); + } + _onRequestWillBeSent(event) { + if (this._coopNavigationRequest && this._coopNavigationRequest.url() === event.request.url) { + this._wkPage._adoptRequestFromNewProcess(this._coopNavigationRequest, this._session, event.requestId); + return; + } + this._wkPage._onRequestWillBeSent(this._session, event); + } + _onLoadingFinished(event) { + this._coopNavigationRequest = void 0; + this._wkPage._onLoadingFinished(event); + } + _onLoadingFailed(event) { + this._coopNavigationRequest = void 0; + this._wkPage._onLoadingFailed(this._session, event); + } + _handleFrameTree(frameTree) { + assert(!frameTree.frame.parentId); + this._mainFrameId = frameTree.frame.id; + } +} +class WKWorkers { + constructor(page) { + this._sessionListeners = []; + this._workerSessions = /* @__PURE__ */ new Map(); + this._page = page; + } + setSession(session) { + eventsHelper.removeEventListeners(this._sessionListeners); + this.clear(); + this._sessionListeners = [ + eventsHelper.addEventListener(session, "Worker.workerCreated", (event) => { + const worker = new Worker$1(this._page, event.url); + const workerSession = new WKSession(session.connection, event.workerId, (message) => { + session.send("Worker.sendMessageToWorker", { + workerId: event.workerId, + message: JSON.stringify(message) + }).catch((e) => { + workerSession.dispatchMessage({ id: message.id, error: { message: e.message } }); + }); + }); + this._workerSessions.set(event.workerId, workerSession); + worker.createExecutionContext(new WKExecutionContext(workerSession, void 0)); + this._page.addWorker(event.workerId, worker); + workerSession.on("Console.messageAdded", (event2) => this._onConsoleMessage(worker, event2)); + Promise.all([ + workerSession.send("Runtime.enable"), + workerSession.send("Console.enable"), + session.send("Worker.initialized", { workerId: event.workerId }) + ]).catch((e) => { + this._page.removeWorker(event.workerId); + }); + }), + eventsHelper.addEventListener(session, "Worker.dispatchMessageFromWorker", (event) => { + const workerSession = this._workerSessions.get(event.workerId); + if (!workerSession) + return; + workerSession.dispatchMessage(JSON.parse(event.message)); + }), + eventsHelper.addEventListener(session, "Worker.workerTerminated", (event) => { + const workerSession = this._workerSessions.get(event.workerId); + if (!workerSession) + return; + workerSession.dispose(); + this._workerSessions.delete(event.workerId); + this._page.removeWorker(event.workerId); + }) + ]; + } + clear() { + this._page.clearWorkers(); + this._workerSessions.clear(); + } + async initializeSession(session) { + await session.send("Worker.enable"); + } + async _onConsoleMessage(worker, event) { + const { type: type2, level, text, parameters, url: url2, line: lineNumber, column: columnNumber } = event.message; + let derivedType = type2 || ""; + if (type2 === "log") + derivedType = level; + else if (type2 === "timing") + derivedType = "timeEnd"; + const handles = (parameters || []).map((p) => { + return createHandle(worker.existingExecutionContext, p); + }); + const location2 = { + url: url2 || "", + lineNumber: (lineNumber || 1) - 1, + columnNumber: (columnNumber || 1) - 1 + }; + this._page.addConsoleMessage(derivedType, handles, location2, handles.length ? void 0 : text); + } +} +const UTILITY_WORLD_NAME = "__playwright_utility_world__"; +class WKPage { + constructor(browserContext, pageProxySession, opener) { + this._provisionalPage = null; + this._requestIdToRequest = /* @__PURE__ */ new Map(); + this._requestIdToRequestWillBeSentEvent = /* @__PURE__ */ new Map(); + this._sessionListeners = []; + this._firstNonInitialNavigationCommittedFulfill = () => { + }; + this._firstNonInitialNavigationCommittedReject = (e) => { + }; + this._lastConsoleMessage = null; + this._requestIdToResponseReceivedPayloadEvent = /* @__PURE__ */ new Map(); + this._recordingVideoFile = null; + this._screencastGeneration = 0; + this._pageProxySession = pageProxySession; + this._opener = opener; + this.rawKeyboard = new RawKeyboardImpl4(pageProxySession); + this.rawMouse = new RawMouseImpl4(pageProxySession); + this.rawTouchscreen = new RawTouchscreenImpl4(pageProxySession); + this._contextIdToContext = /* @__PURE__ */ new Map(); + this._page = new Page$1(this, browserContext); + this.rawMouse.setPage(this._page); + this._workers = new WKWorkers(this._page); + this._session = void 0; + this._browserContext = browserContext; + this._page.on(Page$1.Events.FrameDetached, (frame) => this._removeContextsForFrame(frame, false)); + this._eventListeners = [ + eventsHelper.addEventListener(this._pageProxySession, "Target.targetCreated", this._onTargetCreated.bind(this)), + eventsHelper.addEventListener(this._pageProxySession, "Target.targetDestroyed", this._onTargetDestroyed.bind(this)), + eventsHelper.addEventListener(this._pageProxySession, "Target.dispatchMessageFromTarget", this._onDispatchMessageFromTarget.bind(this)), + eventsHelper.addEventListener(this._pageProxySession, "Target.didCommitProvisionalTarget", this._onDidCommitProvisionalTarget.bind(this)), + eventsHelper.addEventListener(this._pageProxySession, "Screencast.screencastFrame", this._onScreencastFrame.bind(this)) + ]; + this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => { + this._firstNonInitialNavigationCommittedFulfill = f; + this._firstNonInitialNavigationCommittedReject = r; + }); + if (opener && !browserContext._options.noDefaultViewport && opener._nextWindowOpenPopupFeatures) { + const viewportSize = helper.getViewportSizeFromWindowFeatures(opener._nextWindowOpenPopupFeatures); + opener._nextWindowOpenPopupFeatures = void 0; + if (viewportSize) + this._page.setEmulatedSizeFromWindowOpen({ viewport: viewportSize, screen: viewportSize }); + } + } + async _initializePageProxySession() { + if (this._page.browserContext.isSettingStorageState()) + return; + const promises2 = [ + this._pageProxySession.send("Dialog.enable"), + this._pageProxySession.send("Emulation.setActiveAndFocused", { active: true }) + ]; + const contextOptions = this._browserContext._options; + if (contextOptions.javaScriptEnabled === false) + promises2.push(this._pageProxySession.send("Emulation.setJavaScriptEnabled", { enabled: false })); + promises2.push(this._updateViewport()); + promises2.push(this.updateHttpCredentials()); + if (this._browserContext._permissions.size) { + for (const [key2, value] of this._browserContext._permissions) + promises2.push(this._grantPermissions(key2, value)); + } + if (this._browserContext._options.recordVideo) { + const outputFile = path.join(this._browserContext._options.recordVideo.dir, createGuid() + ".webm"); + promises2.push(this._browserContext._ensureVideosPath().then(() => { + return this._startVideo({ + // validateBrowserContextOptions ensures correct video size. + ...this._browserContext._options.recordVideo.size, + outputFile + }); + })); + } + await Promise.all(promises2); + } + _setSession(session) { + eventsHelper.removeEventListeners(this._sessionListeners); + this._session = session; + this.rawKeyboard.setSession(session); + this.rawMouse.setSession(session); + this._addSessionListeners(); + this._workers.setSession(session); + } + // This method is called for provisional targets as well. The session passed as the parameter + // may be different from the current session and may be destroyed without becoming current. + async _initializeSession(session, provisional, resourceTreeHandler) { + await this._initializeSessionMayThrow(session, resourceTreeHandler).catch((e) => { + if (provisional && session.isDisposed()) + return; + if (this._session === session) + throw e; + }); + } + async _initializeSessionMayThrow(session, resourceTreeHandler) { + const [, frameTree] = await Promise.all([ + // Page agent must be enabled before Runtime. + session.send("Page.enable"), + session.send("Page.getResourceTree") + ]); + resourceTreeHandler(frameTree); + const promises2 = [ + // Resource tree should be received before first execution context. + session.send("Runtime.enable"), + session.send("Page.createUserWorld", { name: UTILITY_WORLD_NAME }).catch((_) => { + }), + // Worlds are per-process + session.send("Console.enable"), + session.send("Network.enable"), + this._workers.initializeSession(session) + ]; + if (this._page.browserContext.needsPlaywrightBinding()) + promises2.push(session.send("Runtime.addBinding", { name: PageBinding.kBindingName })); + if (this._page.needsRequestInterception()) { + promises2.push(session.send("Network.setInterceptionEnabled", { enabled: true })); + promises2.push(session.send("Network.setResourceCachingDisabled", { disabled: true })); + promises2.push(session.send("Network.addInterception", { url: ".*", stage: "request", isRegex: true })); + } + if (this._page.browserContext.isSettingStorageState()) { + await Promise.all(promises2); + return; + } + const contextOptions = this._browserContext._options; + if (contextOptions.userAgent) + promises2.push(this.updateUserAgent()); + const emulatedMedia = this._page.emulatedMedia(); + if (emulatedMedia.media || emulatedMedia.colorScheme || emulatedMedia.reducedMotion || emulatedMedia.forcedColors || emulatedMedia.contrast) + promises2.push(WKPage._setEmulateMedia(session, emulatedMedia.media, emulatedMedia.colorScheme, emulatedMedia.reducedMotion, emulatedMedia.forcedColors, emulatedMedia.contrast)); + const bootstrapScript = this._calculateBootstrapScript(); + if (bootstrapScript.length) + promises2.push(session.send("Page.setBootstrapScript", { source: bootstrapScript })); + this._page.frames().map((frame) => frame.evaluateExpression(bootstrapScript).catch((e) => { + })); + if (contextOptions.bypassCSP) + promises2.push(session.send("Page.setBypassCSP", { enabled: true })); + const emulatedSize = this._page.emulatedSize(); + if (emulatedSize) { + promises2.push(session.send("Page.setScreenSizeOverride", { + width: emulatedSize.screen.width, + height: emulatedSize.screen.height + })); + } + promises2.push(this.updateEmulateMedia()); + promises2.push(session.send("Network.setExtraHTTPHeaders", { headers: headersArrayToObject( + this._calculateExtraHTTPHeaders(), + false + /* lowerCase */ + ) })); + if (contextOptions.offline) + promises2.push(session.send("Network.setEmulateOfflineState", { offline: true })); + promises2.push(session.send("Page.setTouchEmulationEnabled", { enabled: !!contextOptions.hasTouch })); + if (contextOptions.timezoneId) { + promises2.push(session.send("Page.setTimeZone", { timeZone: contextOptions.timezoneId }).catch((e) => { + throw new Error(`Invalid timezone ID: ${contextOptions.timezoneId}`); + })); + } + if (this._page.fileChooserIntercepted()) + promises2.push(session.send("Page.setInterceptFileChooserDialog", { enabled: true })); + promises2.push(session.send("Page.overrideSetting", { setting: "DeviceOrientationEventEnabled", value: contextOptions.isMobile })); + promises2.push(session.send("Page.overrideSetting", { setting: "FullScreenEnabled", value: !contextOptions.isMobile })); + promises2.push(session.send("Page.overrideSetting", { setting: "NotificationsEnabled", value: !contextOptions.isMobile })); + promises2.push(session.send("Page.overrideSetting", { setting: "PointerLockEnabled", value: !contextOptions.isMobile })); + promises2.push(session.send("Page.overrideSetting", { setting: "InputTypeMonthEnabled", value: contextOptions.isMobile })); + promises2.push(session.send("Page.overrideSetting", { setting: "InputTypeWeekEnabled", value: contextOptions.isMobile })); + promises2.push(session.send("Page.overrideSetting", { setting: "FixedBackgroundsPaintRelativeToDocument", value: contextOptions.isMobile })); + await Promise.all(promises2); + } + _onDidCommitProvisionalTarget(event) { + const { oldTargetId, newTargetId } = event; + assert(this._provisionalPage); + assert(this._provisionalPage._session.sessionId === newTargetId, "Unknown new target: " + newTargetId); + assert(this._session.sessionId === oldTargetId, "Unknown old target: " + oldTargetId); + const newSession = this._provisionalPage._session; + this._provisionalPage.commit(); + this._provisionalPage.dispose(); + this._provisionalPage = null; + this._setSession(newSession); + } + _onTargetDestroyed(event) { + const { targetId, crashed } = event; + if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) { + this._maybeCancelCoopNavigationRequest(this._provisionalPage); + this._provisionalPage._session.dispose(); + this._provisionalPage.dispose(); + this._provisionalPage = null; + } else if (this._session.sessionId === targetId) { + this._session.dispose(); + eventsHelper.removeEventListeners(this._sessionListeners); + if (crashed) { + this._session.markAsCrashed(); + this._page._didCrash(); + } + } + } + didClose() { + this._pageProxySession.dispose(); + eventsHelper.removeEventListeners(this._sessionListeners); + eventsHelper.removeEventListeners(this._eventListeners); + if (this._session) + this._session.dispose(); + if (this._provisionalPage) { + this._provisionalPage._session.dispose(); + this._provisionalPage.dispose(); + this._provisionalPage = null; + } + this._firstNonInitialNavigationCommittedReject(new TargetClosedError$1()); + this._page._didClose(); + } + dispatchMessageToSession(message) { + this._pageProxySession.dispatchMessage(message); + } + handleProvisionalLoadFailed(event) { + if (!this._page.initializedOrUndefined()) { + this._firstNonInitialNavigationCommittedReject(new Error("Initial load failed")); + return; + } + if (!this._provisionalPage) + return; + let errorText = event.error; + if (errorText.includes("cancelled")) + errorText += "; maybe frame was detached?"; + this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, errorText, event.loaderId); + } + handleWindowOpen(event) { + this._nextWindowOpenPopupFeatures = event.windowFeatures; + } + async _onTargetCreated(event) { + var _a2; + const { targetInfo } = event; + const session = new WKSession(this._pageProxySession.connection, targetInfo.targetId, (message) => { + this._pageProxySession.send("Target.sendMessageToTarget", { + message: JSON.stringify(message), + targetId: targetInfo.targetId + }).catch((e) => { + session.dispatchMessage({ id: message.id, error: { message: e.message } }); + }); + }); + assert(targetInfo.type === "page", "Only page targets are expected in WebKit, received: " + targetInfo.type); + if (!targetInfo.isProvisional) { + assert(!this._page.initializedOrUndefined()); + let pageOrError; + try { + this._setSession(session); + await Promise.all([ + this._initializePageProxySession(), + this._initializeSession(session, false, ({ frameTree }) => this._handleFrameTree(frameTree)) + ]); + pageOrError = this._page; + } catch (e) { + pageOrError = e; + } + if (targetInfo.isPaused) + this._pageProxySession.sendMayFail("Target.resume", { targetId: targetInfo.targetId }); + if (pageOrError instanceof Page$1 && this._page.mainFrame().url() === "") { + try { + await this._firstNonInitialNavigationCommittedPromise; + } catch (e) { + pageOrError = e; + } + } else { + this._firstNonInitialNavigationCommittedPromise.catch(() => { + }); + } + this._page.reportAsNew((_a2 = this._opener) == null ? void 0 : _a2._page, pageOrError instanceof Page$1 ? void 0 : pageOrError); + } else { + assert(targetInfo.isProvisional); + assert(!this._provisionalPage); + this._provisionalPage = new WKProvisionalPage(session, this); + if (targetInfo.isPaused) { + this._provisionalPage.initializationPromise.then(() => { + this._pageProxySession.sendMayFail("Target.resume", { targetId: targetInfo.targetId }); + }); + } + } + } + _onDispatchMessageFromTarget(event) { + const { targetId, message } = event; + if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) + this._provisionalPage._session.dispatchMessage(JSON.parse(message)); + else if (this._session.sessionId === targetId) + this._session.dispatchMessage(JSON.parse(message)); + else + throw new Error("Unknown target: " + targetId); + } + _addSessionListeners() { + this._sessionListeners = [ + eventsHelper.addEventListener(this._session, "Page.frameNavigated", (event) => this._onFrameNavigated(event.frame, false)), + eventsHelper.addEventListener(this._session, "Page.navigatedWithinDocument", (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), + eventsHelper.addEventListener(this._session, "Page.frameAttached", (event) => this._onFrameAttached(event.frameId, event.parentFrameId)), + eventsHelper.addEventListener(this._session, "Page.frameDetached", (event) => this._onFrameDetached(event.frameId)), + eventsHelper.addEventListener(this._session, "Page.willCheckNavigationPolicy", (event) => this._onWillCheckNavigationPolicy(event.frameId)), + eventsHelper.addEventListener(this._session, "Page.didCheckNavigationPolicy", (event) => this._onDidCheckNavigationPolicy(event.frameId, event.cancel)), + eventsHelper.addEventListener(this._session, "Page.frameScheduledNavigation", (event) => this._onFrameScheduledNavigation(event.frameId, event.delay, event.targetIsCurrentFrame)), + eventsHelper.addEventListener(this._session, "Page.loadEventFired", (event) => this._page.frameManager.frameLifecycleEvent(event.frameId, "load")), + eventsHelper.addEventListener(this._session, "Page.domContentEventFired", (event) => this._page.frameManager.frameLifecycleEvent(event.frameId, "domcontentloaded")), + eventsHelper.addEventListener(this._session, "Runtime.executionContextCreated", (event) => this._onExecutionContextCreated(event.context)), + eventsHelper.addEventListener(this._session, "Runtime.bindingCalled", (event) => this._onBindingCalled(event.contextId, event.argument)), + eventsHelper.addEventListener(this._session, "Console.messageAdded", (event) => this._onConsoleMessage(event)), + eventsHelper.addEventListener(this._session, "Console.messageRepeatCountUpdated", (event) => this._onConsoleRepeatCountUpdated(event)), + eventsHelper.addEventListener(this._pageProxySession, "Dialog.javascriptDialogOpening", (event) => this._onDialog(event)), + eventsHelper.addEventListener(this._session, "Page.fileChooserOpened", (event) => this._onFileChooserOpened(event)), + eventsHelper.addEventListener(this._session, "Network.requestWillBeSent", (e) => this._onRequestWillBeSent(this._session, e)), + eventsHelper.addEventListener(this._session, "Network.requestIntercepted", (e) => this._onRequestIntercepted(this._session, e)), + eventsHelper.addEventListener(this._session, "Network.responseReceived", (e) => this._onResponseReceived(this._session, e)), + eventsHelper.addEventListener(this._session, "Network.loadingFinished", (e) => this._onLoadingFinished(e)), + eventsHelper.addEventListener(this._session, "Network.loadingFailed", (e) => this._onLoadingFailed(this._session, e)), + eventsHelper.addEventListener(this._session, "Network.webSocketCreated", (e) => this._page.frameManager.onWebSocketCreated(e.requestId, e.url)), + eventsHelper.addEventListener(this._session, "Network.webSocketWillSendHandshakeRequest", (e) => this._page.frameManager.onWebSocketRequest(e.requestId)), + eventsHelper.addEventListener(this._session, "Network.webSocketHandshakeResponseReceived", (e) => this._page.frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), + eventsHelper.addEventListener(this._session, "Network.webSocketFrameSent", (e) => e.response.payloadData && this._page.frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), + eventsHelper.addEventListener(this._session, "Network.webSocketFrameReceived", (e) => e.response.payloadData && this._page.frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), + eventsHelper.addEventListener(this._session, "Network.webSocketClosed", (e) => this._page.frameManager.webSocketClosed(e.requestId)), + eventsHelper.addEventListener(this._session, "Network.webSocketFrameError", (e) => this._page.frameManager.webSocketError(e.requestId, e.errorMessage)) + ]; + } + async _updateState(method, params) { + await this._forAllSessions((session) => session.send(method, params).then()); + } + async _forAllSessions(callback) { + const sessions = [ + this._session + ]; + if (this._provisionalPage) + sessions.push(this._provisionalPage._session); + await Promise.all(sessions.map((session) => callback(session).catch((e) => { + }))); + } + _onWillCheckNavigationPolicy(frameId) { + if (this._provisionalPage) + return; + this._page.frameManager.frameRequestedNavigation(frameId); + } + _onDidCheckNavigationPolicy(frameId, cancel) { + if (!cancel) + return; + if (this._provisionalPage) + return; + this._page.frameManager.frameAbortedNavigation(frameId, "Navigation canceled by policy check"); + } + _onFrameScheduledNavigation(frameId, delay, targetIsCurrentFrame) { + if (targetIsCurrentFrame) + this._page.frameManager.frameRequestedNavigation(frameId); + } + _handleFrameTree(frameTree) { + this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null); + this._onFrameNavigated(frameTree.frame, true); + this._page.frameManager.frameLifecycleEvent(frameTree.frame.id, "domcontentloaded"); + this._page.frameManager.frameLifecycleEvent(frameTree.frame.id, "load"); + if (!frameTree.childFrames) + return; + for (const child of frameTree.childFrames) + this._handleFrameTree(child); + } + _onFrameAttached(frameId, parentFrameId) { + return this._page.frameManager.frameAttached(frameId, parentFrameId); + } + _onFrameNavigated(framePayload, initial) { + const frame = this._page.frameManager.frame(framePayload.id); + assert(frame); + this._removeContextsForFrame(frame, true); + if (!framePayload.parentId) + this._workers.clear(); + this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || "", framePayload.loaderId, initial); + if (!initial) + this._firstNonInitialNavigationCommittedFulfill(); + } + _onFrameNavigatedWithinDocument(frameId, url2) { + this._page.frameManager.frameCommittedSameDocumentNavigation(frameId, url2); + } + _onFrameDetached(frameId) { + this._page.frameManager.frameDetached(frameId); + } + _removeContextsForFrame(frame, notifyFrame) { + for (const [contextId, context] of this._contextIdToContext) { + if (context.frame === frame) { + this._contextIdToContext.delete(contextId); + if (notifyFrame) + frame._contextDestroyed(context); + } + } + } + _onExecutionContextCreated(contextPayload) { + if (this._contextIdToContext.has(contextPayload.id)) + return; + const frame = this._page.frameManager.frame(contextPayload.frameId); + if (!frame) + return; + const delegate = new WKExecutionContext(this._session, contextPayload.id); + let worldName = null; + if (contextPayload.type === "normal") + worldName = "main"; + else if (contextPayload.type === "user" && contextPayload.name === UTILITY_WORLD_NAME) + worldName = "utility"; + const context = new FrameExecutionContext(delegate, frame, worldName); + if (worldName) + frame._contextCreated(worldName, context); + this._contextIdToContext.set(contextPayload.id, context); + } + async _onBindingCalled(contextId, argument2) { + const pageOrError = await this._page.waitForInitializedOrError(); + if (!(pageOrError instanceof Error)) { + const context = this._contextIdToContext.get(contextId); + if (context) + await this._page.onBindingCalled(argument2, context); + } + } + async navigateFrame(frame, url2, referrer) { + if (this._pageProxySession.isDisposed()) + throw new TargetClosedError$1(); + const pageProxyId = this._pageProxySession.sessionId; + const result = await this._pageProxySession.connection.browserSession.send("Playwright.navigate", { url: url2, pageProxyId, frameId: frame._id, referrer }); + return { newDocumentId: result.loaderId }; + } + _onConsoleMessage(event) { + const { type: type2, level, text, parameters, url: url2, line: lineNumber, column: columnNumber, source: source2 } = event.message; + if (level === "error" && source2 === "javascript") { + const { name, message } = splitErrorMessage(text); + let stack; + if (event.message.stackTrace) { + stack = text + "\n" + event.message.stackTrace.callFrames.map((callFrame) => { + return ` at ${callFrame.functionName || "unknown"} (${callFrame.url}:${callFrame.lineNumber}:${callFrame.columnNumber})`; + }).join("\n"); + } else { + stack = ""; + } + this._lastConsoleMessage = null; + const error2 = new Error(message); + error2.stack = stack; + error2.name = name; + this._page.emitOnContextOnceInitialized(BrowserContext$1.Events.PageError, error2, this._page); + return; + } + let derivedType = type2 || ""; + if (type2 === "log") + derivedType = level; + else if (type2 === "timing") + derivedType = "timeEnd"; + const handles = []; + for (const p of parameters || []) { + let context; + if (p.objectId) { + const objectId = JSON.parse(p.objectId); + context = this._contextIdToContext.get(objectId.injectedScriptId); + } else { + context = [...this._contextIdToContext.values()].find((c) => c.frame === this._page.mainFrame()); + } + if (!context) + return; + handles.push(createHandle(context, p)); + } + this._lastConsoleMessage = { + derivedType, + text, + handles, + count: 0, + location: { + url: url2 || "", + lineNumber: (lineNumber || 1) - 1, + columnNumber: (columnNumber || 1) - 1 + } + }; + this._onConsoleRepeatCountUpdated({ count: 1 }); + } + _onConsoleRepeatCountUpdated(event) { + if (this._lastConsoleMessage) { + const { + derivedType, + text, + handles, + count, + location: location2 + } = this._lastConsoleMessage; + for (let i = count; i < event.count; ++i) + this._page.addConsoleMessage(derivedType, handles, location2, handles.length ? void 0 : text); + this._lastConsoleMessage.count = event.count; + } + } + _onDialog(event) { + this._page.browserContext.dialogManager.dialogDidOpen(new Dialog$1( + this._page, + event.type, + event.message, + async (accept, promptText) => { + if (event.type === "beforeunload" && !accept) + this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, "navigation cancelled by beforeunload dialog"); + await this._pageProxySession.send("Dialog.handleJavaScriptDialog", { accept, promptText }); + }, + event.defaultPrompt + )); + } + async _onFileChooserOpened(event) { + let handle; + try { + const context = await this._page.frameManager.frame(event.frameId)._mainContext(); + handle = createHandle(context, event.element).asElement(); + } catch (e) { + return; + } + await this._page._onFileChooserOpened(handle); + } + static async _setEmulateMedia(session, mediaType, colorScheme, reducedMotion, forcedColors, contrast) { + const promises2 = []; + promises2.push(session.send("Page.setEmulatedMedia", { media: mediaType === "no-override" ? "" : mediaType })); + let appearance = void 0; + switch (colorScheme) { + case "light": + appearance = "Light"; + break; + case "dark": + appearance = "Dark"; + break; + case "no-override": + appearance = void 0; + break; + } + promises2.push(session.send("Page.overrideUserPreference", { name: "PrefersColorScheme", value: appearance })); + let reducedMotionWk = void 0; + switch (reducedMotion) { + case "reduce": + reducedMotionWk = "Reduce"; + break; + case "no-preference": + reducedMotionWk = "NoPreference"; + break; + case "no-override": + reducedMotionWk = void 0; + break; + } + promises2.push(session.send("Page.overrideUserPreference", { name: "PrefersReducedMotion", value: reducedMotionWk })); + let forcedColorsWk = void 0; + switch (forcedColors) { + case "active": + forcedColorsWk = "Active"; + break; + case "none": + forcedColorsWk = "None"; + break; + case "no-override": + forcedColorsWk = void 0; + break; + } + promises2.push(session.send("Page.setForcedColors", { forcedColors: forcedColorsWk })); + let contrastWk = void 0; + switch (contrast) { + case "more": + contrastWk = "More"; + break; + case "no-preference": + contrastWk = "NoPreference"; + break; + case "no-override": + contrastWk = void 0; + break; + } + promises2.push(session.send("Page.overrideUserPreference", { name: "PrefersContrast", value: contrastWk })); + await Promise.all(promises2); + } + async updateExtraHTTPHeaders() { + await this._updateState("Network.setExtraHTTPHeaders", { headers: headersArrayToObject( + this._calculateExtraHTTPHeaders(), + false + /* lowerCase */ + ) }); + } + _calculateExtraHTTPHeaders() { + const locale = this._browserContext._options.locale; + const headers = mergeHeaders([ + this._browserContext._options.extraHTTPHeaders, + this._page.extraHTTPHeaders(), + locale ? singleHeader("Accept-Language", locale) : void 0 + ]); + return headers; + } + async updateEmulateMedia() { + const emulatedMedia = this._page.emulatedMedia(); + const colorScheme = emulatedMedia.colorScheme; + const reducedMotion = emulatedMedia.reducedMotion; + const forcedColors = emulatedMedia.forcedColors; + const contrast = emulatedMedia.contrast; + await this._forAllSessions((session) => WKPage._setEmulateMedia(session, emulatedMedia.media, colorScheme, reducedMotion, forcedColors, contrast)); + } + async updateEmulatedViewportSize() { + var _a2; + this._browserContext._validateEmulatedViewport((_a2 = this._page.emulatedSize()) == null ? void 0 : _a2.viewport); + await this._updateViewport(); + } + async updateUserAgent() { + const contextOptions = this._browserContext._options; + this._updateState("Page.overrideUserAgent", { value: contextOptions.userAgent }); + } + async bringToFront() { + this._pageProxySession.send("Target.activate", { + targetId: this._session.sessionId + }); + } + async _updateViewport() { + const options2 = this._browserContext._options; + const emulatedSize = this._page.emulatedSize(); + if (!emulatedSize) + return; + const viewportSize = emulatedSize.viewport; + const screenSize = emulatedSize.screen; + const promises2 = [ + this._pageProxySession.send("Emulation.setDeviceMetricsOverride", { + width: viewportSize.width, + height: viewportSize.height, + fixedLayout: !!options2.isMobile, + deviceScaleFactor: options2.deviceScaleFactor || 1 + }), + this._session.send("Page.setScreenSizeOverride", { + width: screenSize.width, + height: screenSize.height + }) + ]; + if (options2.isMobile) { + const angle = viewportSize.width > viewportSize.height ? 90 : 0; + promises2.push(this._pageProxySession.send("Emulation.setOrientationOverride", { angle })); + } + await Promise.all(promises2); + } + async updateRequestInterception() { + const enabled = this._page.needsRequestInterception(); + await Promise.all([ + this._updateState("Network.setInterceptionEnabled", { enabled }), + this._updateState("Network.setResourceCachingDisabled", { disabled: enabled }), + this._updateState("Network.addInterception", { url: ".*", stage: "request", isRegex: true }) + ]); + } + async updateOffline() { + await this._updateState("Network.setEmulateOfflineState", { offline: !!this._browserContext._options.offline }); + } + async updateHttpCredentials() { + const credentials = this._browserContext._options.httpCredentials || { username: "", password: "", origin: "" }; + await this._pageProxySession.send("Emulation.setAuthCredentials", { username: credentials.username, password: credentials.password, origin: credentials.origin }); + } + async updateFileChooserInterception() { + const enabled = this._page.fileChooserIntercepted(); + await this._session.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => { + }); + } + async reload() { + await this._session.send("Page.reload"); + } + goBack() { + return this._session.send("Page.goBack").then(() => true).catch((error2) => { + if (error2 instanceof Error && error2.message.includes(`Protocol error (Page.goBack): Failed to go`)) + return false; + throw error2; + }); + } + goForward() { + return this._session.send("Page.goForward").then(() => true).catch((error2) => { + if (error2 instanceof Error && error2.message.includes(`Protocol error (Page.goForward): Failed to go`)) + return false; + throw error2; + }); + } + async requestGC() { + await this._session.send("Heap.gc"); + } + async addInitScript(initScript) { + await this._updateBootstrapScript(); + } + async removeInitScripts(initScripts) { + await this._updateBootstrapScript(); + } + async exposePlaywrightBinding() { + await this._updateState("Runtime.addBinding", { name: PageBinding.kBindingName }); + } + _calculateBootstrapScript() { + const scripts = []; + if (!this._page.browserContext._options.isMobile) { + scripts.push("delete window.orientation"); + scripts.push("delete window.ondevicemotion"); + scripts.push("delete window.ondeviceorientation"); + } + scripts.push('if (!window.safari) window.safari = { pushNotification: { toString() { return "[object SafariRemoteNotification]"; } } };'); + scripts.push("if (!window.GestureEvent) window.GestureEvent = function GestureEvent() {};"); + scripts.push(this._publicKeyCredentialScript()); + scripts.push(...this._page.allInitScripts().map((script) => script.source)); + return scripts.join(";\n"); + } + _publicKeyCredentialScript() { + function polyfill2() { + window.PublicKeyCredential ?? (window.PublicKeyCredential = { + async getClientCapabilities() { + return {}; + }, + async isConditionalMediationAvailable() { + return false; + }, + async isUserVerifyingPlatformAuthenticatorAvailable() { + return false; + } + }); + } + return `(${polyfill2.toString()})();`; + } + async _updateBootstrapScript() { + await this._updateState("Page.setBootstrapScript", { source: this._calculateBootstrapScript() }); + } + async closePage(runBeforeUnload) { + await this._stopVideo(); + await this._pageProxySession.sendMayFail("Target.close", { + targetId: this._session.sessionId, + runBeforeUnload + }); + } + async setBackgroundColor(color) { + await this._session.send("Page.setDefaultBackgroundColorOverride", { color }); + } + _toolbarHeight() { + var _a2; + if ((_a2 = this._page.browserContext._browser) == null ? void 0 : _a2.options.headful) + return hostPlatform === "mac10.15" ? 55 : 59; + return 0; + } + async _startVideo(options2) { + assert(!this._recordingVideoFile); + const { screencastId } = await this._pageProxySession.send("Screencast.startVideo", { + file: options2.outputFile, + width: options2.width, + height: options2.height, + toolbarHeight: this._toolbarHeight() + }); + this._recordingVideoFile = options2.outputFile; + this._browserContext._browser._videoStarted(this._browserContext, screencastId, options2.outputFile, this._page.waitForInitializedOrError()); + } + async _stopVideo() { + if (!this._recordingVideoFile) + return; + await this._pageProxySession.sendMayFail("Screencast.stopVideo"); + this._recordingVideoFile = null; + } + validateScreenshotDimension(side, omitDeviceScaleFactor) { + if (process.platform === "darwin") + return; + if (!omitDeviceScaleFactor && this._page.browserContext._options.deviceScaleFactor) + side = Math.ceil(side * this._page.browserContext._options.deviceScaleFactor); + if (side > 32767) + throw new Error("Cannot take screenshot larger than 32767 pixels on any dimension"); + } + async takeScreenshot(progress2, format, documentRect, viewportRect, quality, fitsViewport, scale) { + const rect = documentRect || viewportRect; + const omitDeviceScaleFactor = scale === "css"; + this.validateScreenshotDimension(rect.width, omitDeviceScaleFactor); + this.validateScreenshotDimension(rect.height, omitDeviceScaleFactor); + const result = await this._session.send("Page.snapshotRect", { ...rect, coordinateSystem: documentRect ? "Page" : "Viewport", omitDeviceScaleFactor }); + const prefix = "data:image/png;base64,"; + let buffer2 = Buffer.from(result.dataURL.substr(prefix.length), "base64"); + if (format === "jpeg") + buffer2 = jpegjs.encode(PNG.sync.read(buffer2), quality).data; + return buffer2; + } + async getContentFrame(handle) { + const nodeInfo = await this._session.send("DOM.describeNode", { + objectId: handle._objectId + }); + if (!nodeInfo.contentFrameId) + return null; + return this._page.frameManager.frame(nodeInfo.contentFrameId); + } + async getOwnerFrame(handle) { + if (!handle._objectId) + return null; + const nodeInfo = await this._session.send("DOM.describeNode", { + objectId: handle._objectId + }); + return nodeInfo.ownerFrameId || null; + } + async getBoundingBox(handle) { + const quads = await this.getContentQuads(handle); + if (!quads || !quads.length) + return null; + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + for (const quad of quads) { + for (const point of quad) { + minX = Math.min(minX, point.x); + maxX = Math.max(maxX, point.x); + minY = Math.min(minY, point.y); + maxY = Math.max(maxY, point.y); + } + } + return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; + } + async scrollRectIntoViewIfNeeded(handle, rect) { + return await this._session.send("DOM.scrollIntoViewIfNeeded", { + objectId: handle._objectId, + rect + }).then(() => "done").catch((e) => { + if (e instanceof Error && e.message.includes("Node does not have a layout object")) + return "error:notvisible"; + if (e instanceof Error && e.message.includes("Node is detached from document")) + return "error:notconnected"; + throw e; + }); + } + async setScreencastOptions(options2) { + if (options2) { + const so = { ...options2, toolbarHeight: this._toolbarHeight() }; + const { generation } = await this._pageProxySession.send("Screencast.startScreencast", so); + this._screencastGeneration = generation; + } else { + await this._pageProxySession.send("Screencast.stopScreencast"); + } + } + _onScreencastFrame(event) { + const generation = this._screencastGeneration; + this._page.throttleScreencastFrameAck(() => { + this._pageProxySession.send("Screencast.screencastFrameAck", { generation }).catch((e) => debugLogger.log("error", e)); + }); + const buffer2 = Buffer.from(event.data, "base64"); + this._page.emit(Page$1.Events.ScreencastFrame, { + buffer: buffer2, + width: event.deviceWidth, + height: event.deviceHeight + }); + } + rafCountForStablePosition() { + return process.platform === "win32" ? 5 : 1; + } + async getContentQuads(handle) { + const result = await this._session.sendMayFail("DOM.getContentQuads", { + objectId: handle._objectId + }); + if (!result) + return null; + return result.quads.map((quad) => [ + { x: quad[0], y: quad[1] }, + { x: quad[2], y: quad[3] }, + { x: quad[4], y: quad[5] }, + { x: quad[6], y: quad[7] } + ]); + } + async setInputFilePaths(handle, paths) { + const pageProxyId = this._pageProxySession.sessionId; + const objectId = handle._objectId; + await Promise.all([ + this._pageProxySession.connection.browserSession.send("Playwright.grantFileReadAccess", { pageProxyId, paths }), + this._session.send("DOM.setInputFiles", { objectId, paths }) + ]); + } + async adoptElementHandle(handle, to) { + const result = await this._session.sendMayFail("DOM.resolveNode", { + objectId: handle._objectId, + executionContextId: to.delegate._contextId + }); + if (!result || result.object.subtype === "null") + throw new Error(kUnableToAdoptErrorMessage); + return createHandle(to, result.object); + } + async getAccessibilityTree(needle) { + return getAccessibilityTree(this._session, needle); + } + async inputActionEpilogue() { + } + async resetForReuse() { + } + async getFrameElement(frame) { + const parent = frame.parentFrame(); + if (!parent) + throw new Error("Frame has been detached."); + const context = await parent._mainContext(); + const result = await this._session.send("DOM.resolveNode", { + frameId: frame._id, + executionContextId: context.delegate._contextId + }); + if (!result || result.object.subtype === "null") + throw new Error("Frame has been detached."); + return createHandle(context, result.object); + } + _maybeCancelCoopNavigationRequest(provisionalPage) { + const navigationRequest = provisionalPage.coopNavigationRequest(); + for (const [requestId, request2] of this._requestIdToRequest) { + if (request2.request === navigationRequest) { + this._onLoadingFailed(provisionalPage._session, { + requestId, + errorText: "Provisiolal navigation canceled.", + timestamp: request2._timestamp, + canceled: true + }); + return; + } + } + } + _adoptRequestFromNewProcess(navigationRequest, newSession, newRequestId) { + for (const [requestId, request2] of this._requestIdToRequest) { + if (request2.request === navigationRequest) { + this._requestIdToRequest.delete(requestId); + request2.adoptRequestFromNewProcess(newSession, newRequestId); + this._requestIdToRequest.set(newRequestId, request2); + return; + } + } + } + _onRequestWillBeSent(session, event) { + if (event.request.url.startsWith("data:")) + return; + if (event.request.url.startsWith("about:")) + return; + if (this._page.needsRequestInterception() && !event.redirectResponse) + this._requestIdToRequestWillBeSentEvent.set(event.requestId, event); + else + this._onRequest(session, event, false); + } + _onRequest(session, event, intercepted) { + let redirectedFrom = null; + if (event.redirectResponse) { + const request22 = this._requestIdToRequest.get(event.requestId); + if (request22) { + this._handleRequestRedirect(request22, event.requestId, event.redirectResponse, event.timestamp); + redirectedFrom = request22; + } + } + const frame = redirectedFrom ? redirectedFrom.request.frame() : this._page.frameManager.frame(event.frameId); + if (!frame) + return; + const isNavigationRequest = event.type === "Document"; + const documentId = isNavigationRequest ? event.loaderId : void 0; + const request2 = new WKInterceptableRequest(session, frame, event, redirectedFrom, documentId); + let route; + if (intercepted) { + route = new WKRouteImpl(session, event.requestId); + request2.request.setRawRequestHeaders(null); + } + this._requestIdToRequest.set(event.requestId, request2); + this._page.frameManager.requestStarted(request2.request, route); + } + _handleRequestRedirect(request2, requestId, responsePayload, timestamp2) { + const response2 = request2.createResponse(responsePayload); + response2._securityDetailsFinished(); + response2._serverAddrFinished(); + response2.setResponseHeadersSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(responsePayload.timing ? helper.secondsToRoundishMillis(timestamp2 - request2._timestamp) : -1); + this._requestIdToRequest.delete(requestId); + this._page.frameManager.requestReceivedResponse(response2); + this._page.frameManager.reportRequestFinished(request2.request, response2); + } + _onRequestIntercepted(session, event) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (!requestWillBeSentEvent) { + session.sendMayFail("Network.interceptWithRequest", { requestId: event.requestId }); + return; + } + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(session, requestWillBeSentEvent, true); + } + _onResponseReceived(session, event) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (requestWillBeSentEvent) { + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(session, requestWillBeSentEvent, false); + } + const request2 = this._requestIdToRequest.get(event.requestId); + if (!request2) + return; + this._requestIdToResponseReceivedPayloadEvent.set(event.requestId, event); + const response2 = request2.createResponse(event.response); + this._page.frameManager.requestReceivedResponse(response2); + if (response2.status() === 204 && request2.request.isNavigationRequest()) { + this._onLoadingFailed(session, { + requestId: event.requestId, + errorText: "Aborted: 204 No Content", + timestamp: event.timestamp + }); + } + } + _onLoadingFinished(event) { + var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k, _l; + const request2 = this._requestIdToRequest.get(event.requestId); + if (!request2) + return; + const response2 = request2.request._existingResponse(); + if (response2) { + const responseReceivedPayload = this._requestIdToResponseReceivedPayloadEvent.get(event.requestId); + response2._serverAddrFinished(parseRemoteAddress((_a2 = event == null ? void 0 : event.metrics) == null ? void 0 : _a2.remoteAddress)); + response2._securityDetailsFinished({ + protocol: isLoadedSecurely(response2.url(), response2.timing()) ? (_c2 = (_b2 = event.metrics) == null ? void 0 : _b2.securityConnection) == null ? void 0 : _c2.protocol : void 0, + subjectName: (_e2 = (_d2 = responseReceivedPayload == null ? void 0 : responseReceivedPayload.response.security) == null ? void 0 : _d2.certificate) == null ? void 0 : _e2.subject, + validFrom: (_g2 = (_f2 = responseReceivedPayload == null ? void 0 : responseReceivedPayload.response.security) == null ? void 0 : _f2.certificate) == null ? void 0 : _g2.validFrom, + validTo: (_i2 = (_h2 = responseReceivedPayload == null ? void 0 : responseReceivedPayload.response.security) == null ? void 0 : _h2.certificate) == null ? void 0 : _i2.validUntil + }); + if ((_j2 = event.metrics) == null ? void 0 : _j2.protocol) + response2._setHttpVersion(event.metrics.protocol); + response2.setEncodedBodySize(((_k = event.metrics) == null ? void 0 : _k.responseBodyBytesReceived) ?? null); + response2.setResponseHeadersSize(((_l = event.metrics) == null ? void 0 : _l.responseHeaderBytesReceived) ?? null); + response2._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request2._timestamp)); + } else { + request2.request.setRawRequestHeaders(null); + } + this._requestIdToResponseReceivedPayloadEvent.delete(event.requestId); + this._requestIdToRequest.delete(event.requestId); + this._page.frameManager.reportRequestFinished(request2.request, response2); + } + _onLoadingFailed(session, event) { + const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId); + if (requestWillBeSentEvent) { + this._requestIdToRequestWillBeSentEvent.delete(event.requestId); + this._onRequest(session, requestWillBeSentEvent, false); + } + const request2 = this._requestIdToRequest.get(event.requestId); + if (!request2) + return; + const response2 = request2.request._existingResponse(); + if (response2) { + response2._serverAddrFinished(); + response2._securityDetailsFinished(); + response2.setResponseHeadersSize(null); + response2.setEncodedBodySize(null); + response2._requestFinished(helper.secondsToRoundishMillis(event.timestamp - request2._timestamp)); + } else { + request2.request.setRawRequestHeaders(null); + } + this._requestIdToRequest.delete(event.requestId); + request2.request._setFailureText(event.errorText); + this._page.frameManager.requestFailed(request2.request, event.errorText.includes("cancelled")); + } + async _grantPermissions(origin, permissions) { + const webPermissionToProtocol = /* @__PURE__ */ new Map([ + ["geolocation", "geolocation"], + ["notifications", "notifications"], + ["clipboard-read", "clipboard-read"] + ]); + const filtered = permissions.map((permission) => { + const protocolPermission = webPermissionToProtocol.get(permission); + if (!protocolPermission) + throw new Error("Unknown permission: " + permission); + return protocolPermission; + }); + await this._pageProxySession.send("Emulation.grantPermissions", { origin, permissions: filtered }); + } + async _clearPermissions() { + await this._pageProxySession.send("Emulation.resetPermissions", {}); + } + shouldToggleStyleSheetToSyncAnimations() { + return true; + } +} +function parseRemoteAddress(value) { + if (!value) + return; + try { + const colon = value.lastIndexOf(":"); + const dot = value.lastIndexOf("."); + if (dot < 0) { + return { + ipAddress: `[${value.slice(0, colon)}]`, + port: +value.slice(colon + 1) + }; + } + if (colon > dot) { + const [address, port] = value.split(":"); + return { + ipAddress: address, + port: +port + }; + } else { + const [address, port] = value.split("."); + return { + ipAddress: `[${address}]`, + port: +port + }; + } + } catch (_) { + } +} +function isLoadedSecurely(url2, timing) { + try { + const u = new URL(url2); + if (u.protocol !== "https:" && u.protocol !== "wss:" && u.protocol !== "sftp:") + return false; + if (timing.secureConnectionStart === -1 && timing.connectStart !== -1) + return false; + return true; + } catch (_) { + } +} +const BROWSER_VERSION = "18.5"; +const DEFAULT_USER_AGENT = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/${BROWSER_VERSION} Safari/605.1.15`; +class WKBrowser extends Browser$1 { + constructor(parent, transport, options2) { + super(parent, options2); + this._contexts = /* @__PURE__ */ new Map(); + this._wkPages = /* @__PURE__ */ new Map(); + this._connection = new WKConnection(transport, this._onDisconnect.bind(this), options2.protocolLogger, options2.browserLogsCollector); + this._browserSession = this._connection.browserSession; + this._browserSession.on("Playwright.pageProxyCreated", this._onPageProxyCreated.bind(this)); + this._browserSession.on("Playwright.pageProxyDestroyed", this._onPageProxyDestroyed.bind(this)); + this._browserSession.on("Playwright.provisionalLoadFailed", (event) => this._onProvisionalLoadFailed(event)); + this._browserSession.on("Playwright.windowOpen", (event) => this._onWindowOpen(event)); + this._browserSession.on("Playwright.downloadCreated", this._onDownloadCreated.bind(this)); + this._browserSession.on("Playwright.downloadFilenameSuggested", this._onDownloadFilenameSuggested.bind(this)); + this._browserSession.on("Playwright.downloadFinished", this._onDownloadFinished.bind(this)); + this._browserSession.on("Playwright.screencastFinished", this._onScreencastFinished.bind(this)); + this._browserSession.on(kPageProxyMessageReceived, this._onPageProxyMessageReceived.bind(this)); + } + static async connect(parent, transport, options2) { + var _a2; + const browser2 = new WKBrowser(parent, transport, options2); + if (options2.__testHookOnConnectToBrowser) + await options2.__testHookOnConnectToBrowser(); + const promises2 = [ + browser2._browserSession.send("Playwright.enable") + ]; + if (options2.persistent) { + (_a2 = options2.persistent).userAgent || (_a2.userAgent = DEFAULT_USER_AGENT); + browser2._defaultContext = new WKBrowserContext(browser2, void 0, options2.persistent); + promises2.push(browser2._defaultContext._initialize()); + } + await Promise.all(promises2); + return browser2; + } + _onDisconnect() { + for (const wkPage of this._wkPages.values()) + wkPage.didClose(); + this._wkPages.clear(); + for (const video of this._idToVideo.values()) + video.artifact.reportFinished(new TargetClosedError$1()); + this._idToVideo.clear(); + this._didClose(); + } + async doCreateNewContext(options2) { + const proxy = options2.proxyOverride || options2.proxy; + const createOptions = proxy ? { + // Enable socks5 hostname resolution on Windows. + // See https://github.com/microsoft/playwright/issues/20451 + proxyServer: process.platform === "win32" ? proxy.server.replace(/^socks5:\/\//, "socks5h://") : proxy.server, + proxyBypassList: proxy.bypass + } : void 0; + const { browserContextId } = await this._browserSession.send("Playwright.createContext", createOptions); + options2.userAgent = options2.userAgent || DEFAULT_USER_AGENT; + const context = new WKBrowserContext(this, browserContextId, options2); + await context._initialize(); + this._contexts.set(browserContextId, context); + return context; + } + contexts() { + return Array.from(this._contexts.values()); + } + version() { + return BROWSER_VERSION; + } + userAgent() { + return DEFAULT_USER_AGENT; + } + _onDownloadCreated(payload) { + const page = this._wkPages.get(payload.pageProxyId); + if (!page) + return; + page._page.frameManager.frameAbortedNavigation(payload.frameId, "Download is starting"); + let originPage = page._page.initializedOrUndefined(); + if (!originPage) { + page._firstNonInitialNavigationCommittedReject(new Error("Starting new page download")); + if (page._opener) + originPage = page._opener._page.initializedOrUndefined(); + } + if (!originPage) + return; + this._downloadCreated(originPage, payload.uuid, payload.url); + } + _onDownloadFilenameSuggested(payload) { + this._downloadFilenameSuggested(payload.uuid, payload.suggestedFilename); + } + _onDownloadFinished(payload) { + this._downloadFinished(payload.uuid, payload.error); + } + _onScreencastFinished(payload) { + var _a2; + (_a2 = this._takeVideo(payload.screencastId)) == null ? void 0 : _a2.reportFinished(); + } + _onPageProxyCreated(event) { + const pageProxyId = event.pageProxyId; + let context = null; + if (event.browserContextId) { + context = this._contexts.get(event.browserContextId) || null; + } + if (!context) + context = this._defaultContext; + if (!context) + return; + const pageProxySession = new WKSession(this._connection, pageProxyId, (message) => { + this._connection.rawSend({ ...message, pageProxyId }); + }); + const opener = event.openerId ? this._wkPages.get(event.openerId) : void 0; + const wkPage = new WKPage(context, pageProxySession, opener || null); + this._wkPages.set(pageProxyId, wkPage); + } + _onPageProxyDestroyed(event) { + const pageProxyId = event.pageProxyId; + const wkPage = this._wkPages.get(pageProxyId); + if (!wkPage) + return; + wkPage.didClose(); + this._wkPages.delete(pageProxyId); + } + _onPageProxyMessageReceived(event) { + const wkPage = this._wkPages.get(event.pageProxyId); + if (!wkPage) + return; + wkPage.dispatchMessageToSession(event.message); + } + _onProvisionalLoadFailed(event) { + const wkPage = this._wkPages.get(event.pageProxyId); + if (!wkPage) + return; + wkPage.handleProvisionalLoadFailed(event); + } + _onWindowOpen(event) { + const wkPage = this._wkPages.get(event.pageProxyId); + if (!wkPage) + return; + wkPage.handleWindowOpen(event); + } + isConnected() { + return !this._connection.isClosed(); + } +} +class WKBrowserContext extends BrowserContext$1 { + constructor(browser2, browserContextId, options2) { + super(browser2, options2, browserContextId); + this._validateEmulatedViewport(options2.viewport); + this._authenticateProxyViaHeader(); + } + async _initialize() { + assert(!this._wkPages().length); + const browserContextId = this._browserContextId; + const promises2 = [super._initialize()]; + promises2.push(this._browser._browserSession.send("Playwright.setDownloadBehavior", { + behavior: this._options.acceptDownloads === "accept" ? "allow" : "deny", + downloadPath: this._browser.options.downloadsPath, + browserContextId + })); + if (this._options.ignoreHTTPSErrors || this._options.internalIgnoreHTTPSErrors) + promises2.push(this._browser._browserSession.send("Playwright.setIgnoreCertificateErrors", { browserContextId, ignore: true })); + if (this._options.locale) + promises2.push(this._browser._browserSession.send("Playwright.setLanguages", { browserContextId, languages: [this._options.locale] })); + if (this._options.geolocation) + promises2.push(this.setGeolocation(this._options.geolocation)); + if (this._options.offline) + promises2.push(this.setOffline(this._options.offline)); + if (this._options.httpCredentials) + promises2.push(this.setHTTPCredentials(this._options.httpCredentials)); + await Promise.all(promises2); + } + _wkPages() { + return Array.from(this._browser._wkPages.values()).filter((wkPage) => wkPage._browserContext === this); + } + possiblyUninitializedPages() { + return this._wkPages().map((wkPage) => wkPage._page); + } + async doCreateNewPage(markAsServerSideOnly) { + const { pageProxyId } = await this._browser._browserSession.send("Playwright.createPage", { browserContextId: this._browserContextId }); + const page = this._browser._wkPages.get(pageProxyId)._page; + if (markAsServerSideOnly) + page.markAsServerSideOnly(); + return page; + } + async doGetCookies(urls) { + const { cookies } = await this._browser._browserSession.send("Playwright.getAllCookies", { browserContextId: this._browserContextId }); + return filterCookies(cookies.map((c) => { + const copy = { ...c }; + copy.expires = c.expires === -1 ? -1 : c.expires / 1e3; + delete copy.session; + return copy; + }), urls); + } + async addCookies(cookies) { + const cc = rewriteCookies(cookies).map((c) => ({ + ...c, + session: c.expires === -1 || c.expires === void 0, + expires: c.expires && c.expires !== -1 ? c.expires * 1e3 : c.expires + })); + await this._browser._browserSession.send("Playwright.setCookies", { cookies: cc, browserContextId: this._browserContextId }); + } + async doClearCookies() { + await this._browser._browserSession.send("Playwright.deleteAllCookies", { browserContextId: this._browserContextId }); + } + async doGrantPermissions(origin, permissions) { + await Promise.all(this.pages().map((page) => page.delegate._grantPermissions(origin, permissions))); + } + async doClearPermissions() { + await Promise.all(this.pages().map((page) => page.delegate._clearPermissions())); + } + async setGeolocation(geolocation) { + verifyGeolocation(geolocation); + this._options.geolocation = geolocation; + const payload = geolocation ? { ...geolocation, timestamp: Date.now() } : void 0; + await this._browser._browserSession.send("Playwright.setGeolocationOverride", { browserContextId: this._browserContextId, geolocation: payload }); + } + async setExtraHTTPHeaders(headers) { + this._options.extraHTTPHeaders = headers; + for (const page of this.pages()) + await page.delegate.updateExtraHTTPHeaders(); + } + async setUserAgent(userAgent) { + this._options.userAgent = userAgent; + for (const page of this.pages()) + await page.delegate.updateUserAgent(); + } + async setOffline(offline) { + this._options.offline = offline; + for (const page of this.pages()) + await page.delegate.updateOffline(); + } + async doSetHTTPCredentials(httpCredentials) { + this._options.httpCredentials = httpCredentials; + for (const page of this.pages()) + await page.delegate.updateHttpCredentials(); + } + async doAddInitScript(initScript) { + for (const page of this.pages()) + await page.delegate._updateBootstrapScript(); + } + async doRemoveInitScripts(initScripts) { + for (const page of this.pages()) + await page.delegate._updateBootstrapScript(); + } + async doUpdateRequestInterception() { + for (const page of this.pages()) + await page.delegate.updateRequestInterception(); + } + async doExposePlaywrightBinding() { + for (const page of this.pages()) + await page.delegate.exposePlaywrightBinding(); + } + onClosePersistent() { + } + async clearCache() { + await this._browser._browserSession.send("Playwright.clearMemoryCache", { + browserContextId: this._browserContextId + }); + } + async doClose(reason) { + if (!this._browserContextId) { + await Promise.all(this._wkPages().map((wkPage) => wkPage._stopVideo())); + await this._browser.close({ reason }); + } else { + await this._browser._browserSession.send("Playwright.deleteContext", { browserContextId: this._browserContextId }); + this._browser._contexts.delete(this._browserContextId); + } + } + async cancelDownload(uuid) { + await this._browser._browserSession.send("Playwright.cancelDownload", { uuid }); + } + _validateEmulatedViewport(viewportSize) { + if (!viewportSize) + return; + if (process.platform === "win32" && this._browser.options.headful && (viewportSize.width < 250 || viewportSize.height < 240)) + throw new Error(`WebKit on Windows has a minimal viewport of 250x240.`); + } +} +class WebKit extends BrowserType$1 { + constructor(parent) { + super(parent, "webkit"); + } + connectToTransport(transport, options2) { + return WKBrowser.connect(this.attribution.playwright, transport, options2); + } + amendEnvironment(env, userDataDir, executable, browserArguments) { + return { ...env, CURL_COOKIE_JAR_PATH: path.join(userDataDir, "cookiejar.db") }; + } + doRewriteStartupLog(error2) { + if (!error2.logs) + return error2; + if (error2.logs.includes("Failed to open display") || error2.logs.includes("cannot open display")) + error2.logs = "\n" + wrapInASCIIBox(kNoXServerRunningError, 1); + return error2; + } + attemptToGracefullyCloseBrowser(transport) { + transport.send({ method: "Playwright.close", params: {}, id: kBrowserCloseMessageId }); + } + defaultArgs(options2, isPersistent, userDataDir) { + const { args = [], headless } = options2; + const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir")); + if (userDataDirArg) + throw this._createUserDataDirArgMisuseError("--user-data-dir"); + if (args.find((arg) => !arg.startsWith("-"))) + throw new Error("Arguments can not specify page to be opened"); + const webkitArguments = ["--inspector-pipe"]; + if (process.platform === "win32") + webkitArguments.push("--disable-accelerated-compositing"); + if (headless) + webkitArguments.push("--headless"); + if (isPersistent) + webkitArguments.push(`--user-data-dir=${userDataDir}`); + else + webkitArguments.push(`--no-startup-window`); + const proxy = options2.proxyOverride || options2.proxy; + if (proxy) { + if (process.platform === "darwin") { + webkitArguments.push(`--proxy=${proxy.server}`); + if (proxy.bypass) + webkitArguments.push(`--proxy-bypass-list=${proxy.bypass}`); + } else if (process.platform === "linux") { + webkitArguments.push(`--proxy=${proxy.server}`); + if (proxy.bypass) + webkitArguments.push(...proxy.bypass.split(",").map((t) => `--ignore-host=${t}`)); + } else if (process.platform === "win32") { + webkitArguments.push(`--curl-proxy=${proxy.server.replace(/^socks5:\/\//, "socks5h://")}`); + if (proxy.bypass) + webkitArguments.push(`--curl-noproxy=${proxy.bypass}`); + } + } + webkitArguments.push(...args); + if (isPersistent) + webkitArguments.push("about:blank"); + return webkitArguments; + } +} +let Playwright$1 = class Playwright extends SdkObject { + constructor(options2) { + super({ attribution: {}, instrumentation: createInstrumentation$1() }, void 0, "Playwright"); + this._allPages = /* @__PURE__ */ new Set(); + this._allBrowsers = /* @__PURE__ */ new Set(); + this.options = options2; + this.attribution.playwright = this; + this.instrumentation.addListener({ + onBrowserOpen: (browser2) => this._allBrowsers.add(browser2), + onBrowserClose: (browser2) => this._allBrowsers.delete(browser2), + onPageOpen: (page) => this._allPages.add(page), + onPageClose: (page) => this._allPages.delete(page), + onCallLog: (sdkObject, metadata, logName, message) => { + debugLogger.log(logName, message); + } + }, null); + this.chromium = new Chromium(this); + this.bidiChromium = new BidiChromium(this); + this.bidiFirefox = new BidiFirefox(this); + this.firefox = new Firefox(this); + this.webkit = new WebKit(this); + this.electron = new Electron$1(this); + this.android = new Android$1(this, new AdbBackend()); + this.debugController = new DebugController(this); + } + async hideHighlight() { + await Promise.all([...this._allPages].map((p) => p.hideHighlight().catch(() => { + }))); + } + allBrowsers() { + return [...this._allBrowsers]; + } + allPages() { + return [...this._allPages]; + } +}; +class EventEmitter { + constructor(platform) { + this._events = void 0; + this._eventsCount = 0; + this._maxListeners = void 0; + this._pendingHandlers = /* @__PURE__ */ new Map(); + this._platform = platform; + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + this.on = this.addListener; + this.off = this.removeListener; + } + setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || Number.isNaN(n)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); + this._maxListeners = n; + return this; + } + getMaxListeners() { + return this._maxListeners === void 0 ? this._platform.defaultMaxListeners() : this._maxListeners; + } + emit(type2, ...args) { + const events2 = this._events; + if (events2 === void 0) + return false; + const handler = events2 == null ? void 0 : events2[type2]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + this._callHandler(type2, handler, args); + } else { + const len = handler.length; + const listeners = handler.slice(); + for (let i = 0; i < len; ++i) + this._callHandler(type2, listeners[i], args); + } + return true; + } + _callHandler(type2, handler, args) { + const promise = Reflect.apply(handler, this, args); + if (!(promise instanceof Promise)) + return; + let set2 = this._pendingHandlers.get(type2); + if (!set2) { + set2 = /* @__PURE__ */ new Set(); + this._pendingHandlers.set(type2, set2); + } + set2.add(promise); + promise.catch((e) => { + if (this._rejectionHandler) + this._rejectionHandler(e); + else + throw e; + }).finally(() => set2.delete(promise)); + } + addListener(type2, listener) { + return this._addListener(type2, listener, false); + } + on(type2, listener) { + return this._addListener(type2, listener, false); + } + _addListener(type2, listener, prepend) { + checkListener(listener); + let events2 = this._events; + let existing; + if (events2 === void 0) { + events2 = this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else { + if (events2.newListener !== void 0) { + this.emit("newListener", type2, unwrapListener(listener)); + events2 = this._events; + } + existing = events2[type2]; + } + if (existing === void 0) { + existing = events2[type2] = listener; + ++this._eventsCount; + } else { + if (typeof existing === "function") { + existing = events2[type2] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + const m = this.getMaxListeners(); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + const w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type2) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = this; + w.type = type2; + w.count = existing.length; + if (!this._platform.isUnderTest()) { + console.warn(w); + } + } + } + return this; + } + prependListener(type2, listener) { + return this._addListener(type2, listener, true); + } + once(type2, listener) { + checkListener(listener); + this.on(type2, new OnceWrapper(this, type2, listener).wrapperFunction); + return this; + } + prependOnceListener(type2, listener) { + checkListener(listener); + this.prependListener(type2, new OnceWrapper(this, type2, listener).wrapperFunction); + return this; + } + removeListener(type2, listener) { + checkListener(listener); + const events2 = this._events; + if (events2 === void 0) + return this; + const list = events2[type2]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) { + this._events = /* @__PURE__ */ Object.create(null); + } else { + delete events2[type2]; + if (events2.removeListener) + this.emit("removeListener", type2, list.listener ?? listener); + } + } else if (typeof list !== "function") { + let position = -1; + let originalListener; + for (let i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || wrappedListener(list[i]) === listener) { + originalListener = wrappedListener(list[i]); + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else + list.splice(position, 1); + if (list.length === 1) + events2[type2] = list[0]; + if (events2.removeListener !== void 0) + this.emit("removeListener", type2, originalListener || listener); + } + return this; + } + off(type2, listener) { + return this.removeListener(type2, listener); + } + removeAllListeners(type2, options2) { + this._removeAllListeners(type2); + if (!options2) + return this; + if (options2.behavior === "wait") { + const errors2 = []; + this._rejectionHandler = (error2) => errors2.push(error2); + return this._waitFor(type2).then(() => { + if (errors2.length) + throw errors2[0]; + }); + } + if (options2.behavior === "ignoreErrors") + this._rejectionHandler = () => { + }; + return Promise.resolve(); + } + _removeAllListeners(type2) { + const events2 = this._events; + if (!events2) + return; + if (!events2.removeListener) { + if (type2 === void 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events2[type2] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events2[type2]; + } + return; + } + if (type2 === void 0) { + const keys = Object.keys(events2); + let key2; + for (let i = 0; i < keys.length; ++i) { + key2 = keys[i]; + if (key2 === "removeListener") + continue; + this._removeAllListeners(key2); + } + this._removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return; + } + const listeners = events2[type2]; + if (typeof listeners === "function") { + this.removeListener(type2, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) + this.removeListener(type2, listeners[i]); + } + } + listeners(type2) { + return this._listeners(this, type2, true); + } + rawListeners(type2) { + return this._listeners(this, type2, false); + } + listenerCount(type2) { + const events2 = this._events; + if (events2 !== void 0) { + const listener = events2[type2]; + if (typeof listener === "function") + return 1; + if (listener !== void 0) + return listener.length; + } + return 0; + } + eventNames() { + return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : []; + } + async _waitFor(type2) { + let promises2 = []; + if (type2) { + promises2 = [...this._pendingHandlers.get(type2) || []]; + } else { + promises2 = []; + for (const [, pending] of this._pendingHandlers) + promises2.push(...pending); + } + await Promise.all(promises2); + } + _listeners(target, type2, unwrap) { + const events2 = target._events; + if (events2 === void 0) + return []; + const listener = events2[type2]; + if (listener === void 0) + return []; + if (typeof listener === "function") + return unwrap ? [unwrapListener(listener)] : [listener]; + return unwrap ? unwrapListeners(listener) : listener.slice(); + } +} +function checkListener(listener) { + if (typeof listener !== "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); +} +class OnceWrapper { + constructor(eventEmitter, eventType, listener) { + this._fired = false; + this._eventEmitter = eventEmitter; + this._eventType = eventType; + this._listener = listener; + this.wrapperFunction = this._handle.bind(this); + this.wrapperFunction.listener = listener; + } + _handle(...args) { + if (this._fired) + return; + this._fired = true; + this._eventEmitter.removeListener(this._eventType, this.wrapperFunction); + return this._listener.apply(this._eventEmitter, args); + } +} +function unwrapListener(l) { + return wrappedListener(l) ?? l; +} +function unwrapListeners(arr) { + return arr.map((l) => wrappedListener(l) ?? l); +} +function wrappedListener(l) { + return l.listener; +} +function captureLibraryStackTrace(platform) { + const stack = captureRawStack(); + let parsedFrames = stack.map((line) => { + const frame = parseStackFrame(line, platform.pathSeparator, platform.showInternalStackFrames()); + if (!frame || !frame.file) + return null; + const isPlaywrightLibrary = !!platform.coreDir && frame.file.startsWith(platform.coreDir); + const parsed = { + frame, + frameText: line, + isPlaywrightLibrary + }; + return parsed; + }).filter(Boolean); + let apiName = ""; + for (let i = 0; i < parsedFrames.length - 1; i++) { + const parsedFrame = parsedFrames[i]; + if (parsedFrame.isPlaywrightLibrary && !parsedFrames[i + 1].isPlaywrightLibrary) { + apiName = apiName || normalizeAPIName(parsedFrame.frame.function); + break; + } + } + function normalizeAPIName(name) { + if (!name) + return ""; + const match = name.match(/(API|JS|CDP|[A-Z])(.*)/); + if (!match) + return name; + return match[1].toLowerCase() + match[2]; + } + const filterPrefixes = platform.boxedStackPrefixes(); + parsedFrames = parsedFrames.filter((f) => { + if (filterPrefixes.some((prefix) => f.frame.file.startsWith(prefix))) + return false; + return true; + }); + return { + frames: parsedFrames.map((p) => p.frame), + apiName + }; +} +class ChannelOwner extends EventEmitter { + constructor(parent, type2, guid, initializer) { + const connection = parent instanceof ChannelOwner ? parent._connection : parent; + super(connection._platform); + this._objects = /* @__PURE__ */ new Map(); + this._eventToSubscriptionMapping = /* @__PURE__ */ new Map(); + this._wasCollected = false; + this.setMaxListeners(0); + this._connection = connection; + this._type = type2; + this._guid = guid; + this._parent = parent instanceof ChannelOwner ? parent : void 0; + this._instrumentation = this._connection._instrumentation; + this._connection._objects.set(guid, this); + if (this._parent) { + this._parent._objects.set(guid, this); + this._logger = this._parent._logger; + } + this._channel = this._createChannel(new EventEmitter(connection._platform)); + this._initializer = initializer; + } + _setEventToSubscriptionMapping(mapping) { + this._eventToSubscriptionMapping = mapping; + } + _updateSubscription(event, enabled) { + const protocolEvent = this._eventToSubscriptionMapping.get(String(event)); + if (protocolEvent) + this._channel.updateSubscription({ event: protocolEvent, enabled }).catch(() => { + }); + } + on(event, listener) { + if (!this.listenerCount(event)) + this._updateSubscription(event, true); + super.on(event, listener); + return this; + } + addListener(event, listener) { + if (!this.listenerCount(event)) + this._updateSubscription(event, true); + super.addListener(event, listener); + return this; + } + prependListener(event, listener) { + if (!this.listenerCount(event)) + this._updateSubscription(event, true); + super.prependListener(event, listener); + return this; + } + off(event, listener) { + super.off(event, listener); + if (!this.listenerCount(event)) + this._updateSubscription(event, false); + return this; + } + removeListener(event, listener) { + super.removeListener(event, listener); + if (!this.listenerCount(event)) + this._updateSubscription(event, false); + return this; + } + _adopt(child) { + child._parent._objects.delete(child._guid); + this._objects.set(child._guid, child); + child._parent = this; + } + _dispose(reason) { + if (this._parent) + this._parent._objects.delete(this._guid); + this._connection._objects.delete(this._guid); + this._wasCollected = reason === "gc"; + for (const object of [...this._objects.values()]) + object._dispose(reason); + this._objects.clear(); + } + _debugScopeState() { + return { + _guid: this._guid, + objects: Array.from(this._objects.values()).map((o) => o._debugScopeState()) + }; + } + _validatorToWireContext() { + return { + tChannelImpl: tChannelImplToWire, + binary: this._connection.rawBuffers() ? "buffer" : "toBase64", + isUnderTest: () => this._platform.isUnderTest() + }; + } + _createChannel(base2) { + const channel = new Proxy(base2, { + get: (obj, prop) => { + if (typeof prop === "string") { + const validator = maybeFindValidator(this._type, prop, "Params"); + const { internal } = methodMetainfo.get(this._type + "." + prop) || {}; + if (validator) { + return async (params) => { + return await this._wrapApiCall(async (apiZone) => { + const validatedParams = validator(params, "", this._validatorToWireContext()); + if (!apiZone.internal && !apiZone.reported) { + apiZone.reported = true; + this._instrumentation.onApiCallBegin(apiZone, { type: this._type, method: prop, params }); + logApiCall(this._platform, this._logger, `=> ${apiZone.apiName} started`); + return await this._connection.sendMessageToServer(this, prop, validatedParams, apiZone); + } + return await this._connection.sendMessageToServer(this, prop, validatedParams, { internal: true }); + }, { internal }); + }; + } + } + return obj[prop]; + } + }); + channel._object = this; + return channel; + } + async _wrapApiCall(func, options2) { + const logger = this._logger; + const existingApiZone = this._platform.zones.current().data(); + if (existingApiZone) + return await func(existingApiZone); + const crxZone = currentZone().data("crxZone"); + const stackTrace = captureLibraryStackTrace(this._platform); + const apiZone = { title: options2 == null ? void 0 : options2.title, apiName: (crxZone == null ? void 0 : crxZone.apiName) ?? stackTrace.apiName, frames: stackTrace.frames, internal: (options2 == null ? void 0 : options2.internal) ?? false, reported: false, userData: void 0, stepId: void 0 }; + try { + const result = await this._platform.zones.current().push(apiZone).run(async () => await func(apiZone)); + if (!(options2 == null ? void 0 : options2.internal)) { + logApiCall(this._platform, logger, `<= ${apiZone.apiName} succeeded`); + this._instrumentation.onApiCallEnd(apiZone); + } + return result; + } catch (e) { + const innerError = (this._platform.showInternalStackFrames() || this._platform.isUnderTest()) && e.stack ? "\n\n" + e.stack : ""; + if (apiZone.apiName && !apiZone.apiName.includes("")) + e.message = apiZone.apiName + ": " + e.message; + const stackFrames = "\n" + stringifyStackFrames(stackTrace.frames).join("\n") + innerError; + if (stackFrames.trim()) + e.stack = e.message + stackFrames; + else + e.stack = ""; + if (!(options2 == null ? void 0 : options2.internal)) { + apiZone.error = e; + logApiCall(this._platform, logger, `<= ${apiZone.apiName} failed`); + this._instrumentation.onApiCallEnd(apiZone); + } + throw e; + } + } + _toImpl() { + var _a2, _b2; + return (_b2 = (_a2 = this._connection).toImpl) == null ? void 0 : _b2.call(_a2, this); + } + toJSON() { + return { + _type: this._type, + _guid: this._guid + }; + } +} +function logApiCall(platform, logger, message) { + if (logger && logger.isEnabled("api", "info")) + logger.log("api", "info", message, [], { color: "cyan" }); + platform.log("api", message); +} +function tChannelImplToWire(names, arg, path2, context) { + if (arg._object instanceof ChannelOwner && (names === "*" || names.includes(arg._object._type))) + return { guid: arg._object._guid }; + throw new ValidationError(`${path2}: expected channel ${names.toString()}`); +} +class Stream extends ChannelOwner { + static from(Stream2) { + return Stream2._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + } + stream() { + return this._platform.streamReadable(this._channel); + } +} +const fileUploadSizeLimit = 50 * 1024 * 1024; +async function mkdirIfNeeded(platform, filePath) { + await platform.fs().promises.mkdir(platform.path().dirname(filePath), { recursive: true }).catch(() => { + }); +} +class Artifact2 extends ChannelOwner { + static from(channel) { + return channel._object; + } + async pathAfterFinished() { + if (this._connection.isRemote()) + throw new Error(`Path is not available when connecting remotely. Use saveAs() to save a local copy.`); + return (await this._channel.pathAfterFinished()).value; + } + async saveAs(path2) { + if (!this._connection.isRemote()) { + await this._channel.saveAs({ path: path2 }); + return; + } + const result = await this._channel.saveAsStream(); + const stream2 = Stream.from(result.stream); + await mkdirIfNeeded(this._platform, path2); + await new Promise((resolve, reject) => { + stream2.stream().pipe(this._platform.fs().createWriteStream(path2)).on("finish", resolve).on("error", reject); + }); + } + async failure() { + return (await this._channel.failure()).error || null; + } + async createReadStream() { + const result = await this._channel.stream(); + const stream2 = Stream.from(result.stream); + return stream2.stream(); + } + async readIntoBuffer() { + const stream2 = await this.createReadStream(); + return await new Promise((resolve, reject) => { + const chunks = []; + stream2.on("data", (chunk) => { + chunks.push(chunk); + }); + stream2.on("end", () => { + resolve(Buffer.concat(chunks)); + }); + stream2.on("error", reject); + }); + } + async cancel() { + return await this._channel.cancel(); + } + async delete() { + return await this._channel.delete(); + } +} +class CDPSession extends ChannelOwner { + static from(cdpSession) { + return cdpSession._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._channel.on("event", ({ method, params }) => { + this.emit(method, params); + }); + this.on = super.on; + this.addListener = super.addListener; + this.off = super.removeListener; + this.removeListener = super.removeListener; + this.once = super.once; + } + async send(method, params) { + const result = await this._channel.send({ method, params }); + return result.result; + } + async detach() { + return await this._channel.detach(); + } +} +function envObjectToArray(env) { + const result = []; + for (const name in env) { + if (!Object.is(env[name], void 0)) + result.push({ name, value: String(env[name]) }); + } + return result; +} +async function evaluationScript(platform, fun, arg, addSourceUrl = true) { + if (typeof fun === "function") { + const source2 = fun.toString(); + const argString = Object.is(arg, void 0) ? "undefined" : JSON.stringify(arg); + return `(${source2})(${argString})`; + } + if (arg !== void 0) + throw new Error("Cannot evaluate a string with arguments"); + if (isString(fun)) + return fun; + if (fun.content !== void 0) + return fun.content; + if (fun.path !== void 0) { + let source2 = await platform.fs().promises.readFile(fun.path, "utf8"); + if (addSourceUrl) + source2 = addSourceUrlToScript(source2, fun.path); + return source2; + } + throw new Error("Either path or content property must be present"); +} +function addSourceUrlToScript(source2, path2) { + return `${source2} +//# sourceURL=${path2.replace(/\n/g, "")}`; +} +class Clock2 { + constructor(browserContext) { + this._browserContext = browserContext; + } + async install(options2 = {}) { + await this._browserContext._channel.clockInstall(options2.time !== void 0 ? parseTime(options2.time) : {}); + } + async fastForward(ticks) { + await this._browserContext._channel.clockFastForward(parseTicks(ticks)); + } + async pauseAt(time) { + await this._browserContext._channel.clockPauseAt(parseTime(time)); + } + async resume() { + await this._browserContext._channel.clockResume({}); + } + async runFor(ticks) { + await this._browserContext._channel.clockRunFor(parseTicks(ticks)); + } + async setFixedTime(time) { + await this._browserContext._channel.clockSetFixedTime(parseTime(time)); + } + async setSystemTime(time) { + await this._browserContext._channel.clockSetSystemTime(parseTime(time)); + } +} +function parseTime(time) { + if (typeof time === "number") + return { timeNumber: time }; + if (typeof time === "string") + return { timeString: time }; + if (!isFinite(time.getTime())) + throw new Error(`Invalid date: ${time}`); + return { timeNumber: time.getTime() }; +} +function parseTicks(ticks) { + return { + ticksNumber: typeof ticks === "number" ? ticks : void 0, + ticksString: typeof ticks === "string" ? ticks : void 0 + }; +} +class TimeoutError2 extends Error { + constructor(message) { + super(message); + this.name = "TimeoutError"; + } +} +class TargetClosedError2 extends Error { + constructor(cause) { + super(cause || "Target page, context or browser has been closed"); + } +} +function isTargetClosedError(error2) { + return error2 instanceof TargetClosedError2; +} +function serializeError(e) { + if (isError$2(e)) + return { error: { message: e.message, stack: e.stack, name: e.name } }; + return { value: serializeValue(e, (value) => ({ fallThrough: value })) }; +} +function parseError(error2) { + if (!error2.error) { + if (error2.value === void 0) + throw new Error("Serialized error must have either an error or a value"); + return parseSerializedValue(error2.value, void 0); + } + if (error2.error.name === "TimeoutError") { + const e2 = new TimeoutError2(error2.error.message); + e2.stack = error2.error.stack || ""; + return e2; + } + if (error2.error.name === "TargetClosedError") { + const e2 = new TargetClosedError2(error2.error.message); + e2.stack = error2.error.stack || ""; + return e2; + } + const e = new Error(error2.error.message); + e.stack = error2.error.stack || ""; + e.name = error2.error.name; + return e; +} +class JSHandle2 extends ChannelOwner { + static from(handle) { + return handle._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._preview = this._initializer.preview; + this._channel.on("previewUpdated", ({ preview }) => this._preview = preview); + } + async evaluate(pageFunction, arg) { + const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async evaluateHandle(pageFunction, arg) { + const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result.handle); + } + async getProperty(propertyName) { + const result = await this._channel.getProperty({ name: propertyName }); + return JSHandle2.from(result.handle); + } + async getProperties() { + const map2 = /* @__PURE__ */ new Map(); + for (const { name, value } of (await this._channel.getPropertyList()).properties) + map2.set(name, JSHandle2.from(value)); + return map2; + } + async jsonValue() { + return parseResult((await this._channel.jsonValue()).value); + } + asElement() { + return null; + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + async dispose() { + try { + await this._channel.dispose(); + } catch (e) { + if (isTargetClosedError(e)) + return; + throw e; + } + } + toString() { + return this._preview; + } +} +function serializeArgument(arg) { + const handles = []; + const pushHandle = (channel) => { + handles.push(channel); + return handles.length - 1; + }; + const value = serializeValue(arg, (value2) => { + if (value2 instanceof JSHandle2) + return { h: pushHandle(value2._channel) }; + return { fallThrough: value2 }; + }); + return { value, handles }; +} +function parseResult(value) { + return parseSerializedValue(value, void 0); +} +function assertMaxArguments(count, max2) { + if (count > max2) + throw new Error("Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object."); +} +function axNodeFromProtocol(axNode) { + const result = { + ...axNode, + value: axNode.valueNumber !== void 0 ? axNode.valueNumber : axNode.valueString, + checked: axNode.checked === "checked" ? true : axNode.checked === "unchecked" ? false : axNode.checked, + pressed: axNode.pressed === "pressed" ? true : axNode.pressed === "released" ? false : axNode.pressed, + children: axNode.children ? axNode.children.map(axNodeFromProtocol) : void 0 + }; + delete result.valueNumber; + delete result.valueString; + return result; +} +class Accessibility2 { + constructor(channel) { + this._channel = channel; + } + async snapshot(options2 = {}) { + const root = options2.root ? options2.root._elementChannel : void 0; + const result = await this._channel.accessibilitySnapshot({ interestingOnly: options2.interestingOnly, root }); + return result.rootAXNode ? axNodeFromProtocol(result.rootAXNode) : null; + } +} +class Coverage { + constructor(channel) { + this._channel = channel; + } + async startJSCoverage(options2 = {}) { + await this._channel.startJSCoverage(options2); + } + async stopJSCoverage() { + return (await this._channel.stopJSCoverage()).entries; + } + async startCSSCoverage(options2 = {}) { + await this._channel.startCSSCoverage(options2); + } + async stopCSSCoverage() { + return (await this._channel.stopCSSCoverage()).entries; + } +} +class Download2 { + constructor(page, url2, suggestedFilename, artifact) { + this._page = page; + this._url = url2; + this._suggestedFilename = suggestedFilename; + this._artifact = artifact; + } + page() { + return this._page; + } + url() { + return this._url; + } + suggestedFilename() { + return this._suggestedFilename; + } + async path() { + return await this._artifact.pathAfterFinished(); + } + async saveAs(path2) { + return await this._artifact.saveAs(path2); + } + async failure() { + return await this._artifact.failure(); + } + async createReadStream() { + return await this._artifact.createReadStream(); + } + async cancel() { + return await this._artifact.cancel(); + } + async delete() { + return await this._artifact.delete(); + } +} +const Events = { + AndroidDevice: { + WebView: "webview", + Close: "close" + }, + AndroidSocket: { + Data: "data", + Close: "close" + }, + AndroidWebView: { + Close: "close" + }, + Browser: { + Disconnected: "disconnected" + }, + BrowserContext: { + Console: "console", + Close: "close", + Dialog: "dialog", + Page: "page", + // Can't use just 'error' due to node.js special treatment of error events. + // @see https://nodejs.org/api/events.html#events_error_events + WebError: "weberror", + BackgroundPage: "backgroundpage", + ServiceWorker: "serviceworker", + Request: "request", + Response: "response", + RequestFailed: "requestfailed", + RequestFinished: "requestfinished" + }, + Page: { + Close: "close", + Crash: "crash", + Console: "console", + Dialog: "dialog", + Download: "download", + FileChooser: "filechooser", + DOMContentLoaded: "domcontentloaded", + // Can't use just 'error' due to node.js special treatment of error events. + // @see https://nodejs.org/api/events.html#events_error_events + PageError: "pageerror", + Request: "request", + Response: "response", + RequestFailed: "requestfailed", + RequestFinished: "requestfinished", + FrameAttached: "frameattached", + FrameDetached: "framedetached", + FrameNavigated: "framenavigated", + Load: "load", + Popup: "popup", + WebSocket: "websocket", + Worker: "worker" + }, + WebSocket: { + Close: "close", + Error: "socketerror", + FrameReceived: "framereceived", + FrameSent: "framesent" + }, + Worker: { + Close: "close" + }, + ElectronApplication: { + Close: "close", + Console: "console", + Window: "window" + } +}; +function getByAttributeTextSelector(attrName, text, options2) { + return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, (options2 == null ? void 0 : options2.exact) || false)}]`; +} +function getByTestIdSelector(testIdAttributeName2, testId) { + return `internal:testid=[${testIdAttributeName2}=${escapeForAttributeSelector(testId, true)}]`; +} +function getByLabelSelector(text, options2) { + return "internal:label=" + escapeForTextSelector(text, !!(options2 == null ? void 0 : options2.exact)); +} +function getByAltTextSelector(text, options2) { + return getByAttributeTextSelector("alt", text, options2); +} +function getByTitleSelector(text, options2) { + return getByAttributeTextSelector("title", text, options2); +} +function getByPlaceholderSelector(text, options2) { + return getByAttributeTextSelector("placeholder", text, options2); +} +function getByTextSelector(text, options2) { + return "internal:text=" + escapeForTextSelector(text, !!(options2 == null ? void 0 : options2.exact)); +} +function getByRoleSelector(role, options2 = {}) { + const props = []; + if (options2.checked !== void 0) + props.push(["checked", String(options2.checked)]); + if (options2.disabled !== void 0) + props.push(["disabled", String(options2.disabled)]); + if (options2.selected !== void 0) + props.push(["selected", String(options2.selected)]); + if (options2.expanded !== void 0) + props.push(["expanded", String(options2.expanded)]); + if (options2.includeHidden !== void 0) + props.push(["include-hidden", String(options2.includeHidden)]); + if (options2.level !== void 0) + props.push(["level", String(options2.level)]); + if (options2.name !== void 0) + props.push(["name", escapeForAttributeSelector(options2.name, !!options2.exact)]); + if (options2.pressed !== void 0) + props.push(["pressed", String(options2.pressed)]); + return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`; +} +class Locator { + constructor(frame, selector, options2) { + this._frame = frame; + this._selector = selector; + if (options2 == null ? void 0 : options2.hasText) + this._selector += ` >> internal:has-text=${escapeForTextSelector(options2.hasText, false)}`; + if (options2 == null ? void 0 : options2.hasNotText) + this._selector += ` >> internal:has-not-text=${escapeForTextSelector(options2.hasNotText, false)}`; + if (options2 == null ? void 0 : options2.has) { + const locator = options2.has; + if (locator._frame !== frame) + throw new Error(`Inner "has" locator must belong to the same frame.`); + this._selector += ` >> internal:has=` + JSON.stringify(locator._selector); + } + if (options2 == null ? void 0 : options2.hasNot) { + const locator = options2.hasNot; + if (locator._frame !== frame) + throw new Error(`Inner "hasNot" locator must belong to the same frame.`); + this._selector += ` >> internal:has-not=` + JSON.stringify(locator._selector); + } + if ((options2 == null ? void 0 : options2.visible) !== void 0) + this._selector += ` >> visible=${options2.visible ? "true" : "false"}`; + if (this._frame._platform.inspectCustom) + this[this._frame._platform.inspectCustom] = () => this._inspect(); + } + async _withElement(task, options2) { + const timeout = this._frame._timeout({ timeout: options2.timeout }); + const deadline = timeout ? monotonicTime() + timeout : 0; + return await this._frame._wrapApiCall(async () => { + const result = await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, state: "attached", timeout }); + const handle = ElementHandle2.fromNullable(result.element); + if (!handle) + throw new Error(`Could not resolve ${this._selector} to DOM Element`); + try { + return await task(handle, deadline ? deadline - monotonicTime() : 0); + } finally { + await handle.dispose(); + } + }, { title: options2.title, internal: options2.internal }); + } + _equals(locator) { + return this._frame === locator._frame && this._selector === locator._selector; + } + page() { + return this._frame.page(); + } + async boundingBox(options2) { + return await this._withElement((h) => h.boundingBox(), { title: "Bounding box", timeout: options2 == null ? void 0 : options2.timeout }); + } + async check(options2 = {}) { + return await this._frame.check(this._selector, { strict: true, ...options2 }); + } + async click(options2 = {}) { + return await this._frame.click(this._selector, { strict: true, ...options2 }); + } + async dblclick(options2 = {}) { + await this._frame.dblclick(this._selector, { strict: true, ...options2 }); + } + async dispatchEvent(type2, eventInit = {}, options2) { + return await this._frame.dispatchEvent(this._selector, type2, eventInit, { strict: true, ...options2 }); + } + async dragTo(target, options2 = {}) { + return await this._frame.dragAndDrop(this._selector, target._selector, { + strict: true, + ...options2 + }); + } + async evaluate(pageFunction, arg, options2) { + return await this._withElement((h) => h.evaluate(pageFunction, arg), { title: "Evaluate", timeout: options2 == null ? void 0 : options2.timeout }); + } + async evaluateAll(pageFunction, arg) { + return await this._frame.$$eval(this._selector, pageFunction, arg); + } + async evaluateHandle(pageFunction, arg, options2) { + return await this._withElement((h) => h.evaluateHandle(pageFunction, arg), { title: "Evaluate", timeout: options2 == null ? void 0 : options2.timeout }); + } + async fill(value, options2 = {}) { + return await this._frame.fill(this._selector, value, { strict: true, ...options2 }); + } + async clear(options2 = {}) { + return await this.fill("", options2); + } + async _highlight() { + return await this._frame._highlight(this._selector); + } + async highlight() { + return await this._frame._highlight(this._selector); + } + locator(selectorOrLocator, options2) { + if (isString(selectorOrLocator)) + return new Locator(this._frame, this._selector + " >> " + selectorOrLocator, options2); + if (selectorOrLocator._frame !== this._frame) + throw new Error(`Locators must belong to the same frame.`); + return new Locator(this._frame, this._selector + " >> internal:chain=" + JSON.stringify(selectorOrLocator._selector), options2); + } + getByTestId(testId) { + return this.locator(getByTestIdSelector(testIdAttributeName(), testId)); + } + getByAltText(text, options2) { + return this.locator(getByAltTextSelector(text, options2)); + } + getByLabel(text, options2) { + return this.locator(getByLabelSelector(text, options2)); + } + getByPlaceholder(text, options2) { + return this.locator(getByPlaceholderSelector(text, options2)); + } + getByText(text, options2) { + return this.locator(getByTextSelector(text, options2)); + } + getByTitle(text, options2) { + return this.locator(getByTitleSelector(text, options2)); + } + getByRole(role, options2 = {}) { + return this.locator(getByRoleSelector(role, options2)); + } + frameLocator(selector) { + return new FrameLocator(this._frame, this._selector + " >> " + selector); + } + filter(options2) { + return new Locator(this._frame, this._selector, options2); + } + async elementHandle(options2) { + return await this._frame.waitForSelector(this._selector, { strict: true, state: "attached", ...options2 }); + } + async elementHandles() { + return await this._frame.$$(this._selector); + } + contentFrame() { + return new FrameLocator(this._frame, this._selector); + } + describe(description) { + return new Locator(this._frame, this._selector + " >> internal:describe=" + JSON.stringify(description)); + } + first() { + return new Locator(this._frame, this._selector + " >> nth=0"); + } + last() { + return new Locator(this._frame, this._selector + ` >> nth=-1`); + } + nth(index2) { + return new Locator(this._frame, this._selector + ` >> nth=${index2}`); + } + and(locator) { + if (locator._frame !== this._frame) + throw new Error(`Locators must belong to the same frame.`); + return new Locator(this._frame, this._selector + ` >> internal:and=` + JSON.stringify(locator._selector)); + } + or(locator) { + if (locator._frame !== this._frame) + throw new Error(`Locators must belong to the same frame.`); + return new Locator(this._frame, this._selector + ` >> internal:or=` + JSON.stringify(locator._selector)); + } + async focus(options2) { + return await this._frame.focus(this._selector, { strict: true, ...options2 }); + } + async blur(options2) { + await this._frame._channel.blur({ selector: this._selector, strict: true, ...options2, timeout: this._frame._timeout(options2) }); + } + async count() { + return await this._frame._queryCount(this._selector); + } + async _generateLocatorString() { + return await this._withElement((h) => h._generateLocatorString(), { title: "Generate locator string", internal: true }); + } + async getAttribute(name, options2) { + return await this._frame.getAttribute(this._selector, name, { strict: true, ...options2 }); + } + async hover(options2 = {}) { + return await this._frame.hover(this._selector, { strict: true, ...options2 }); + } + async innerHTML(options2) { + return await this._frame.innerHTML(this._selector, { strict: true, ...options2 }); + } + async innerText(options2) { + return await this._frame.innerText(this._selector, { strict: true, ...options2 }); + } + async inputValue(options2) { + return await this._frame.inputValue(this._selector, { strict: true, ...options2 }); + } + async isChecked(options2) { + return await this._frame.isChecked(this._selector, { strict: true, ...options2 }); + } + async isDisabled(options2) { + return await this._frame.isDisabled(this._selector, { strict: true, ...options2 }); + } + async isEditable(options2) { + return await this._frame.isEditable(this._selector, { strict: true, ...options2 }); + } + async isEnabled(options2) { + return await this._frame.isEnabled(this._selector, { strict: true, ...options2 }); + } + async isHidden(options2) { + return await this._frame.isHidden(this._selector, { strict: true, ...options2 }); + } + async isVisible(options2) { + return await this._frame.isVisible(this._selector, { strict: true, ...options2 }); + } + async press(key2, options2 = {}) { + return await this._frame.press(this._selector, key2, { strict: true, ...options2 }); + } + async screenshot(options2 = {}) { + const mask = options2.mask; + return await this._withElement((h, timeout) => h.screenshot({ ...options2, mask, timeout }), { title: "Screenshot", timeout: options2.timeout }); + } + async ariaSnapshot(options2) { + const result = await this._frame._channel.ariaSnapshot({ ...options2, selector: this._selector, timeout: this._frame._timeout(options2) }); + return result.snapshot; + } + async scrollIntoViewIfNeeded(options2 = {}) { + return await this._withElement((h, timeout) => h.scrollIntoViewIfNeeded({ ...options2, timeout }), { title: "Scroll into view", timeout: options2.timeout }); + } + async selectOption(values, options2 = {}) { + return await this._frame.selectOption(this._selector, values, { strict: true, ...options2 }); + } + async selectText(options2 = {}) { + return await this._withElement((h, timeout) => h.selectText({ ...options2, timeout }), { title: "Select text", timeout: options2.timeout }); + } + async setChecked(checked, options2) { + if (checked) + await this.check(options2); + else + await this.uncheck(options2); + } + async setInputFiles(files, options2 = {}) { + return await this._frame.setInputFiles(this._selector, files, { strict: true, ...options2 }); + } + async tap(options2 = {}) { + return await this._frame.tap(this._selector, { strict: true, ...options2 }); + } + async textContent(options2) { + return await this._frame.textContent(this._selector, { strict: true, ...options2 }); + } + async type(text, options2 = {}) { + return await this._frame.type(this._selector, text, { strict: true, ...options2 }); + } + async pressSequentially(text, options2 = {}) { + return await this.type(text, options2); + } + async uncheck(options2 = {}) { + return await this._frame.uncheck(this._selector, { strict: true, ...options2 }); + } + async all() { + return new Array(await this.count()).fill(0).map((e, i) => this.nth(i)); + } + async allInnerTexts() { + return await this._frame.$$eval(this._selector, (ee) => ee.map((e) => e.innerText)); + } + async allTextContents() { + return await this._frame.$$eval(this._selector, (ee) => ee.map((e) => e.textContent || "")); + } + async waitFor(options2) { + await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, omitReturnValue: true, ...options2, timeout: this._frame._timeout(options2) }); + } + async _expect(expression, options2) { + const params = { selector: this._selector, expression, ...options2, isNot: !!options2.isNot }; + params.expectedValue = serializeArgument(options2.expectedValue); + const result = await this._frame._channel.expect(params); + if (result.received !== void 0) + result.received = parseResult(result.received); + return result; + } + _inspect() { + return this.toString(); + } + toString() { + return asLocator("javascript", this._selector); + } +} +class FrameLocator { + constructor(frame, selector) { + this._frame = frame; + this._frameSelector = selector; + } + locator(selectorOrLocator, options2) { + if (isString(selectorOrLocator)) + return new Locator(this._frame, this._frameSelector + " >> internal:control=enter-frame >> " + selectorOrLocator, options2); + if (selectorOrLocator._frame !== this._frame) + throw new Error(`Locators must belong to the same frame.`); + return new Locator(this._frame, this._frameSelector + " >> internal:control=enter-frame >> " + selectorOrLocator._selector, options2); + } + getByTestId(testId) { + return this.locator(getByTestIdSelector(testIdAttributeName(), testId)); + } + getByAltText(text, options2) { + return this.locator(getByAltTextSelector(text, options2)); + } + getByLabel(text, options2) { + return this.locator(getByLabelSelector(text, options2)); + } + getByPlaceholder(text, options2) { + return this.locator(getByPlaceholderSelector(text, options2)); + } + getByText(text, options2) { + return this.locator(getByTextSelector(text, options2)); + } + getByTitle(text, options2) { + return this.locator(getByTitleSelector(text, options2)); + } + getByRole(role, options2 = {}) { + return this.locator(getByRoleSelector(role, options2)); + } + owner() { + return new Locator(this._frame, this._frameSelector); + } + frameLocator(selector) { + return new FrameLocator(this._frame, this._frameSelector + " >> internal:control=enter-frame >> " + selector); + } + first() { + return new FrameLocator(this._frame, this._frameSelector + " >> nth=0"); + } + last() { + return new FrameLocator(this._frame, this._frameSelector + ` >> nth=-1`); + } + nth(index2) { + return new FrameLocator(this._frame, this._frameSelector + ` >> nth=${index2}`); + } +} +let _testIdAttributeName = "data-testid"; +function testIdAttributeName() { + return _testIdAttributeName; +} +function setTestIdAttribute(attributeName) { + _testIdAttributeName = attributeName; +} +class Tracing2 extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._includeSources = false; + this._isTracing = false; + } + static from(channel) { + return channel._object; + } + async start(options2 = {}) { + this._includeSources = !!options2.sources; + await this._channel.tracingStart({ + name: options2.name, + snapshots: options2.snapshots, + screenshots: options2.screenshots, + live: options2._live + }); + const { traceName } = await this._channel.tracingStartChunk({ name: options2.name, title: options2.title }); + await this._startCollectingStacks(traceName); + } + async startChunk(options2 = {}) { + const { traceName } = await this._channel.tracingStartChunk(options2); + await this._startCollectingStacks(traceName); + } + async group(name, options2 = {}) { + await this._channel.tracingGroup({ name, location: options2.location }); + } + async groupEnd() { + await this._channel.tracingGroupEnd(); + } + async _startCollectingStacks(traceName) { + var _a2; + if (!this._isTracing) { + this._isTracing = true; + this._connection.setIsTracing(true); + } + const result = await ((_a2 = this._connection.localUtils()) == null ? void 0 : _a2.tracingStarted({ tracesDir: this._tracesDir, traceName })); + this._stacksId = result == null ? void 0 : result.stacksId; + } + async stopChunk(options2 = {}) { + await this._doStopChunk(options2.path); + } + async stop(options2 = {}) { + await this._doStopChunk(options2.path); + await this._channel.tracingStop(); + } + async _doStopChunk(filePath) { + this._resetStackCounter(); + if (!filePath) { + await this._channel.tracingStopChunk({ mode: "discard" }); + if (this._stacksId) + await this._connection.localUtils().traceDiscarded({ stacksId: this._stacksId }); + return; + } + const localUtils = this._connection.localUtils(); + if (!localUtils) + throw new Error("Cannot save trace in thin clients"); + const isLocal = !this._connection.isRemote(); + if (isLocal) { + const result2 = await this._channel.tracingStopChunk({ mode: "entries" }); + await localUtils.zip({ zipFile: filePath, entries: result2.entries, mode: "write", stacksId: this._stacksId, includeSources: this._includeSources }); + return; + } + const result = await this._channel.tracingStopChunk({ mode: "archive" }); + if (!result.artifact) { + if (this._stacksId) + await localUtils.traceDiscarded({ stacksId: this._stacksId }); + return; + } + const artifact = Artifact2.from(result.artifact); + await artifact.saveAs(filePath); + await artifact.delete(); + await localUtils.zip({ zipFile: filePath, entries: [], mode: "append", stacksId: this._stacksId, includeSources: this._includeSources }); + } + _resetStackCounter() { + if (this._isTracing) { + this._isTracing = false; + this._connection.setIsTracing(false); + } + } +} +class TimeoutSettings { + constructor(platform, parent) { + this._parent = parent; + this._platform = platform; + } + setDefaultTimeout(timeout) { + this._defaultTimeout = timeout; + } + setDefaultNavigationTimeout(timeout) { + this._defaultNavigationTimeout = timeout; + } + defaultNavigationTimeout() { + return this._defaultNavigationTimeout; + } + defaultTimeout() { + return this._defaultTimeout; + } + navigationTimeout(options2) { + if (typeof options2.timeout === "number") + return options2.timeout; + if (this._defaultNavigationTimeout !== void 0) + return this._defaultNavigationTimeout; + if (this._platform.isDebugMode()) + return 0; + if (this._defaultTimeout !== void 0) + return this._defaultTimeout; + if (this._parent) + return this._parent.navigationTimeout(options2); + return DEFAULT_PLAYWRIGHT_TIMEOUT; + } + timeout(options2) { + if (typeof options2.timeout === "number") + return options2.timeout; + if (this._platform.isDebugMode()) + return 0; + if (this._defaultTimeout !== void 0) + return this._defaultTimeout; + if (this._parent) + return this._parent.timeout(options2); + return DEFAULT_PLAYWRIGHT_TIMEOUT; + } + launchTimeout(options2) { + if (typeof options2.timeout === "number") + return options2.timeout; + if (this._platform.isDebugMode()) + return 0; + if (this._parent) + return this._parent.launchTimeout(options2); + return DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; + } +} +class APIRequest { + constructor(playwright2) { + this._contexts = /* @__PURE__ */ new Set(); + this._playwright = playwright2; + } + async newContext(options2 = {}) { + var _a2, _b2; + options2 = { + ...this._playwright._defaultContextOptions, + ...options2 + }; + const storageState = typeof options2.storageState === "string" ? JSON.parse(await this._playwright._platform.fs().promises.readFile(options2.storageState, "utf8")) : options2.storageState; + const context = APIRequestContext.from((await this._playwright._channel.newRequest({ + ...options2, + extraHTTPHeaders: options2.extraHTTPHeaders ? headersObjectToArray(options2.extraHTTPHeaders) : void 0, + storageState, + tracesDir: (_a2 = this._playwright._defaultLaunchOptions) == null ? void 0 : _a2.tracesDir, + // We do not expose tracesDir in the API, so do not allow options to accidentally override it. + clientCertificates: await toClientCertificatesProtocol(this._playwright._platform, options2.clientCertificates) + })).request); + this._contexts.add(context); + context._request = this; + context._timeoutSettings.setDefaultTimeout(options2.timeout ?? this._playwright._defaultContextTimeout); + context._tracing._tracesDir = (_b2 = this._playwright._defaultLaunchOptions) == null ? void 0 : _b2.tracesDir; + await context._instrumentation.runAfterCreateRequestContext(context); + return context; + } +} +class APIRequestContext extends ChannelOwner { + static from(channel) { + return channel._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._tracing = Tracing2.from(initializer.tracing); + this._timeoutSettings = new TimeoutSettings(this._platform); + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + async dispose(options2 = {}) { + var _a2; + this._closeReason = options2.reason; + await this._instrumentation.runBeforeCloseRequestContext(this); + try { + await this._channel.dispose(options2); + } catch (e) { + if (isTargetClosedError(e)) + return; + throw e; + } + this._tracing._resetStackCounter(); + (_a2 = this._request) == null ? void 0 : _a2._contexts.delete(this); + } + async delete(url2, options2) { + return await this.fetch(url2, { + ...options2, + method: "DELETE" + }); + } + async head(url2, options2) { + return await this.fetch(url2, { + ...options2, + method: "HEAD" + }); + } + async get(url2, options2) { + return await this.fetch(url2, { + ...options2, + method: "GET" + }); + } + async patch(url2, options2) { + return await this.fetch(url2, { + ...options2, + method: "PATCH" + }); + } + async post(url2, options2) { + return await this.fetch(url2, { + ...options2, + method: "POST" + }); + } + async put(url2, options2) { + return await this.fetch(url2, { + ...options2, + method: "PUT" + }); + } + async fetch(urlOrRequest, options2 = {}) { + const url2 = isString(urlOrRequest) ? urlOrRequest : void 0; + const request2 = isString(urlOrRequest) ? void 0 : urlOrRequest; + return await this._innerFetch({ url: url2, request: request2, ...options2 }); + } + async _innerFetch(options2 = {}) { + return await this._wrapApiCall(async () => { + var _a2, _b2, _c2; + if (this._closeReason) + throw new TargetClosedError2(this._closeReason); + assert(options2.request || typeof options2.url === "string", "First argument must be either URL string or Request"); + assert((options2.data === void 0 ? 0 : 1) + (options2.form === void 0 ? 0 : 1) + (options2.multipart === void 0 ? 0 : 1) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`); + assert(options2.maxRedirects === void 0 || options2.maxRedirects >= 0, `'maxRedirects' must be greater than or equal to '0'`); + assert(options2.maxRetries === void 0 || options2.maxRetries >= 0, `'maxRetries' must be greater than or equal to '0'`); + const url2 = options2.url !== void 0 ? options2.url : options2.request.url(); + const method = options2.method || ((_a2 = options2.request) == null ? void 0 : _a2.method()); + let encodedParams = void 0; + if (typeof options2.params === "string") + encodedParams = options2.params; + else if (options2.params instanceof URLSearchParams) + encodedParams = options2.params.toString(); + const headersObj = options2.headers || ((_b2 = options2.request) == null ? void 0 : _b2.headers()); + const headers = headersObj ? headersObjectToArray(headersObj) : void 0; + let jsonData; + let formData; + let multipartData; + let postDataBuffer; + if (options2.data !== void 0) { + if (isString(options2.data)) { + if (isJsonContentType(headers)) + jsonData = isJsonParsable(options2.data) ? options2.data : JSON.stringify(options2.data); + else + postDataBuffer = Buffer.from(options2.data, "utf8"); + } else if (Buffer.isBuffer(options2.data)) { + postDataBuffer = options2.data; + } else if (typeof options2.data === "object" || typeof options2.data === "number" || typeof options2.data === "boolean") { + jsonData = JSON.stringify(options2.data); + } else { + throw new Error(`Unexpected 'data' type`); + } + } else if (options2.form) { + if (globalThis.FormData && options2.form instanceof FormData) { + formData = []; + for (const [name, value] of options2.form.entries()) { + if (typeof value !== "string") + throw new Error(`Expected string for options.form["${name}"], found File. Please use options.multipart instead.`); + formData.push({ name, value }); + } + } else { + formData = objectToArray(options2.form); + } + } else if (options2.multipart) { + multipartData = []; + if (globalThis.FormData && options2.multipart instanceof FormData) { + const form = options2.multipart; + for (const [name, value] of form.entries()) { + if (isString(value)) { + multipartData.push({ name, value }); + } else { + const file = { + name: value.name, + mimeType: value.type, + buffer: Buffer.from(await value.arrayBuffer()) + }; + multipartData.push({ name, file }); + } + } + } else { + for (const [name, value] of Object.entries(options2.multipart)) + multipartData.push(await toFormField(this._platform, name, value)); + } + } + if (postDataBuffer === void 0 && jsonData === void 0 && formData === void 0 && multipartData === void 0) + postDataBuffer = ((_c2 = options2.request) == null ? void 0 : _c2.postDataBuffer()) || void 0; + const fixtures = { + __testHookLookup: options2.__testHookLookup + }; + const result = await this._channel.fetch({ + url: url2, + params: typeof options2.params === "object" ? objectToArray(options2.params) : void 0, + encodedParams, + method, + headers, + postData: postDataBuffer, + jsonData, + formData, + multipartData, + timeout: this._timeoutSettings.timeout(options2), + failOnStatusCode: options2.failOnStatusCode, + ignoreHTTPSErrors: options2.ignoreHTTPSErrors, + maxRedirects: options2.maxRedirects, + maxRetries: options2.maxRetries, + ...fixtures + }); + return new APIResponse(this, result.response); + }); + } + async storageState(options2 = {}) { + const state2 = await this._channel.storageState({ indexedDB: options2.indexedDB }); + if (options2.path) { + await mkdirIfNeeded(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, JSON.stringify(state2, void 0, 2), "utf8"); + } + return state2; + } +} +async function toFormField(platform, name, value) { + const typeOfValue = typeof value; + if (isFilePayload(value)) { + const payload = value; + if (!Buffer.isBuffer(payload.buffer)) + throw new Error(`Unexpected buffer type of 'data.${name}'`); + return { name, file: filePayloadToJson(payload) }; + } else if (typeOfValue === "string" || typeOfValue === "number" || typeOfValue === "boolean") { + return { name, value: String(value) }; + } else { + return { name, file: await readStreamToJson(platform, value) }; + } +} +function isJsonParsable(value) { + if (typeof value !== "string") + return false; + try { + JSON.parse(value); + return true; + } catch (e) { + if (e instanceof SyntaxError) + return false; + else + throw e; + } +} +class APIResponse { + constructor(context, initializer) { + this._request = context; + this._initializer = initializer; + this._headers = new RawHeaders(this._initializer.headers); + if (context._platform.inspectCustom) + this[context._platform.inspectCustom] = () => this._inspect(); + } + ok() { + return this._initializer.status >= 200 && this._initializer.status <= 299; + } + url() { + return this._initializer.url; + } + status() { + return this._initializer.status; + } + statusText() { + return this._initializer.statusText; + } + headers() { + return this._headers.headers(); + } + headersArray() { + return this._headers.headersArray(); + } + async body() { + return await this._request._wrapApiCall(async () => { + try { + const result = await this._request._channel.fetchResponseBody({ fetchUid: this._fetchUid() }); + if (result.binary === void 0) + throw new Error("Response has been disposed"); + return result.binary; + } catch (e) { + if (isTargetClosedError(e)) + throw new Error("Response has been disposed"); + throw e; + } + }, { internal: true }); + } + async text() { + const content = await this.body(); + return content.toString("utf8"); + } + async json() { + const content = await this.text(); + return JSON.parse(content); + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + async dispose() { + await this._request._channel.disposeAPIResponse({ fetchUid: this._fetchUid() }); + } + _inspect() { + const headers = this.headersArray().map(({ name, value }) => ` ${name}: ${value}`); + return `APIResponse: ${this.status()} ${this.statusText()} +${headers.join("\n")}`; + } + _fetchUid() { + return this._initializer.fetchUid; + } + async _fetchLog() { + const { log } = await this._request._channel.fetchLog({ fetchUid: this._fetchUid() }); + return log; + } +} +function filePayloadToJson(payload) { + return { + name: payload.name, + mimeType: payload.mimeType, + buffer: payload.buffer + }; +} +async function readStreamToJson(platform, stream2) { + const buffer2 = await new Promise((resolve, reject) => { + const chunks = []; + stream2.on("data", (chunk) => chunks.push(chunk)); + stream2.on("end", () => resolve(Buffer.concat(chunks))); + stream2.on("error", (err) => reject(err)); + }); + const streamPath = Buffer.isBuffer(stream2.path) ? stream2.path.toString("utf8") : stream2.path; + return { + name: platform.path().basename(streamPath), + buffer: buffer2 + }; +} +function isJsonContentType(headers) { + if (!headers) + return false; + for (const { name, value } of headers) { + if (name.toLocaleLowerCase() === "content-type") + return value === "application/json"; + } + return false; +} +function objectToArray(map2) { + if (!map2) + return void 0; + const result = []; + for (const [name, value] of Object.entries(map2)) { + if (value !== void 0) + result.push({ name, value: String(value) }); + } + return result; +} +function isFilePayload(value) { + return typeof value === "object" && value["name"] && value["mimeType"] && value["buffer"]; +} +class Waiter { + constructor(channelOwner, event) { + this._failures = []; + this._logs = []; + this._waitId = channelOwner._platform.createGuid(); + this._channelOwner = channelOwner; + this._savedZone = channelOwner._platform.zones.current().pop(); + this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "before", event } }).catch(() => { + }); + this._dispose = [ + () => this._channelOwner._wrapApiCall(async () => { + await this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "after", error: this._error } }); + }, { internal: true }).catch(() => { + }) + ]; + } + static createForEvent(channelOwner, event) { + return new Waiter(channelOwner, event); + } + async waitForEvent(emitter, event, predicate) { + const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate); + return await this.waitForPromise(promise, dispose); + } + rejectOnEvent(emitter, event, error2, predicate) { + const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate); + this._rejectOn(promise.then(() => { + throw typeof error2 === "function" ? error2() : error2; + }), dispose); + } + rejectOnTimeout(timeout, message) { + if (!timeout) + return; + const { promise, dispose } = waitForTimeout(timeout); + this._rejectOn(promise.then(() => { + throw new TimeoutError2(message); + }), dispose); + } + rejectImmediately(error2) { + this._immediateError = error2; + } + dispose() { + for (const dispose of this._dispose) + dispose(); + } + async waitForPromise(promise, dispose) { + try { + if (this._immediateError) + throw this._immediateError; + const result = await Promise.race([promise, ...this._failures]); + if (dispose) + dispose(); + return result; + } catch (e) { + if (dispose) + dispose(); + this._error = e.message; + this.dispose(); + rewriteErrorMessage(e, e.message + formatLogRecording(this._logs)); + throw e; + } + } + log(s) { + this._logs.push(s); + this._channelOwner._wrapApiCall(async () => { + await this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "log", message: s } }); + }, { internal: true }).catch(() => { + }); + } + _rejectOn(promise, dispose) { + this._failures.push(promise); + if (dispose) + this._dispose.push(dispose); + } +} +function waitForEvent(emitter, event, savedZone, predicate) { + let listener; + const promise = new Promise((resolve, reject) => { + listener = async (eventArg) => { + await savedZone.run(async () => { + try { + if (predicate && !await predicate(eventArg)) + return; + emitter.removeListener(event, listener); + resolve(eventArg); + } catch (e) { + emitter.removeListener(event, listener); + reject(e); + } + }); + }; + emitter.addListener(event, listener); + }); + const dispose = () => emitter.removeListener(event, listener); + return { promise, dispose }; +} +function waitForTimeout(timeout) { + let timeoutId; + const promise = new Promise((resolve) => timeoutId = setTimeout(resolve, timeout)); + const dispose = () => clearTimeout(timeoutId); + return { promise, dispose }; +} +function formatLogRecording(log) { + if (!log.length) + return ""; + const header = ` logs `; + const headerLength = 60; + const leftLength = (headerLength - header.length) / 2; + const rightLength = headerLength - header.length - leftLength; + return ` +${"=".repeat(leftLength)}${header}${"=".repeat(rightLength)} +${log.join("\n")} +${"=".repeat(headerLength)}`; +} +class Worker extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._closedScope = new LongStandingScope(); + this._channel.on("close", () => { + if (this._page) + this._page._workers.delete(this); + if (this._context) + this._context._serviceWorkers.delete(this); + this.emit(Events.Worker.Close, this); + }); + this.once(Events.Worker.Close, () => { + var _a2; + return this._closedScope.close(((_a2 = this._page) == null ? void 0 : _a2._closeErrorWithReason()) || new TargetClosedError2()); + }); + } + static from(worker) { + return worker._object; + } + url() { + return this._initializer.url; + } + async evaluate(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async evaluateHandle(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result.handle); + } +} +class Request2 extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._redirectedFrom = null; + this._redirectedTo = null; + this._failureText = null; + this._fallbackOverrides = {}; + this._redirectedFrom = Request2.fromNullable(initializer.redirectedFrom); + if (this._redirectedFrom) + this._redirectedFrom._redirectedTo = this; + this._provisionalHeaders = new RawHeaders(initializer.headers); + this._timing = { + startTime: 0, + domainLookupStart: -1, + domainLookupEnd: -1, + connectStart: -1, + secureConnectionStart: -1, + connectEnd: -1, + requestStart: -1, + responseStart: -1, + responseEnd: -1 + }; + } + static from(request2) { + return request2._object; + } + static fromNullable(request2) { + return request2 ? Request2.from(request2) : null; + } + url() { + return this._fallbackOverrides.url || this._initializer.url; + } + resourceType() { + return this._initializer.resourceType; + } + method() { + return this._fallbackOverrides.method || this._initializer.method; + } + postData() { + var _a2; + return ((_a2 = this._fallbackOverrides.postDataBuffer || this._initializer.postData) == null ? void 0 : _a2.toString("utf-8")) || null; + } + postDataBuffer() { + return this._fallbackOverrides.postDataBuffer || this._initializer.postData || null; + } + postDataJSON() { + const postData = this.postData(); + if (!postData) + return null; + const contentType = this.headers()["content-type"]; + if (contentType == null ? void 0 : contentType.includes("application/x-www-form-urlencoded")) { + const entries = {}; + const parsed = new URLSearchParams(postData); + for (const [k, v] of parsed.entries()) + entries[k] = v; + return entries; + } + try { + return JSON.parse(postData); + } catch (e) { + throw new Error("POST data is not a valid JSON object: " + postData); + } + } + /** + * @deprecated + */ + headers() { + if (this._fallbackOverrides.headers) + return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers).headers(); + return this._provisionalHeaders.headers(); + } + async _actualHeaders() { + if (this._fallbackOverrides.headers) + return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers); + if (!this._actualHeadersPromise) { + this._actualHeadersPromise = this._wrapApiCall(async () => { + return new RawHeaders((await this._channel.rawRequestHeaders()).headers); + }, { internal: true }); + } + return await this._actualHeadersPromise; + } + async allHeaders() { + return (await this._actualHeaders()).headers(); + } + async headersArray() { + return (await this._actualHeaders()).headersArray(); + } + async headerValue(name) { + return (await this._actualHeaders()).get(name); + } + async response() { + return Response2.fromNullable((await this._channel.response()).response); + } + async _internalResponse() { + return Response2.fromNullable((await this._channel.response()).response); + } + frame() { + if (!this._initializer.frame) { + assert(this.serviceWorker()); + throw new Error("Service Worker requests do not have an associated frame."); + } + const frame = Frame.from(this._initializer.frame); + if (!frame._page) { + throw new Error([ + "Frame for this navigation request is not available, because the request", + "was issued before the frame is created. You can check whether the request", + "is a navigation request by calling isNavigationRequest() method." + ].join("\n")); + } + return frame; + } + _safePage() { + var _a2; + return ((_a2 = Frame.fromNullable(this._initializer.frame)) == null ? void 0 : _a2._page) || null; + } + serviceWorker() { + return this._initializer.serviceWorker ? Worker.from(this._initializer.serviceWorker) : null; + } + isNavigationRequest() { + return this._initializer.isNavigationRequest; + } + redirectedFrom() { + return this._redirectedFrom; + } + redirectedTo() { + return this._redirectedTo; + } + failure() { + if (this._failureText === null) + return null; + return { + errorText: this._failureText + }; + } + timing() { + return this._timing; + } + async sizes() { + const response2 = await this.response(); + if (!response2) + throw new Error("Unable to fetch sizes for failed request"); + return (await response2._channel.sizes()).sizes; + } + _setResponseEndTiming(responseEndTiming) { + this._timing.responseEnd = responseEndTiming; + if (this._timing.responseStart === -1) + this._timing.responseStart = responseEndTiming; + } + _finalRequest() { + return this._redirectedTo ? this._redirectedTo._finalRequest() : this; + } + _applyFallbackOverrides(overrides) { + if (overrides.url) + this._fallbackOverrides.url = overrides.url; + if (overrides.method) + this._fallbackOverrides.method = overrides.method; + if (overrides.headers) + this._fallbackOverrides.headers = overrides.headers; + if (isString(overrides.postData)) + this._fallbackOverrides.postDataBuffer = Buffer.from(overrides.postData, "utf-8"); + else if (overrides.postData instanceof Buffer) + this._fallbackOverrides.postDataBuffer = overrides.postData; + else if (overrides.postData) + this._fallbackOverrides.postDataBuffer = Buffer.from(JSON.stringify(overrides.postData), "utf-8"); + } + _fallbackOverridesForContinue() { + return this._fallbackOverrides; + } + _targetClosedScope() { + var _a2, _b2; + return ((_a2 = this.serviceWorker()) == null ? void 0 : _a2._closedScope) || ((_b2 = this._safePage()) == null ? void 0 : _b2._closedOrCrashedScope) || new LongStandingScope(); + } +} +class Route2 extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._handlingPromise = null; + this._didThrow = false; + } + static from(route) { + return route._object; + } + request() { + return Request2.from(this._initializer.request); + } + async _raceWithTargetClose(promise) { + return await this.request()._targetClosedScope().safeRace(promise); + } + async _startHandling() { + this._handlingPromise = new ManualPromise(); + return await this._handlingPromise; + } + async fallback(options2 = {}) { + this._checkNotHandled(); + this.request()._applyFallbackOverrides(options2); + this._reportHandled(false); + } + async abort(errorCode) { + await this._handleRoute(async () => { + await this._raceWithTargetClose(this._channel.abort({ errorCode })); + }); + } + async _redirectNavigationRequest(url2) { + await this._handleRoute(async () => { + await this._raceWithTargetClose(this._channel.redirectNavigationRequest({ url: url2 })); + }); + } + async fetch(options2 = {}) { + return await this._wrapApiCall(async () => { + return await this._context.request._innerFetch({ request: this.request(), data: options2.postData, ...options2 }); + }); + } + async fulfill(options2 = {}) { + await this._handleRoute(async () => { + await this._innerFulfill(options2); + }); + } + async _handleRoute(callback) { + this._checkNotHandled(); + try { + await callback(); + this._reportHandled(true); + } catch (e) { + this._didThrow = true; + throw e; + } + } + async _innerFulfill(options2 = {}) { + let fetchResponseUid; + let { status: statusOption, headers: headersOption, body } = options2; + if (options2.json !== void 0) { + assert(options2.body === void 0, "Can specify either body or json parameters"); + body = JSON.stringify(options2.json); + } + if (options2.response instanceof APIResponse) { + statusOption ?? (statusOption = options2.response.status()); + headersOption ?? (headersOption = options2.response.headers()); + if (body === void 0 && options2.path === void 0) { + if (options2.response._request._connection === this._connection) + fetchResponseUid = options2.response._fetchUid(); + else + body = await options2.response.body(); + } + } + let isBase64 = false; + let length = 0; + if (options2.path) { + const buffer2 = await this._platform.fs().promises.readFile(options2.path); + body = buffer2.toString("base64"); + isBase64 = true; + length = buffer2.length; + } else if (isString(body)) { + isBase64 = false; + length = Buffer.byteLength(body); + } else if (body) { + length = body.length; + body = body.toString("base64"); + isBase64 = true; + } + const headers = {}; + for (const header of Object.keys(headersOption || {})) + headers[header.toLowerCase()] = String(headersOption[header]); + if (options2.contentType) + headers["content-type"] = String(options2.contentType); + else if (options2.json) + headers["content-type"] = "application/json"; + else if (options2.path) + headers["content-type"] = getMimeTypeForPath(options2.path) || "application/octet-stream"; + if (length && !("content-length" in headers)) + headers["content-length"] = String(length); + await this._raceWithTargetClose(this._channel.fulfill({ + status: statusOption || 200, + headers: headersObjectToArray(headers), + body, + isBase64, + fetchResponseUid + })); + } + async continue(options2 = {}) { + await this._handleRoute(async () => { + this.request()._applyFallbackOverrides(options2); + await this._innerContinue( + false + /* isFallback */ + ); + }); + } + _checkNotHandled() { + if (!this._handlingPromise) + throw new Error("Route is already handled!"); + } + _reportHandled(done) { + const chain = this._handlingPromise; + this._handlingPromise = null; + chain.resolve(done); + } + async _innerContinue(isFallback) { + const options2 = this.request()._fallbackOverridesForContinue(); + return await this._raceWithTargetClose(this._channel.continue({ + url: options2.url, + method: options2.method, + headers: options2.headers ? headersObjectToArray(options2.headers) : void 0, + postData: options2.postDataBuffer, + isFallback + })); + } +} +class WebSocketRoute extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._connected = false; + this._server = { + onMessage: (handler) => { + this._onServerMessage = handler; + }, + onClose: (handler) => { + this._onServerClose = handler; + }, + connectToServer: () => { + throw new Error(`connectToServer must be called on the page-side WebSocketRoute`); + }, + url: () => { + return this._initializer.url; + }, + close: async (options2 = {}) => { + await this._channel.closeServer({ ...options2, wasClean: true }).catch(() => { + }); + }, + send: (message) => { + if (isString(message)) + this._channel.sendToServer({ message, isBase64: false }).catch(() => { + }); + else + this._channel.sendToServer({ message: message.toString("base64"), isBase64: true }).catch(() => { + }); + }, + async [Symbol.asyncDispose]() { + await this.close(); + } + }; + this._channel.on("messageFromPage", ({ message, isBase64 }) => { + if (this._onPageMessage) + this._onPageMessage(isBase64 ? Buffer.from(message, "base64") : message); + else if (this._connected) + this._channel.sendToServer({ message, isBase64 }).catch(() => { + }); + }); + this._channel.on("messageFromServer", ({ message, isBase64 }) => { + if (this._onServerMessage) + this._onServerMessage(isBase64 ? Buffer.from(message, "base64") : message); + else + this._channel.sendToPage({ message, isBase64 }).catch(() => { + }); + }); + this._channel.on("closePage", ({ code, reason, wasClean }) => { + if (this._onPageClose) + this._onPageClose(code, reason); + else + this._channel.closeServer({ code, reason, wasClean }).catch(() => { + }); + }); + this._channel.on("closeServer", ({ code, reason, wasClean }) => { + if (this._onServerClose) + this._onServerClose(code, reason); + else + this._channel.closePage({ code, reason, wasClean }).catch(() => { + }); + }); + } + static from(route) { + return route._object; + } + url() { + return this._initializer.url; + } + async close(options2 = {}) { + await this._channel.closePage({ ...options2, wasClean: true }).catch(() => { + }); + } + connectToServer() { + if (this._connected) + throw new Error("Already connected to the server"); + this._connected = true; + this._channel.connect().catch(() => { + }); + return this._server; + } + send(message) { + if (isString(message)) + this._channel.sendToPage({ message, isBase64: false }).catch(() => { + }); + else + this._channel.sendToPage({ message: message.toString("base64"), isBase64: true }).catch(() => { + }); + } + onMessage(handler) { + this._onPageMessage = handler; + } + onClose(handler) { + this._onPageClose = handler; + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async _afterHandle() { + if (this._connected) + return; + await this._channel.ensureOpened(); + } +} +class WebSocketRouteHandler { + constructor(baseURL, url2, handler) { + this._baseURL = baseURL; + this.url = url2; + this.handler = handler; + } + static prepareInterceptionPatterns(handlers) { + const patterns = []; + let all = false; + for (const handler of handlers) { + if (isString(handler.url)) + patterns.push({ glob: handler.url }); + else if (isRegExp$4(handler.url)) + patterns.push({ regexSource: handler.url.source, regexFlags: handler.url.flags }); + else + all = true; + } + if (all) + return [{ glob: "**/*" }]; + return patterns; + } + matches(wsURL) { + return urlMatches(this._baseURL, wsURL, this.url, true); + } + async handle(webSocketRoute) { + const handler = this.handler; + await handler(webSocketRoute); + await webSocketRoute._afterHandle(); + } +} +class Response2 extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._finishedPromise = new ManualPromise(); + this._provisionalHeaders = new RawHeaders(initializer.headers); + this._request = Request2.from(this._initializer.request); + Object.assign(this._request._timing, this._initializer.timing); + } + static from(response2) { + return response2._object; + } + static fromNullable(response2) { + return response2 ? Response2.from(response2) : null; + } + url() { + return this._initializer.url; + } + ok() { + return this._initializer.status === 0 || this._initializer.status >= 200 && this._initializer.status <= 299; + } + status() { + return this._initializer.status; + } + statusText() { + return this._initializer.statusText; + } + fromServiceWorker() { + return this._initializer.fromServiceWorker; + } + /** + * @deprecated + */ + headers() { + return this._provisionalHeaders.headers(); + } + async _actualHeaders() { + if (!this._actualHeadersPromise) { + this._actualHeadersPromise = (async () => { + return new RawHeaders((await this._channel.rawResponseHeaders()).headers); + })(); + } + return await this._actualHeadersPromise; + } + async allHeaders() { + return (await this._actualHeaders()).headers(); + } + async headersArray() { + return (await this._actualHeaders()).headersArray().slice(); + } + async headerValue(name) { + return (await this._actualHeaders()).get(name); + } + async headerValues(name) { + return (await this._actualHeaders()).getAll(name); + } + async finished() { + return await this.request()._targetClosedScope().race(this._finishedPromise); + } + async body() { + return (await this._channel.body()).binary; + } + async text() { + const content = await this.body(); + return content.toString("utf8"); + } + async json() { + const content = await this.text(); + return JSON.parse(content); + } + request() { + return this._request; + } + frame() { + return this._request.frame(); + } + async serverAddr() { + return (await this._channel.serverAddr()).value || null; + } + async securityDetails() { + return (await this._channel.securityDetails()).value || null; + } +} +class WebSocket extends ChannelOwner { + static from(webSocket) { + return webSocket._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._isClosed = false; + this._page = parent; + this._channel.on("frameSent", (event) => { + if (event.opcode === 1) + this.emit(Events.WebSocket.FrameSent, { payload: event.data }); + else if (event.opcode === 2) + this.emit(Events.WebSocket.FrameSent, { payload: Buffer.from(event.data, "base64") }); + }); + this._channel.on("frameReceived", (event) => { + if (event.opcode === 1) + this.emit(Events.WebSocket.FrameReceived, { payload: event.data }); + else if (event.opcode === 2) + this.emit(Events.WebSocket.FrameReceived, { payload: Buffer.from(event.data, "base64") }); + }); + this._channel.on("socketError", ({ error: error2 }) => this.emit(Events.WebSocket.Error, error2)); + this._channel.on("close", () => { + this._isClosed = true; + this.emit(Events.WebSocket.Close, this); + }); + } + url() { + return this._initializer.url; + } + isClosed() { + return this._isClosed; + } + async waitForEvent(event, optionsOrPredicate = {}) { + return await this._wrapApiCall(async () => { + const timeout = this._page._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate); + const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate; + const waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`); + if (event !== Events.WebSocket.Error) + waiter.rejectOnEvent(this, Events.WebSocket.Error, new Error("Socket error")); + if (event !== Events.WebSocket.Close) + waiter.rejectOnEvent(this, Events.WebSocket.Close, new Error("Socket closed")); + waiter.rejectOnEvent(this._page, Events.Page.Close, () => this._page._closeErrorWithReason()); + const result = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result; + }); + } +} +function validateHeaders(headers) { + for (const key2 of Object.keys(headers)) { + const value = headers[key2]; + if (!Object.is(value, void 0) && !isString(value)) + throw new Error(`Expected value of header "${key2}" to be String, but "${typeof value}" is found.`); + } +} +class RouteHandler { + constructor(platform, baseURL, url2, handler, times = Number.MAX_SAFE_INTEGER) { + this.handledCount = 0; + this._ignoreException = false; + this._activeInvocations = /* @__PURE__ */ new Set(); + this._baseURL = baseURL; + this._times = times; + this.url = url2; + this.handler = handler; + this._savedZone = platform.zones.current().pop(); + } + static prepareInterceptionPatterns(handlers) { + const patterns = []; + let all = false; + for (const handler of handlers) { + if (isString(handler.url)) + patterns.push({ glob: handler.url }); + else if (isRegExp$4(handler.url)) + patterns.push({ regexSource: handler.url.source, regexFlags: handler.url.flags }); + else + all = true; + } + if (all) + return [{ glob: "**/*" }]; + return patterns; + } + matches(requestURL) { + return urlMatches(this._baseURL, requestURL, this.url); + } + async handle(route) { + return await this._savedZone.run(async () => this._handleImpl(route)); + } + async _handleImpl(route) { + const handlerInvocation = { complete: new ManualPromise(), route }; + this._activeInvocations.add(handlerInvocation); + try { + return await this._handleInternal(route); + } catch (e) { + if (this._ignoreException) + return false; + if (isTargetClosedError(e)) { + rewriteErrorMessage(e, `"${e.message}" while running route callback. +Consider awaiting \`await page.unrouteAll({ behavior: 'ignoreErrors' })\` +before the end of the test to ignore remaining routes in flight.`); + } + throw e; + } finally { + handlerInvocation.complete.resolve(); + this._activeInvocations.delete(handlerInvocation); + } + } + async stop(behavior) { + if (behavior === "ignoreErrors") { + this._ignoreException = true; + } else { + const promises2 = []; + for (const activation of this._activeInvocations) { + if (!activation.route._didThrow) + promises2.push(activation.complete); + } + await Promise.all(promises2); + } + } + async _handleInternal(route) { + ++this.handledCount; + const handledPromise = route._startHandling(); + const handler = this.handler; + const [handled] = await Promise.all([ + handledPromise, + handler(route, route.request()) + ]); + return handled; + } + willExpire() { + return this.handledCount + 1 >= this._times; + } +} +class RawHeaders { + constructor(headers) { + this._headersMap = new MultiMap(); + this._headersArray = headers; + for (const header of headers) + this._headersMap.set(header.name.toLowerCase(), header.value); + } + static _fromHeadersObjectLossy(headers) { + const headersArray = Object.entries(headers).map(([name, value]) => ({ + name, + value + })).filter((header) => header.value !== void 0); + return new RawHeaders(headersArray); + } + get(name) { + const values = this.getAll(name); + if (!values || !values.length) + return null; + return values.join(name.toLowerCase() === "set-cookie" ? "\n" : ", "); + } + getAll(name) { + return [...this._headersMap.get(name.toLowerCase())]; + } + headers() { + const result = {}; + for (const name of this._headersMap.keys()) + result[name] = this.get(name); + return result; + } + headersArray() { + return this._headersArray; + } +} +const kLifecycleEvents = /* @__PURE__ */ new Set(["load", "domcontentloaded", "networkidle", "commit"]); +class Frame extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._parentFrame = null; + this._url = ""; + this._name = ""; + this._detached = false; + this._childFrames = /* @__PURE__ */ new Set(); + this._eventEmitter = new EventEmitter(parent._platform); + this._eventEmitter.setMaxListeners(0); + this._parentFrame = Frame.fromNullable(initializer.parentFrame); + if (this._parentFrame) + this._parentFrame._childFrames.add(this); + this._name = initializer.name; + this._url = initializer.url; + this._loadStates = new Set(initializer.loadStates); + this._channel.on("loadstate", (event) => { + if (event.add) { + this._loadStates.add(event.add); + this._eventEmitter.emit("loadstate", event.add); + } + if (event.remove) + this._loadStates.delete(event.remove); + if (!this._parentFrame && event.add === "load" && this._page) + this._page.emit(Events.Page.Load, this._page); + if (!this._parentFrame && event.add === "domcontentloaded" && this._page) + this._page.emit(Events.Page.DOMContentLoaded, this._page); + }); + this._channel.on("navigated", (event) => { + this._url = event.url; + this._name = event.name; + this._eventEmitter.emit("navigated", event); + if (!event.error && this._page) + this._page.emit(Events.Page.FrameNavigated, this); + }); + } + static from(frame) { + return frame._object; + } + static fromNullable(frame) { + return frame ? Frame.from(frame) : null; + } + page() { + return this._page; + } + _timeout(options2) { + var _a2; + const timeoutSettings = ((_a2 = this._page) == null ? void 0 : _a2._timeoutSettings) || new TimeoutSettings(this._platform); + return timeoutSettings.timeout(options2 || {}); + } + _navigationTimeout(options2) { + var _a2; + const timeoutSettings = ((_a2 = this._page) == null ? void 0 : _a2._timeoutSettings) || new TimeoutSettings(this._platform); + return timeoutSettings.navigationTimeout(options2 || {}); + } + async goto(url2, options2 = {}) { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + return Response2.fromNullable((await this._channel.goto({ url: url2, ...options2, waitUntil, timeout: this._navigationTimeout(options2) })).response); + } + _setupNavigationWaiter(options2) { + const waiter = new Waiter(this._page, ""); + if (this._page.isClosed()) + waiter.rejectImmediately(this._page._closeErrorWithReason()); + waiter.rejectOnEvent(this._page, Events.Page.Close, () => this._page._closeErrorWithReason()); + waiter.rejectOnEvent(this._page, Events.Page.Crash, new Error("Navigation failed because page crashed!")); + waiter.rejectOnEvent(this._page, Events.Page.FrameDetached, new Error("Navigating frame was detached!"), (frame) => frame === this); + const timeout = this._page._timeoutSettings.navigationTimeout(options2); + waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded.`); + return waiter; + } + async waitForNavigation(options2 = {}) { + return await this._page._wrapApiCall(async () => { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + const waiter = this._setupNavigationWaiter(options2); + const toUrl = typeof options2.url === "string" ? ` to "${options2.url}"` : ""; + waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`); + const navigatedEvent = await waiter.waitForEvent(this._eventEmitter, "navigated", (event) => { + var _a2; + if (event.error) + return true; + waiter.log(` navigated to "${event.url}"`); + return urlMatches((_a2 = this._page) == null ? void 0 : _a2.context()._options.baseURL, event.url, options2.url); + }); + if (navigatedEvent.error) { + const e = new Error(navigatedEvent.error); + e.stack = ""; + await waiter.waitForPromise(Promise.reject(e)); + } + if (!this._loadStates.has(waitUntil)) { + await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => { + waiter.log(` "${s}" event fired`); + return s === waitUntil; + }); + } + const request2 = navigatedEvent.newDocument ? Request2.fromNullable(navigatedEvent.newDocument.request) : null; + const response2 = request2 ? await waiter.waitForPromise(request2._finalRequest()._internalResponse()) : null; + waiter.dispose(); + return response2; + }, { title: "Wait for navigation" }); + } + async waitForLoadState(state2 = "load", options2 = {}) { + state2 = verifyLoadState("state", state2); + return await this._page._wrapApiCall(async () => { + const waiter = this._setupNavigationWaiter(options2); + if (this._loadStates.has(state2)) { + waiter.log(` not waiting, "${state2}" event already fired`); + } else { + await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => { + waiter.log(` "${s}" event fired`); + return s === state2; + }); + } + waiter.dispose(); + }, { title: `Wait for load state "${state2}"` }); + } + async waitForURL(url2, options2 = {}) { + var _a2; + if (urlMatches((_a2 = this._page) == null ? void 0 : _a2.context()._options.baseURL, this.url(), url2)) + return await this.waitForLoadState(options2.waitUntil, options2); + await this.waitForNavigation({ url: url2, ...options2 }); + } + async frameElement() { + return ElementHandle2.from((await this._channel.frameElement()).element); + } + async evaluateHandle(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result.handle); + } + async evaluate(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async _evaluateExposeUtilityScript(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async $(selector, options2) { + const result = await this._channel.querySelector({ selector, ...options2 }); + return ElementHandle2.fromNullable(result.element); + } + async waitForSelector(selector, options2 = {}) { + if (options2.visibility) + throw new Error("options.visibility is not supported, did you mean options.state?"); + if (options2.waitFor && options2.waitFor !== "visible") + throw new Error("options.waitFor is not supported, did you mean options.state?"); + const result = await this._channel.waitForSelector({ selector, ...options2, timeout: this._timeout(options2) }); + return ElementHandle2.fromNullable(result.element); + } + async dispatchEvent(selector, type2, eventInit, options2 = {}) { + await this._channel.dispatchEvent({ selector, type: type2, eventInit: serializeArgument(eventInit), ...options2, timeout: this._timeout(options2) }); + } + async $eval(selector, pageFunction, arg) { + assertMaxArguments(arguments.length, 3); + const result = await this._channel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async $$eval(selector, pageFunction, arg) { + assertMaxArguments(arguments.length, 3); + const result = await this._channel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async $$(selector) { + const result = await this._channel.querySelectorAll({ selector }); + return result.elements.map((e) => ElementHandle2.from(e)); + } + async _queryCount(selector) { + return (await this._channel.queryCount({ selector })).value; + } + async content() { + return (await this._channel.content()).value; + } + async setContent(html, options2 = {}) { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + await this._channel.setContent({ html, ...options2, waitUntil, timeout: this._navigationTimeout(options2) }); + } + name() { + return this._name || ""; + } + url() { + return this._url; + } + parentFrame() { + return this._parentFrame; + } + childFrames() { + return Array.from(this._childFrames); + } + isDetached() { + return this._detached; + } + async addScriptTag(options2 = {}) { + const copy = { ...options2 }; + if (copy.path) { + copy.content = (await this._platform.fs().promises.readFile(copy.path)).toString(); + copy.content = addSourceUrlToScript(copy.content, copy.path); + } + return ElementHandle2.from((await this._channel.addScriptTag({ ...copy })).element); + } + async addStyleTag(options2 = {}) { + const copy = { ...options2 }; + if (copy.path) { + copy.content = (await this._platform.fs().promises.readFile(copy.path)).toString(); + copy.content += "/*# sourceURL=" + copy.path.replace(/\n/g, "") + "*/"; + } + return ElementHandle2.from((await this._channel.addStyleTag({ ...copy })).element); + } + async click(selector, options2 = {}) { + return await this._channel.click({ selector, ...options2, timeout: this._timeout(options2) }); + } + async dblclick(selector, options2 = {}) { + return await this._channel.dblclick({ selector, ...options2, timeout: this._timeout(options2) }); + } + async dragAndDrop(source2, target, options2 = {}) { + return await this._channel.dragAndDrop({ source: source2, target, ...options2, timeout: this._timeout(options2) }); + } + async tap(selector, options2 = {}) { + return await this._channel.tap({ selector, ...options2, timeout: this._timeout(options2) }); + } + async fill(selector, value, options2 = {}) { + return await this._channel.fill({ selector, value, ...options2, timeout: this._timeout(options2) }); + } + async _highlight(selector) { + return await this._channel.highlight({ selector }); + } + locator(selector, options2) { + return new Locator(this, selector, options2); + } + getByTestId(testId) { + return this.locator(getByTestIdSelector(testIdAttributeName(), testId)); + } + getByAltText(text, options2) { + return this.locator(getByAltTextSelector(text, options2)); + } + getByLabel(text, options2) { + return this.locator(getByLabelSelector(text, options2)); + } + getByPlaceholder(text, options2) { + return this.locator(getByPlaceholderSelector(text, options2)); + } + getByText(text, options2) { + return this.locator(getByTextSelector(text, options2)); + } + getByTitle(text, options2) { + return this.locator(getByTitleSelector(text, options2)); + } + getByRole(role, options2 = {}) { + return this.locator(getByRoleSelector(role, options2)); + } + frameLocator(selector) { + return new FrameLocator(this, selector); + } + async focus(selector, options2 = {}) { + await this._channel.focus({ selector, ...options2, timeout: this._timeout(options2) }); + } + async textContent(selector, options2 = {}) { + const value = (await this._channel.textContent({ selector, ...options2, timeout: this._timeout(options2) })).value; + return value === void 0 ? null : value; + } + async innerText(selector, options2 = {}) { + return (await this._channel.innerText({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async innerHTML(selector, options2 = {}) { + return (await this._channel.innerHTML({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async getAttribute(selector, name, options2 = {}) { + const value = (await this._channel.getAttribute({ selector, name, ...options2, timeout: this._timeout(options2) })).value; + return value === void 0 ? null : value; + } + async inputValue(selector, options2 = {}) { + return (await this._channel.inputValue({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async isChecked(selector, options2 = {}) { + return (await this._channel.isChecked({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async isDisabled(selector, options2 = {}) { + return (await this._channel.isDisabled({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async isEditable(selector, options2 = {}) { + return (await this._channel.isEditable({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async isEnabled(selector, options2 = {}) { + return (await this._channel.isEnabled({ selector, ...options2, timeout: this._timeout(options2) })).value; + } + async isHidden(selector, options2 = {}) { + return (await this._channel.isHidden({ selector, ...options2 })).value; + } + async isVisible(selector, options2 = {}) { + return (await this._channel.isVisible({ selector, ...options2 })).value; + } + async hover(selector, options2 = {}) { + await this._channel.hover({ selector, ...options2, timeout: this._timeout(options2) }); + } + async selectOption(selector, values, options2 = {}) { + return (await this._channel.selectOption({ selector, ...convertSelectOptionValues(values), ...options2, timeout: this._timeout(options2) })).values; + } + async setInputFiles(selector, files, options2 = {}) { + const converted = await convertInputFiles(this._platform, files, this.page().context()); + await this._channel.setInputFiles({ selector, ...converted, ...options2, timeout: this._timeout(options2) }); + } + async type(selector, text, options2 = {}) { + await this._channel.type({ selector, text, ...options2, timeout: this._timeout(options2) }); + } + async press(selector, key2, options2 = {}) { + await this._channel.press({ selector, key: key2, ...options2, timeout: this._timeout(options2) }); + } + async check(selector, options2 = {}) { + await this._channel.check({ selector, ...options2, timeout: this._timeout(options2) }); + } + async uncheck(selector, options2 = {}) { + await this._channel.uncheck({ selector, ...options2, timeout: this._timeout(options2) }); + } + async setChecked(selector, checked, options2) { + if (checked) + await this.check(selector, options2); + else + await this.uncheck(selector, options2); + } + async waitForTimeout(timeout) { + await this._channel.waitForTimeout({ timeout }); + } + async waitForFunction(pageFunction, arg, options2 = {}) { + if (typeof options2.polling === "string") + assert(options2.polling === "raf", "Unknown polling option: " + options2.polling); + const result = await this._channel.waitForFunction({ + ...options2, + pollingInterval: options2.polling === "raf" ? void 0 : options2.polling, + expression: String(pageFunction), + isFunction: typeof pageFunction === "function", + arg: serializeArgument(arg), + timeout: this._timeout(options2) + }); + return JSHandle2.from(result.handle); + } + async title() { + return (await this._channel.title()).value; + } +} +function verifyLoadState(name, waitUntil) { + if (waitUntil === "networkidle0") + waitUntil = "networkidle"; + if (!kLifecycleEvents.has(waitUntil)) + throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`); + return waitUntil; +} +let WritableStream$1 = class WritableStream2 extends ChannelOwner { + static from(Stream2) { + return Stream2._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + } + stream() { + return this._platform.streamWritable(this._channel); + } +}; +class ElementHandle2 extends JSHandle2 { + static from(handle) { + return handle._object; + } + static fromNullable(handle) { + return handle ? ElementHandle2.from(handle) : null; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._frame = parent; + this._elementChannel = this._channel; + } + asElement() { + return this; + } + async ownerFrame() { + return Frame.fromNullable((await this._elementChannel.ownerFrame()).frame); + } + async contentFrame() { + return Frame.fromNullable((await this._elementChannel.contentFrame()).frame); + } + async _generateLocatorString() { + const value = (await this._elementChannel.generateLocatorString()).value; + return value === void 0 ? null : value; + } + async getAttribute(name) { + const value = (await this._elementChannel.getAttribute({ name })).value; + return value === void 0 ? null : value; + } + async inputValue() { + return (await this._elementChannel.inputValue()).value; + } + async textContent() { + const value = (await this._elementChannel.textContent()).value; + return value === void 0 ? null : value; + } + async innerText() { + return (await this._elementChannel.innerText()).value; + } + async innerHTML() { + return (await this._elementChannel.innerHTML()).value; + } + async isChecked() { + return (await this._elementChannel.isChecked()).value; + } + async isDisabled() { + return (await this._elementChannel.isDisabled()).value; + } + async isEditable() { + return (await this._elementChannel.isEditable()).value; + } + async isEnabled() { + return (await this._elementChannel.isEnabled()).value; + } + async isHidden() { + return (await this._elementChannel.isHidden()).value; + } + async isVisible() { + return (await this._elementChannel.isVisible()).value; + } + async dispatchEvent(type2, eventInit = {}) { + await this._elementChannel.dispatchEvent({ type: type2, eventInit: serializeArgument(eventInit) }); + } + async scrollIntoViewIfNeeded(options2 = {}) { + await this._elementChannel.scrollIntoViewIfNeeded({ ...options2, timeout: this._frame._timeout(options2) }); + } + async hover(options2 = {}) { + await this._elementChannel.hover({ ...options2, timeout: this._frame._timeout(options2) }); + } + async click(options2 = {}) { + return await this._elementChannel.click({ ...options2, timeout: this._frame._timeout(options2) }); + } + async dblclick(options2 = {}) { + return await this._elementChannel.dblclick({ ...options2, timeout: this._frame._timeout(options2) }); + } + async tap(options2 = {}) { + return await this._elementChannel.tap({ ...options2, timeout: this._frame._timeout(options2) }); + } + async selectOption(values, options2 = {}) { + const result = await this._elementChannel.selectOption({ ...convertSelectOptionValues(values), ...options2, timeout: this._frame._timeout(options2) }); + return result.values; + } + async fill(value, options2 = {}) { + return await this._elementChannel.fill({ value, ...options2, timeout: this._frame._timeout(options2) }); + } + async selectText(options2 = {}) { + await this._elementChannel.selectText({ ...options2, timeout: this._frame._timeout(options2) }); + } + async setInputFiles(files, options2 = {}) { + const frame = await this.ownerFrame(); + if (!frame) + throw new Error("Cannot set input files to detached element"); + const converted = await convertInputFiles(this._platform, files, frame.page().context()); + await this._elementChannel.setInputFiles({ ...converted, ...options2, timeout: this._frame._timeout(options2) }); + } + async focus() { + await this._elementChannel.focus(); + } + async type(text, options2 = {}) { + await this._elementChannel.type({ text, ...options2, timeout: this._frame._timeout(options2) }); + } + async press(key2, options2 = {}) { + await this._elementChannel.press({ key: key2, ...options2, timeout: this._frame._timeout(options2) }); + } + async check(options2 = {}) { + return await this._elementChannel.check({ ...options2, timeout: this._frame._timeout(options2) }); + } + async uncheck(options2 = {}) { + return await this._elementChannel.uncheck({ ...options2, timeout: this._frame._timeout(options2) }); + } + async setChecked(checked, options2) { + if (checked) + await this.check(options2); + else + await this.uncheck(options2); + } + async boundingBox() { + const value = (await this._elementChannel.boundingBox()).value; + return value === void 0 ? null : value; + } + async screenshot(options2 = {}) { + const mask = options2.mask; + const copy = { ...options2, mask: void 0, timeout: this._frame._timeout(options2) }; + if (!copy.type) + copy.type = determineScreenshotType(options2); + if (mask) { + copy.mask = mask.map((locator) => ({ + frame: locator._frame._channel, + selector: locator._selector + })); + } + const result = await this._elementChannel.screenshot(copy); + if (options2.path) { + await mkdirIfNeeded(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, result.binary); + } + return result.binary; + } + async $(selector) { + return ElementHandle2.fromNullable((await this._elementChannel.querySelector({ selector })).element); + } + async $$(selector) { + const result = await this._elementChannel.querySelectorAll({ selector }); + return result.elements.map((h) => ElementHandle2.from(h)); + } + async $eval(selector, pageFunction, arg) { + const result = await this._elementChannel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async $$eval(selector, pageFunction, arg) { + const result = await this._elementChannel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async waitForElementState(state2, options2 = {}) { + return await this._elementChannel.waitForElementState({ state: state2, ...options2, timeout: this._frame._timeout(options2) }); + } + async waitForSelector(selector, options2 = {}) { + const result = await this._elementChannel.waitForSelector({ selector, ...options2, timeout: this._frame._timeout(options2) }); + return ElementHandle2.fromNullable(result.element); + } +} +function convertSelectOptionValues(values) { + if (values === null) + return {}; + if (!Array.isArray(values)) + values = [values]; + if (!values.length) + return {}; + for (let i = 0; i < values.length; i++) + assert(values[i] !== null, `options[${i}]: expected object, got null`); + if (values[0] instanceof ElementHandle2) + return { elements: values.map((v) => v._elementChannel) }; + if (isString(values[0])) + return { options: values.map((valueOrLabel) => ({ valueOrLabel })) }; + return { options: values }; +} +function filePayloadExceedsSizeLimit(payloads) { + return payloads.reduce((size, item) => size + (item.buffer ? item.buffer.byteLength : 0), 0) >= fileUploadSizeLimit; +} +async function resolvePathsAndDirectoryForInputFiles(platform, items) { + let localPaths; + let localDirectory; + for (const item of items) { + const stat2 = await platform.fs().promises.stat(item); + if (stat2.isDirectory()) { + if (localDirectory) + throw new Error("Multiple directories are not supported"); + localDirectory = platform.path().resolve(item); + } else { + localPaths ?? (localPaths = []); + localPaths.push(platform.path().resolve(item)); + } + } + if ((localPaths == null ? void 0 : localPaths.length) && localDirectory) + throw new Error("File paths must be all files or a single directory"); + return [localPaths, localDirectory]; +} +async function convertInputFiles(platform, files, context) { + const items = Array.isArray(files) ? files.slice() : [files]; + if (items.some((item) => typeof item === "string")) { + if (!items.every((item) => typeof item === "string")) + throw new Error("File paths cannot be mixed with buffers"); + const [localPaths, localDirectory] = await resolvePathsAndDirectoryForInputFiles(platform, items); + if (context._connection.isRemote()) { + const files2 = localDirectory ? (await platform.fs().promises.readdir(localDirectory, { withFileTypes: true, recursive: true })).filter((f) => f.isFile()).map((f) => platform.path().join(f.path, f.name)) : localPaths; + const { writableStreams, rootDir } = await context._wrapApiCall(async () => context._channel.createTempFiles({ + rootDirName: localDirectory ? platform.path().basename(localDirectory) : void 0, + items: await Promise.all(files2.map(async (file) => { + const lastModifiedMs = (await platform.fs().promises.stat(file)).mtimeMs; + return { + name: localDirectory ? platform.path().relative(localDirectory, file) : platform.path().basename(file), + lastModifiedMs + }; + })) + }), { internal: true }); + for (let i = 0; i < files2.length; i++) { + const writable2 = WritableStream$1.from(writableStreams[i]); + await platform.streamFile(files2[i], writable2.stream()); + } + return { + directoryStream: rootDir, + streams: localDirectory ? void 0 : writableStreams + }; + } + return { + localPaths, + localDirectory + }; + } + const payloads = items; + if (filePayloadExceedsSizeLimit(payloads)) + throw new Error("Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead."); + return { payloads }; +} +function determineScreenshotType(options2) { + if (options2.path) { + const mimeType = getMimeTypeForPath(options2.path); + if (mimeType === "image/png") + return "png"; + else if (mimeType === "image/jpeg") + return "jpeg"; + throw new Error(`path: unsupported mime type "${mimeType}"`); + } + return options2.type; +} +class FileChooser2 { + constructor(page, elementHandle, isMultiple) { + this._page = page; + this._elementHandle = elementHandle; + this._isMultiple = isMultiple; + } + element() { + return this._elementHandle; + } + isMultiple() { + return this._isMultiple; + } + page() { + return this._page; + } + async setFiles(files, options2) { + return await this._elementHandle.setInputFiles(files, options2); + } +} +class HarRouter { + static async create(localUtils, file, notFoundAction, options2) { + const { harId, error: error2 } = await localUtils.harOpen({ file }); + if (error2) + throw new Error(error2); + return new HarRouter(localUtils, harId, notFoundAction, options2); + } + constructor(localUtils, harId, notFoundAction, options2) { + this._localUtils = localUtils; + this._harId = harId; + this._options = options2; + this._notFoundAction = notFoundAction; + } + async _handle(route) { + const request2 = route.request(); + const response2 = await this._localUtils.harLookup({ + harId: this._harId, + url: request2.url(), + method: request2.method(), + headers: await request2.headersArray(), + postData: request2.postDataBuffer() || void 0, + isNavigationRequest: request2.isNavigationRequest() + }); + if (response2.action === "redirect") { + route._platform.log("api", `HAR: ${route.request().url()} redirected to ${response2.redirectURL}`); + await route._redirectNavigationRequest(response2.redirectURL); + return; + } + if (response2.action === "fulfill") { + if (response2.status === -1) + return; + await route.fulfill({ + status: response2.status, + headers: Object.fromEntries(response2.headers.map((h) => [h.name, h.value])), + body: response2.body + }); + return; + } + if (response2.action === "error") + route._platform.log("api", "HAR: " + response2.message); + if (this._notFoundAction === "abort") { + await route.abort(); + return; + } + await route.fallback(); + } + async addContextRoute(context) { + await context.route(this._options.urlMatch || "**/*", (route) => this._handle(route)); + } + async addPageRoute(page) { + await page.route(this._options.urlMatch || "**/*", (route) => this._handle(route)); + } + async [Symbol.asyncDispose]() { + await this.dispose(); + } + dispose() { + this._localUtils.harClose({ harId: this._harId }).catch(() => { + }); + } +} +class Keyboard2 { + constructor(page) { + this._page = page; + } + async down(key2) { + await this._page._channel.keyboardDown({ key: key2 }); + } + async up(key2) { + await this._page._channel.keyboardUp({ key: key2 }); + } + async insertText(text) { + await this._page._channel.keyboardInsertText({ text }); + } + async type(text, options2 = {}) { + await this._page._channel.keyboardType({ text, ...options2 }); + } + async press(key2, options2 = {}) { + await this._page._channel.keyboardPress({ key: key2, ...options2 }); + } +} +class Mouse2 { + constructor(page) { + this._page = page; + } + async move(x, y, options2 = {}) { + await this._page._channel.mouseMove({ x, y, ...options2 }); + } + async down(options2 = {}) { + await this._page._channel.mouseDown({ ...options2 }); + } + async up(options2 = {}) { + await this._page._channel.mouseUp(options2); + } + async click(x, y, options2 = {}) { + await this._page._channel.mouseClick({ x, y, ...options2 }); + } + async dblclick(x, y, options2 = {}) { + await this._page._wrapApiCall(async () => { + await this.click(x, y, { ...options2, clickCount: 2 }); + }, { title: "Double click" }); + } + async wheel(deltaX, deltaY) { + await this._page._channel.mouseWheel({ deltaX, deltaY }); + } +} +class Touchscreen2 { + constructor(page) { + this._page = page; + } + async tap(x, y) { + await this._page._channel.touchscreenTap({ x, y }); + } +} +class Video { + constructor(page, connection) { + this._artifact = null; + this._artifactReadyPromise = new ManualPromise(); + this._isRemote = false; + this._isRemote = connection.isRemote(); + this._artifact = page._closedOrCrashedScope.safeRace(this._artifactReadyPromise); + } + _artifactReady(artifact) { + this._artifactReadyPromise.resolve(artifact); + } + async path() { + if (this._isRemote) + throw new Error(`Path is not available when connecting remotely. Use saveAs() to save a local copy.`); + const artifact = await this._artifact; + if (!artifact) + throw new Error("Page did not produce any video frames"); + return artifact._initializer.absolutePath; + } + async saveAs(path2) { + const artifact = await this._artifact; + if (!artifact) + throw new Error("Page did not produce any video frames"); + return await artifact.saveAs(path2); + } + async delete() { + const artifact = await this._artifact; + if (artifact) + await artifact.delete(); + } +} +class Page extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._frames = /* @__PURE__ */ new Set(); + this._workers = /* @__PURE__ */ new Set(); + this._closed = false; + this._closedOrCrashedScope = new LongStandingScope(); + this._routes = []; + this._webSocketRoutes = []; + this._bindings = /* @__PURE__ */ new Map(); + this._video = null; + this._closeWasCalled = false; + this._harRouters = []; + this._locatorHandlers = /* @__PURE__ */ new Map(); + this._browserContext = parent; + this._timeoutSettings = new TimeoutSettings(this._platform, this._browserContext._timeoutSettings); + this.accessibility = new Accessibility2(this._channel); + this.keyboard = new Keyboard2(this); + this.mouse = new Mouse2(this); + this.request = this._browserContext.request; + this.touchscreen = new Touchscreen2(this); + this.clock = this._browserContext.clock; + this._mainFrame = Frame.from(initializer.mainFrame); + this._mainFrame._page = this; + this._frames.add(this._mainFrame); + this._viewportSize = initializer.viewportSize; + this._closed = initializer.isClosed; + this._opener = Page.fromNullable(initializer.opener); + this._channel.on("bindingCall", ({ binding: binding2 }) => this._onBinding(BindingCall.from(binding2))); + this._channel.on("close", () => this._onClose()); + this._channel.on("crash", () => this._onCrash()); + this._channel.on("download", ({ url: url2, suggestedFilename, artifact }) => { + const artifactObject = Artifact2.from(artifact); + this.emit(Events.Page.Download, new Download2(this, url2, suggestedFilename, artifactObject)); + }); + this._channel.on("fileChooser", ({ element, isMultiple }) => this.emit(Events.Page.FileChooser, new FileChooser2(this, ElementHandle2.from(element), isMultiple))); + this._channel.on("frameAttached", ({ frame }) => this._onFrameAttached(Frame.from(frame))); + this._channel.on("frameDetached", ({ frame }) => this._onFrameDetached(Frame.from(frame))); + this._channel.on("locatorHandlerTriggered", ({ uid }) => this._onLocatorHandlerTriggered(uid)); + this._channel.on("route", ({ route }) => this._onRoute(Route2.from(route))); + this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(WebSocketRoute.from(webSocketRoute))); + this._channel.on("video", ({ artifact }) => { + const artifactObject = Artifact2.from(artifact); + this._forceVideo()._artifactReady(artifactObject); + }); + this._channel.on("viewportSizeChanged", ({ viewportSize }) => this._viewportSize = viewportSize); + this._channel.on("webSocket", ({ webSocket }) => this.emit(Events.Page.WebSocket, WebSocket.from(webSocket))); + this._channel.on("worker", ({ worker }) => this._onWorker(Worker.from(worker))); + this.coverage = new Coverage(this._channel); + this.once(Events.Page.Close, () => this._closedOrCrashedScope.close(this._closeErrorWithReason())); + this.once(Events.Page.Crash, () => this._closedOrCrashedScope.close(new TargetClosedError2())); + this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([ + [Events.Page.Console, "console"], + [Events.Page.Dialog, "dialog"], + [Events.Page.Request, "request"], + [Events.Page.Response, "response"], + [Events.Page.RequestFinished, "requestFinished"], + [Events.Page.RequestFailed, "requestFailed"], + [Events.Page.FileChooser, "fileChooser"] + ])); + } + static from(page) { + return page._object; + } + static fromNullable(page) { + return page ? Page.from(page) : null; + } + _onFrameAttached(frame) { + frame._page = this; + this._frames.add(frame); + if (frame._parentFrame) + frame._parentFrame._childFrames.add(frame); + this.emit(Events.Page.FrameAttached, frame); + } + _onFrameDetached(frame) { + this._frames.delete(frame); + frame._detached = true; + if (frame._parentFrame) + frame._parentFrame._childFrames.delete(frame); + this.emit(Events.Page.FrameDetached, frame); + } + async _onRoute(route) { + route._context = this.context(); + const routeHandlers = this._routes.slice(); + for (const routeHandler of routeHandlers) { + if (this._closeWasCalled || this._browserContext._closingStatus !== "none") + return; + if (!routeHandler.matches(route.request().url())) + continue; + const index2 = this._routes.indexOf(routeHandler); + if (index2 === -1) + continue; + if (routeHandler.willExpire()) + this._routes.splice(index2, 1); + const handled = await routeHandler.handle(route); + if (!this._routes.length) + this._wrapApiCall(() => this._updateInterceptionPatterns(), { internal: true }).catch(() => { + }); + if (handled) + return; + } + await this._browserContext._onRoute(route); + } + async _onWebSocketRoute(webSocketRoute) { + const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url())); + if (routeHandler) + await routeHandler.handle(webSocketRoute); + else + await this._browserContext._onWebSocketRoute(webSocketRoute); + } + async _onBinding(bindingCall) { + const func = this._bindings.get(bindingCall._initializer.name); + if (func) { + await bindingCall.call(func); + return; + } + await this._browserContext._onBinding(bindingCall); + } + _onWorker(worker) { + this._workers.add(worker); + worker._page = this; + this.emit(Events.Page.Worker, worker); + } + _onClose() { + this._closed = true; + this._browserContext._pages.delete(this); + this._browserContext._backgroundPages.delete(this); + this._disposeHarRouters(); + this.emit(Events.Page.Close, this); + } + _onCrash() { + this.emit(Events.Page.Crash, this); + } + context() { + return this._browserContext; + } + async opener() { + if (!this._opener || this._opener.isClosed()) + return null; + return this._opener; + } + mainFrame() { + return this._mainFrame; + } + frame(frameSelector) { + const name = isString(frameSelector) ? frameSelector : frameSelector.name; + const url2 = isObject(frameSelector) ? frameSelector.url : void 0; + assert(name || url2, "Either name or url matcher should be specified"); + return this.frames().find((f) => { + if (name) + return f.name() === name; + return urlMatches(this._browserContext._options.baseURL, f.url(), url2); + }) || null; + } + frames() { + return [...this._frames]; + } + setDefaultNavigationTimeout(timeout) { + this._timeoutSettings.setDefaultNavigationTimeout(timeout); + } + setDefaultTimeout(timeout) { + this._timeoutSettings.setDefaultTimeout(timeout); + } + _forceVideo() { + if (!this._video) + this._video = new Video(this, this._connection); + return this._video; + } + video() { + if (!this._browserContext._options.recordVideo) + return null; + return this._forceVideo(); + } + async $(selector, options2) { + return await this._mainFrame.$(selector, options2); + } + async waitForSelector(selector, options2) { + return await this._mainFrame.waitForSelector(selector, options2); + } + async dispatchEvent(selector, type2, eventInit, options2) { + return await this._mainFrame.dispatchEvent(selector, type2, eventInit, options2); + } + async evaluateHandle(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + return await this._mainFrame.evaluateHandle(pageFunction, arg); + } + async $eval(selector, pageFunction, arg) { + assertMaxArguments(arguments.length, 3); + return await this._mainFrame.$eval(selector, pageFunction, arg); + } + async $$eval(selector, pageFunction, arg) { + assertMaxArguments(arguments.length, 3); + return await this._mainFrame.$$eval(selector, pageFunction, arg); + } + async $$(selector) { + return await this._mainFrame.$$(selector); + } + async addScriptTag(options2 = {}) { + return await this._mainFrame.addScriptTag(options2); + } + async addStyleTag(options2 = {}) { + return await this._mainFrame.addStyleTag(options2); + } + async exposeFunction(name, callback) { + await this._channel.exposeBinding({ name }); + const binding2 = (source2, ...args) => callback(...args); + this._bindings.set(name, binding2); + } + async exposeBinding(name, callback, options2 = {}) { + await this._channel.exposeBinding({ name, needsHandle: options2.handle }); + this._bindings.set(name, callback); + } + async setExtraHTTPHeaders(headers) { + validateHeaders(headers); + await this._channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) }); + } + url() { + return this._mainFrame.url(); + } + async content() { + return await this._mainFrame.content(); + } + async setContent(html, options2) { + return await this._mainFrame.setContent(html, options2); + } + async goto(url2, options2) { + return await this._mainFrame.goto(url2, options2); + } + async reload(options2 = {}) { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + return Response2.fromNullable((await this._channel.reload({ ...options2, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options2) })).response); + } + async addLocatorHandler(locator, handler, options2 = {}) { + if (locator._frame !== this._mainFrame) + throw new Error(`Locator must belong to the main frame of this page`); + if (options2.times === 0) + return; + const { uid } = await this._channel.registerLocatorHandler({ selector: locator._selector, noWaitAfter: options2.noWaitAfter }); + this._locatorHandlers.set(uid, { locator, handler, times: options2.times }); + } + async _onLocatorHandlerTriggered(uid) { + let remove = false; + try { + const handler = this._locatorHandlers.get(uid); + if (handler && handler.times !== 0) { + if (handler.times !== void 0) + handler.times--; + await handler.handler(handler.locator); + } + remove = (handler == null ? void 0 : handler.times) === 0; + } finally { + if (remove) + this._locatorHandlers.delete(uid); + this._wrapApiCall(() => this._channel.resolveLocatorHandlerNoReply({ uid, remove }), { internal: true }).catch(() => { + }); + } + } + async removeLocatorHandler(locator) { + for (const [uid, data2] of this._locatorHandlers) { + if (data2.locator._equals(locator)) { + this._locatorHandlers.delete(uid); + await this._channel.unregisterLocatorHandler({ uid }).catch(() => { + }); + } + } + } + async waitForLoadState(state2, options2) { + return await this._mainFrame.waitForLoadState(state2, options2); + } + async waitForNavigation(options2) { + return await this._mainFrame.waitForNavigation(options2); + } + async waitForURL(url2, options2) { + return await this._mainFrame.waitForURL(url2, options2); + } + async waitForRequest(urlOrPredicate, options2 = {}) { + const predicate = async (request2) => { + if (isString(urlOrPredicate) || isRegExp$4(urlOrPredicate)) + return urlMatches(this._browserContext._options.baseURL, request2.url(), urlOrPredicate); + return await urlOrPredicate(request2); + }; + const trimmedUrl = trimUrl(urlOrPredicate); + const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : void 0; + return await this._waitForEvent(Events.Page.Request, { predicate, timeout: options2.timeout }, logLine); + } + async waitForResponse(urlOrPredicate, options2 = {}) { + const predicate = async (response2) => { + if (isString(urlOrPredicate) || isRegExp$4(urlOrPredicate)) + return urlMatches(this._browserContext._options.baseURL, response2.url(), urlOrPredicate); + return await urlOrPredicate(response2); + }; + const trimmedUrl = trimUrl(urlOrPredicate); + const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : void 0; + return await this._waitForEvent(Events.Page.Response, { predicate, timeout: options2.timeout }, logLine); + } + async waitForEvent(event, optionsOrPredicate = {}) { + return await this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`); + } + _closeErrorWithReason() { + return new TargetClosedError2(this._closeReason || this._browserContext._effectiveCloseReason()); + } + async _waitForEvent(event, optionsOrPredicate, logLine) { + return await this._wrapApiCall(async () => { + const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate); + const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate; + const waiter = Waiter.createForEvent(this, event); + if (logLine) + waiter.log(logLine); + waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`); + if (event !== Events.Page.Crash) + waiter.rejectOnEvent(this, Events.Page.Crash, new Error("Page crashed")); + if (event !== Events.Page.Close) + waiter.rejectOnEvent(this, Events.Page.Close, () => this._closeErrorWithReason()); + const result = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result; + }); + } + async goBack(options2 = {}) { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + return Response2.fromNullable((await this._channel.goBack({ ...options2, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options2) })).response); + } + async goForward(options2 = {}) { + const waitUntil = verifyLoadState("waitUntil", options2.waitUntil === void 0 ? "load" : options2.waitUntil); + return Response2.fromNullable((await this._channel.goForward({ ...options2, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options2) })).response); + } + async requestGC() { + await this._channel.requestGC(); + } + async emulateMedia(options2 = {}) { + await this._channel.emulateMedia({ + media: options2.media === null ? "no-override" : options2.media, + colorScheme: options2.colorScheme === null ? "no-override" : options2.colorScheme, + reducedMotion: options2.reducedMotion === null ? "no-override" : options2.reducedMotion, + forcedColors: options2.forcedColors === null ? "no-override" : options2.forcedColors, + contrast: options2.contrast === null ? "no-override" : options2.contrast + }); + } + async setViewportSize(viewportSize) { + this._viewportSize = viewportSize; + await this._channel.setViewportSize({ viewportSize }); + } + viewportSize() { + return this._viewportSize || null; + } + async evaluate(pageFunction, arg) { + assertMaxArguments(arguments.length, 2); + return await this._mainFrame.evaluate(pageFunction, arg); + } + async addInitScript(script, arg) { + const source2 = await evaluationScript(this._platform, script, arg); + await this._channel.addInitScript({ source: source2 }); + } + async route(url2, handler, options2 = {}) { + this._routes.unshift(new RouteHandler(this._platform, this._browserContext._options.baseURL, url2, handler, options2.times)); + await this._updateInterceptionPatterns(); + } + async routeFromHAR(har, options2 = {}) { + const localUtils = this._connection.localUtils(); + if (!localUtils) + throw new Error("Route from har is not supported in thin clients"); + if (options2.update) { + await this._browserContext._recordIntoHAR(har, this, options2); + return; + } + const harRouter = await HarRouter.create(localUtils, har, options2.notFound || "abort", { urlMatch: options2.url }); + this._harRouters.push(harRouter); + await harRouter.addPageRoute(this); + } + async routeWebSocket(url2, handler) { + this._webSocketRoutes.unshift(new WebSocketRouteHandler(this._browserContext._options.baseURL, url2, handler)); + await this._updateWebSocketInterceptionPatterns(); + } + _disposeHarRouters() { + this._harRouters.forEach((router) => router.dispose()); + this._harRouters = []; + } + async unrouteAll(options2) { + await this._unrouteInternal(this._routes, [], options2 == null ? void 0 : options2.behavior); + this._disposeHarRouters(); + } + async unroute(url2, handler) { + const removed = []; + const remaining = []; + for (const route of this._routes) { + if (urlMatchesEqual(route.url, url2) && (!handler || route.handler === handler)) + removed.push(route); + else + remaining.push(route); + } + await this._unrouteInternal(removed, remaining, "default"); + } + async _unrouteInternal(removed, remaining, behavior) { + this._routes = remaining; + await this._updateInterceptionPatterns(); + if (!behavior || behavior === "default") + return; + const promises2 = removed.map((routeHandler) => routeHandler.stop(behavior)); + await Promise.all(promises2); + } + async _updateInterceptionPatterns() { + const patterns = RouteHandler.prepareInterceptionPatterns(this._routes); + await this._channel.setNetworkInterceptionPatterns({ patterns }); + } + async _updateWebSocketInterceptionPatterns() { + const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes); + await this._channel.setWebSocketInterceptionPatterns({ patterns }); + } + async screenshot(options2 = {}) { + const mask = options2.mask; + const copy = { ...options2, mask: void 0, timeout: this._timeoutSettings.timeout(options2) }; + if (!copy.type) + copy.type = determineScreenshotType(options2); + if (mask) { + copy.mask = mask.map((locator) => ({ + frame: locator._frame._channel, + selector: locator._selector + })); + } + const result = await this._channel.screenshot(copy); + if (options2.path) { + await mkdirIfNeeded(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, result.binary); + } + return result.binary; + } + async _expectScreenshot(options2) { + const mask = (options2 == null ? void 0 : options2.mask) ? options2 == null ? void 0 : options2.mask.map((locator2) => ({ + frame: locator2._frame._channel, + selector: locator2._selector + })) : void 0; + const locator = options2.locator ? { + frame: options2.locator._frame._channel, + selector: options2.locator._selector + } : void 0; + return await this._channel.expectScreenshot({ + ...options2, + isNot: !!options2.isNot, + locator, + mask + }); + } + async title() { + return await this._mainFrame.title(); + } + async bringToFront() { + await this._channel.bringToFront(); + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async close(options2 = {}) { + this._closeReason = options2.reason; + this._closeWasCalled = true; + try { + if (this._ownedContext) + await this._ownedContext.close(); + else + await this._channel.close(options2); + } catch (e) { + if (isTargetClosedError(e) && !options2.runBeforeUnload) + return; + throw e; + } + } + isClosed() { + return this._closed; + } + async click(selector, options2) { + return await this._mainFrame.click(selector, options2); + } + async dragAndDrop(source2, target, options2) { + return await this._mainFrame.dragAndDrop(source2, target, options2); + } + async dblclick(selector, options2) { + await this._mainFrame.dblclick(selector, options2); + } + async tap(selector, options2) { + return await this._mainFrame.tap(selector, options2); + } + async fill(selector, value, options2) { + return await this._mainFrame.fill(selector, value, options2); + } + locator(selector, options2) { + return this.mainFrame().locator(selector, options2); + } + getByTestId(testId) { + return this.mainFrame().getByTestId(testId); + } + getByAltText(text, options2) { + return this.mainFrame().getByAltText(text, options2); + } + getByLabel(text, options2) { + return this.mainFrame().getByLabel(text, options2); + } + getByPlaceholder(text, options2) { + return this.mainFrame().getByPlaceholder(text, options2); + } + getByText(text, options2) { + return this.mainFrame().getByText(text, options2); + } + getByTitle(text, options2) { + return this.mainFrame().getByTitle(text, options2); + } + getByRole(role, options2 = {}) { + return this.mainFrame().getByRole(role, options2); + } + frameLocator(selector) { + return this.mainFrame().frameLocator(selector); + } + async focus(selector, options2) { + return await this._mainFrame.focus(selector, options2); + } + async textContent(selector, options2) { + return await this._mainFrame.textContent(selector, options2); + } + async innerText(selector, options2) { + return await this._mainFrame.innerText(selector, options2); + } + async innerHTML(selector, options2) { + return await this._mainFrame.innerHTML(selector, options2); + } + async getAttribute(selector, name, options2) { + return await this._mainFrame.getAttribute(selector, name, options2); + } + async inputValue(selector, options2) { + return await this._mainFrame.inputValue(selector, options2); + } + async isChecked(selector, options2) { + return await this._mainFrame.isChecked(selector, options2); + } + async isDisabled(selector, options2) { + return await this._mainFrame.isDisabled(selector, options2); + } + async isEditable(selector, options2) { + return await this._mainFrame.isEditable(selector, options2); + } + async isEnabled(selector, options2) { + return await this._mainFrame.isEnabled(selector, options2); + } + async isHidden(selector, options2) { + return await this._mainFrame.isHidden(selector, options2); + } + async isVisible(selector, options2) { + return await this._mainFrame.isVisible(selector, options2); + } + async hover(selector, options2) { + return await this._mainFrame.hover(selector, options2); + } + async selectOption(selector, values, options2) { + return await this._mainFrame.selectOption(selector, values, options2); + } + async setInputFiles(selector, files, options2) { + return await this._mainFrame.setInputFiles(selector, files, options2); + } + async type(selector, text, options2) { + return await this._mainFrame.type(selector, text, options2); + } + async press(selector, key2, options2) { + return await this._mainFrame.press(selector, key2, options2); + } + async check(selector, options2) { + return await this._mainFrame.check(selector, options2); + } + async uncheck(selector, options2) { + return await this._mainFrame.uncheck(selector, options2); + } + async setChecked(selector, checked, options2) { + return await this._mainFrame.setChecked(selector, checked, options2); + } + async waitForTimeout(timeout) { + return await this._mainFrame.waitForTimeout(timeout); + } + async waitForFunction(pageFunction, arg, options2) { + return await this._mainFrame.waitForFunction(pageFunction, arg, options2); + } + workers() { + return [...this._workers]; + } + async pause(_options) { + var _a2; + if (this._platform.isJSDebuggerAttached()) + return; + const defaultNavigationTimeout = this._browserContext._timeoutSettings.defaultNavigationTimeout(); + const defaultTimeout = this._browserContext._timeoutSettings.defaultTimeout(); + this._browserContext.setDefaultNavigationTimeout(0); + this._browserContext.setDefaultTimeout(0); + (_a2 = this._instrumentation) == null ? void 0 : _a2.onWillPause({ keepTestTimeout: !!(_options == null ? void 0 : _options.__testHookKeepTestTimeout) }); + await this._closedOrCrashedScope.safeRace(this.context()._channel.pause()); + this._browserContext.setDefaultNavigationTimeout(defaultNavigationTimeout); + this._browserContext.setDefaultTimeout(defaultTimeout); + } + async pdf(options2 = {}) { + const transportOptions = { ...options2 }; + if (transportOptions.margin) + transportOptions.margin = { ...transportOptions.margin }; + if (typeof options2.width === "number") + transportOptions.width = options2.width + "px"; + if (typeof options2.height === "number") + transportOptions.height = options2.height + "px"; + for (const margin of ["top", "right", "bottom", "left"]) { + const index2 = margin; + if (options2.margin && typeof options2.margin[index2] === "number") + transportOptions.margin[index2] = transportOptions.margin[index2] + "px"; + } + const result = await this._channel.pdf(transportOptions); + if (options2.path) { + const platform = this._platform; + await platform.fs().promises.mkdir(platform.path().dirname(options2.path), { recursive: true }); + await platform.fs().promises.writeFile(options2.path, result.pdf); + } + return result.pdf; + } + async _snapshotForAI() { + const result = await this._channel.snapshotForAI(); + return result.snapshot; + } +} +class BindingCall extends ChannelOwner { + static from(channel) { + return channel._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + } + async call(func) { + try { + const frame = Frame.from(this._initializer.frame); + const source2 = { + context: frame._page.context(), + page: frame._page, + frame + }; + let result; + if (this._initializer.handle) + result = await func(source2, JSHandle2.from(this._initializer.handle)); + else + result = await func(source2, ...this._initializer.args.map(parseResult)); + this._channel.resolve({ result: serializeArgument(result) }).catch(() => { + }); + } catch (e) { + this._channel.reject({ error: serializeError(e) }).catch(() => { + }); + } + } +} +function trimUrl(param) { + if (isRegExp$4(param)) + return `/${trimStringWithEllipsis(param.source, 50)}/${param.flags}`; + if (isString(param)) + return `"${trimStringWithEllipsis(param, 50)}"`; +} +class ConsoleMessage2 { + constructor(platform, event) { + this._page = "page" in event && event.page ? Page.from(event.page) : null; + this._event = event; + if (platform.inspectCustom) + this[platform.inspectCustom] = () => this._inspect(); + } + page() { + return this._page; + } + type() { + return this._event.type; + } + text() { + return this._event.text; + } + args() { + return this._event.args.map(JSHandle2.from); + } + location() { + return this._event.location; + } + _inspect() { + return this.text(); + } +} +class Dialog2 extends ChannelOwner { + static from(dialog) { + return dialog._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._page = Page.fromNullable(initializer.page); + } + page() { + return this._page; + } + type() { + return this._initializer.type; + } + message() { + return this._initializer.message; + } + defaultValue() { + return this._initializer.defaultValue; + } + async accept(promptText) { + await this._channel.accept({ promptText }); + } + async dismiss() { + await this._channel.dismiss(); + } +} +class WebError { + constructor(page, error2) { + this._page = page; + this._error = error2; + } + page() { + return this._page; + } + error() { + return this._error; + } +} +class BrowserContext extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._pages = /* @__PURE__ */ new Set(); + this._routes = []; + this._webSocketRoutes = []; + this._browser = null; + this._bindings = /* @__PURE__ */ new Map(); + this._backgroundPages = /* @__PURE__ */ new Set(); + this._serviceWorkers = /* @__PURE__ */ new Set(); + this._harRecorders = /* @__PURE__ */ new Map(); + this._closingStatus = "none"; + this._harRouters = []; + this._options = initializer.options; + this._timeoutSettings = new TimeoutSettings(this._platform); + this.tracing = Tracing2.from(initializer.tracing); + this.request = APIRequestContext.from(initializer.requestContext); + this.request._timeoutSettings = this._timeoutSettings; + this.clock = new Clock2(this); + this._channel.on("bindingCall", ({ binding: binding2 }) => this._onBinding(BindingCall.from(binding2))); + this._channel.on("close", () => this._onClose()); + this._channel.on("page", ({ page }) => this._onPage(Page.from(page))); + this._channel.on("route", ({ route }) => this._onRoute(Route2.from(route))); + this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(WebSocketRoute.from(webSocketRoute))); + this._channel.on("backgroundPage", ({ page }) => { + const backgroundPage = Page.from(page); + this._backgroundPages.add(backgroundPage); + this.emit(Events.BrowserContext.BackgroundPage, backgroundPage); + }); + this._channel.on("serviceWorker", ({ worker }) => { + const serviceWorker = Worker.from(worker); + serviceWorker._context = this; + this._serviceWorkers.add(serviceWorker); + this.emit(Events.BrowserContext.ServiceWorker, serviceWorker); + }); + this._channel.on("console", (event) => { + const consoleMessage = new ConsoleMessage2(this._platform, event); + this.emit(Events.BrowserContext.Console, consoleMessage); + const page = consoleMessage.page(); + if (page) + page.emit(Events.Page.Console, consoleMessage); + }); + this._channel.on("pageError", ({ error: error2, page }) => { + const pageObject = Page.from(page); + const parsedError = parseError(error2); + this.emit(Events.BrowserContext.WebError, new WebError(pageObject, parsedError)); + if (pageObject) + pageObject.emit(Events.Page.PageError, parsedError); + }); + this._channel.on("dialog", ({ dialog }) => { + const dialogObject = Dialog2.from(dialog); + let hasListeners = this.emit(Events.BrowserContext.Dialog, dialogObject); + const page = dialogObject.page(); + if (page) + hasListeners = page.emit(Events.Page.Dialog, dialogObject) || hasListeners; + if (!hasListeners) { + if (dialogObject.type() === "beforeunload") + dialog.accept({}).catch(() => { + }); + else + dialog.dismiss().catch(() => { + }); + } + }); + this._channel.on("request", ({ request: request2, page }) => this._onRequest(Request2.from(request2), Page.fromNullable(page))); + this._channel.on("requestFailed", ({ request: request2, failureText, responseEndTiming, page }) => this._onRequestFailed(Request2.from(request2), responseEndTiming, failureText, Page.fromNullable(page))); + this._channel.on("requestFinished", (params) => this._onRequestFinished(params)); + this._channel.on("response", ({ response: response2, page }) => this._onResponse(Response2.from(response2), Page.fromNullable(page))); + this._closedPromise = new Promise((f) => this.once(Events.BrowserContext.Close, f)); + this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([ + [Events.BrowserContext.Console, "console"], + [Events.BrowserContext.Dialog, "dialog"], + [Events.BrowserContext.Request, "request"], + [Events.BrowserContext.Response, "response"], + [Events.BrowserContext.RequestFinished, "requestFinished"], + [Events.BrowserContext.RequestFailed, "requestFailed"] + ])); + } + static from(context) { + return context._object; + } + static fromNullable(context) { + return context ? BrowserContext.from(context) : null; + } + async _initializeHarFromOptions(recordHar) { + if (!recordHar) + return; + const defaultContent = recordHar.path.endsWith(".zip") ? "attach" : "embed"; + await this._recordIntoHAR(recordHar.path, null, { + url: recordHar.urlFilter, + updateContent: recordHar.content ?? (recordHar.omitContent ? "omit" : defaultContent), + updateMode: recordHar.mode ?? "full" + }); + } + _onPage(page) { + this._pages.add(page); + this.emit(Events.BrowserContext.Page, page); + if (page._opener && !page._opener.isClosed()) + page._opener.emit(Events.Page.Popup, page); + } + _onRequest(request2, page) { + this.emit(Events.BrowserContext.Request, request2); + if (page) + page.emit(Events.Page.Request, request2); + } + _onResponse(response2, page) { + this.emit(Events.BrowserContext.Response, response2); + if (page) + page.emit(Events.Page.Response, response2); + } + _onRequestFailed(request2, responseEndTiming, failureText, page) { + request2._failureText = failureText || null; + request2._setResponseEndTiming(responseEndTiming); + this.emit(Events.BrowserContext.RequestFailed, request2); + if (page) + page.emit(Events.Page.RequestFailed, request2); + } + _onRequestFinished(params) { + const { responseEndTiming } = params; + const request2 = Request2.from(params.request); + const response2 = Response2.fromNullable(params.response); + const page = Page.fromNullable(params.page); + request2._setResponseEndTiming(responseEndTiming); + this.emit(Events.BrowserContext.RequestFinished, request2); + if (page) + page.emit(Events.Page.RequestFinished, request2); + if (response2) + response2._finishedPromise.resolve(null); + } + async _onRoute(route) { + route._context = this; + const page = route.request()._safePage(); + const routeHandlers = this._routes.slice(); + for (const routeHandler of routeHandlers) { + if ((page == null ? void 0 : page._closeWasCalled) || this._closingStatus !== "none") + return; + if (!routeHandler.matches(route.request().url())) + continue; + const index2 = this._routes.indexOf(routeHandler); + if (index2 === -1) + continue; + if (routeHandler.willExpire()) + this._routes.splice(index2, 1); + const handled = await routeHandler.handle(route); + if (!this._routes.length) + this._updateInterceptionPatterns().catch(() => { + }); + if (handled) + return; + } + await route._innerContinue( + true + /* isFallback */ + ).catch(() => { + }); + } + async _onWebSocketRoute(webSocketRoute) { + const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url())); + if (routeHandler) + await routeHandler.handle(webSocketRoute); + else + webSocketRoute.connectToServer(); + } + async _onBinding(bindingCall) { + const func = this._bindings.get(bindingCall._initializer.name); + if (!func) + return; + await bindingCall.call(func); + } + setDefaultNavigationTimeout(timeout) { + this._timeoutSettings.setDefaultNavigationTimeout(timeout); + } + setDefaultTimeout(timeout) { + this._timeoutSettings.setDefaultTimeout(timeout); + } + browser() { + return this._browser; + } + pages() { + return [...this._pages]; + } + async newPage() { + if (this._ownerPage) + throw new Error("Please use browser.newContext()"); + return Page.from((await this._channel.newPage()).page); + } + async cookies(urls) { + if (!urls) + urls = []; + if (urls && typeof urls === "string") + urls = [urls]; + return (await this._channel.cookies({ urls })).cookies; + } + async addCookies(cookies) { + await this._channel.addCookies({ cookies }); + } + async clearCookies(options2 = {}) { + await this._channel.clearCookies({ + name: isString(options2.name) ? options2.name : void 0, + nameRegexSource: isRegExp$4(options2.name) ? options2.name.source : void 0, + nameRegexFlags: isRegExp$4(options2.name) ? options2.name.flags : void 0, + domain: isString(options2.domain) ? options2.domain : void 0, + domainRegexSource: isRegExp$4(options2.domain) ? options2.domain.source : void 0, + domainRegexFlags: isRegExp$4(options2.domain) ? options2.domain.flags : void 0, + path: isString(options2.path) ? options2.path : void 0, + pathRegexSource: isRegExp$4(options2.path) ? options2.path.source : void 0, + pathRegexFlags: isRegExp$4(options2.path) ? options2.path.flags : void 0 + }); + } + async grantPermissions(permissions, options2) { + await this._channel.grantPermissions({ permissions, ...options2 }); + } + async clearPermissions() { + await this._channel.clearPermissions(); + } + async setGeolocation(geolocation) { + await this._channel.setGeolocation({ geolocation: geolocation || void 0 }); + } + async setExtraHTTPHeaders(headers) { + validateHeaders(headers); + await this._channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) }); + } + async setOffline(offline) { + await this._channel.setOffline({ offline }); + } + async setHTTPCredentials(httpCredentials) { + await this._channel.setHTTPCredentials({ httpCredentials: httpCredentials || void 0 }); + } + async addInitScript(script, arg) { + const source2 = await evaluationScript(this._platform, script, arg); + await this._channel.addInitScript({ source: source2 }); + } + async exposeBinding(name, callback, options2 = {}) { + await this._channel.exposeBinding({ name, needsHandle: options2.handle }); + this._bindings.set(name, callback); + } + async exposeFunction(name, callback) { + await this._channel.exposeBinding({ name }); + const binding2 = (source2, ...args) => callback(...args); + this._bindings.set(name, binding2); + } + async route(url2, handler, options2 = {}) { + this._routes.unshift(new RouteHandler(this._platform, this._options.baseURL, url2, handler, options2.times)); + await this._updateInterceptionPatterns(); + } + async routeWebSocket(url2, handler) { + this._webSocketRoutes.unshift(new WebSocketRouteHandler(this._options.baseURL, url2, handler)); + await this._updateWebSocketInterceptionPatterns(); + } + async _recordIntoHAR(har, page, options2 = {}) { + const { harId } = await this._channel.harStart({ + page: page == null ? void 0 : page._channel, + options: { + zip: har.endsWith(".zip"), + content: options2.updateContent ?? "attach", + urlGlob: isString(options2.url) ? options2.url : void 0, + urlRegexSource: isRegExp$4(options2.url) ? options2.url.source : void 0, + urlRegexFlags: isRegExp$4(options2.url) ? options2.url.flags : void 0, + mode: options2.updateMode ?? "minimal" + } + }); + this._harRecorders.set(harId, { path: har, content: options2.updateContent ?? "attach" }); + } + async routeFromHAR(har, options2 = {}) { + const localUtils = this._connection.localUtils(); + if (!localUtils) + throw new Error("Route from har is not supported in thin clients"); + if (options2.update) { + await this._recordIntoHAR(har, null, options2); + return; + } + const harRouter = await HarRouter.create(localUtils, har, options2.notFound || "abort", { urlMatch: options2.url }); + this._harRouters.push(harRouter); + await harRouter.addContextRoute(this); + } + _disposeHarRouters() { + this._harRouters.forEach((router) => router.dispose()); + this._harRouters = []; + } + async unrouteAll(options2) { + await this._unrouteInternal(this._routes, [], options2 == null ? void 0 : options2.behavior); + this._disposeHarRouters(); + } + async unroute(url2, handler) { + const removed = []; + const remaining = []; + for (const route of this._routes) { + if (urlMatchesEqual(route.url, url2) && (!handler || route.handler === handler)) + removed.push(route); + else + remaining.push(route); + } + await this._unrouteInternal(removed, remaining, "default"); + } + async _unrouteInternal(removed, remaining, behavior) { + this._routes = remaining; + await this._updateInterceptionPatterns(); + if (!behavior || behavior === "default") + return; + const promises2 = removed.map((routeHandler) => routeHandler.stop(behavior)); + await Promise.all(promises2); + } + async _updateInterceptionPatterns() { + const patterns = RouteHandler.prepareInterceptionPatterns(this._routes); + await this._channel.setNetworkInterceptionPatterns({ patterns }); + } + async _updateWebSocketInterceptionPatterns() { + const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes); + await this._channel.setWebSocketInterceptionPatterns({ patterns }); + } + _effectiveCloseReason() { + var _a2; + return this._closeReason || ((_a2 = this._browser) == null ? void 0 : _a2._closeReason); + } + async waitForEvent(event, optionsOrPredicate = {}) { + return await this._wrapApiCall(async () => { + const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate); + const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate; + const waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`); + if (event !== Events.BrowserContext.Close) + waiter.rejectOnEvent(this, Events.BrowserContext.Close, () => new TargetClosedError2(this._effectiveCloseReason())); + const result = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result; + }); + } + async storageState(options2 = {}) { + const state2 = await this._channel.storageState({ indexedDB: options2.indexedDB }); + if (options2.path) { + await mkdirIfNeeded(this._platform, options2.path); + await this._platform.fs().promises.writeFile(options2.path, JSON.stringify(state2, void 0, 2), "utf8"); + } + return state2; + } + backgroundPages() { + return [...this._backgroundPages]; + } + serviceWorkers() { + return [...this._serviceWorkers]; + } + async newCDPSession(page) { + if (!(page instanceof Page) && !(page instanceof Frame)) + throw new Error("page: expected Page or Frame"); + const result = await this._channel.newCDPSession(page instanceof Page ? { page: page._channel } : { frame: page._channel }); + return CDPSession.from(result.session); + } + _onClose() { + var _a2, _b2, _c2; + this._closingStatus = "closed"; + (_a2 = this._browser) == null ? void 0 : _a2._contexts.delete(this); + (_b2 = this._browser) == null ? void 0 : _b2._browserType._contexts.delete(this); + (_c2 = this._browser) == null ? void 0 : _c2._browserType._playwright.selectors._contextsForSelectors.delete(this); + this._disposeHarRouters(); + this.tracing._resetStackCounter(); + this.emit(Events.BrowserContext.Close, this); + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async close(options2 = {}) { + if (this._closingStatus !== "none") + return; + this._closeReason = options2.reason; + this._closingStatus = "closing"; + await this.request.dispose(options2); + await this._wrapApiCall(async () => { + await this._instrumentation.runBeforeCloseBrowserContext(this); + for (const [harId, harParams] of this._harRecorders) { + const har = await this._channel.harExport({ harId }); + const artifact = Artifact2.from(har.artifact); + const isCompressed = harParams.content === "attach" || harParams.path.endsWith(".zip"); + const needCompressed = harParams.path.endsWith(".zip"); + if (isCompressed && !needCompressed) { + const localUtils = this._connection.localUtils(); + if (!localUtils) + throw new Error("Uncompressed har is not supported in thin clients"); + await artifact.saveAs(harParams.path + ".tmp"); + await localUtils.harUnzip({ zipFile: harParams.path + ".tmp", harFile: harParams.path }); + } else { + await artifact.saveAs(harParams.path); + } + await artifact.delete(); + } + }, { internal: true }); + await this._channel.close(options2); + await this._closedPromise; + } + async _enableRecorder(params) { + await this._channel.enableRecorder(params); + } +} +async function prepareStorageState(platform, options2) { + if (typeof options2.storageState !== "string") + return options2.storageState; + try { + return JSON.parse(await platform.fs().promises.readFile(options2.storageState, "utf8")); + } catch (e) { + rewriteErrorMessage(e, `Error reading storage state from ${options2.storageState}: +` + e.message); + throw e; + } +} +async function prepareBrowserContextParams(platform, options2) { + if (options2.videoSize && !options2.videosPath) + throw new Error(`"videoSize" option requires "videosPath" to be specified`); + if (options2.extraHTTPHeaders) + validateHeaders(options2.extraHTTPHeaders); + const contextParams = { + ...options2, + viewport: options2.viewport === null ? void 0 : options2.viewport, + noDefaultViewport: options2.viewport === null, + extraHTTPHeaders: options2.extraHTTPHeaders ? headersObjectToArray(options2.extraHTTPHeaders) : void 0, + storageState: await prepareStorageState(platform, options2), + serviceWorkers: options2.serviceWorkers, + colorScheme: options2.colorScheme === null ? "no-override" : options2.colorScheme, + reducedMotion: options2.reducedMotion === null ? "no-override" : options2.reducedMotion, + forcedColors: options2.forcedColors === null ? "no-override" : options2.forcedColors, + contrast: options2.contrast === null ? "no-override" : options2.contrast, + acceptDownloads: toAcceptDownloadsProtocol(options2.acceptDownloads), + clientCertificates: await toClientCertificatesProtocol(platform, options2.clientCertificates) + }; + if (!contextParams.recordVideo && options2.videosPath) { + contextParams.recordVideo = { + dir: options2.videosPath, + size: options2.videoSize + }; + } + if (contextParams.recordVideo && contextParams.recordVideo.dir) + contextParams.recordVideo.dir = platform.path().resolve(contextParams.recordVideo.dir); + return contextParams; +} +function toAcceptDownloadsProtocol(acceptDownloads) { + if (acceptDownloads === void 0) + return void 0; + if (acceptDownloads) + return "accept"; + return "deny"; +} +async function toClientCertificatesProtocol(platform, certs) { + if (!certs) + return void 0; + const bufferizeContent = async (value, path2) => { + if (value) + return value; + if (path2) + return await platform.fs().promises.readFile(path2); + }; + return await Promise.all(certs.map(async (cert) => ({ + origin: cert.origin, + cert: await bufferizeContent(cert.cert, cert.certPath), + key: await bufferizeContent(cert.key, cert.keyPath), + pfx: await bufferizeContent(cert.pfx, cert.pfxPath), + passphrase: cert.passphrase + }))); +} +async function connectOverWebSocket(parentConnection, params) { + const localUtils = parentConnection.localUtils(); + const transport = localUtils ? new JsonPipeTransport(localUtils) : new WebSocketTransport2(); + const connectHeaders = await transport.connect(params); + const connection = new Connection(parentConnection._platform, localUtils, parentConnection._instrumentation, connectHeaders); + connection.markAsRemote(); + connection.on("close", () => transport.close()); + let closeError; + const onTransportClosed = (reason) => { + connection.close(reason || closeError); + }; + transport.onClose((reason) => onTransportClosed(reason)); + connection.onmessage = (message) => transport.send(message).catch(() => onTransportClosed()); + transport.onMessage((message) => { + try { + connection.dispatch(message); + } catch (e) { + closeError = String(e); + transport.close().catch(() => { + }); + } + }); + return connection; +} +class JsonPipeTransport { + constructor(owner) { + this._owner = owner; + } + async connect(params) { + const { pipe, headers: connectHeaders } = await this._owner._channel.connect(params); + this._pipe = pipe; + return connectHeaders; + } + async send(message) { + await this._pipe.send({ message }); + } + onMessage(callback) { + this._pipe.on("message", ({ message }) => callback(message)); + } + onClose(callback) { + this._pipe.on("closed", ({ reason }) => callback(reason)); + } + async close() { + await this._pipe.close().catch(() => { + }); + } +} +class WebSocketTransport2 { + async connect(params) { + this._ws = new window.WebSocket(params.wsEndpoint); + return []; + } + async send(message) { + this._ws.send(JSON.stringify(message)); + } + onMessage(callback) { + this._ws.addEventListener("message", (event) => callback(JSON.parse(event.data))); + } + onClose(callback) { + this._ws.addEventListener("close", () => callback()); + } + async close() { + this._ws.close(); + } +} +class Android2 extends ChannelOwner { + static from(android) { + return android._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._timeoutSettings = new TimeoutSettings(this._platform); + } + setDefaultTimeout(timeout) { + this._timeoutSettings.setDefaultTimeout(timeout); + } + async devices(options2 = {}) { + const { devices } = await this._channel.devices(options2); + return devices.map((d) => AndroidDevice.from(d)); + } + async launchServer(options2 = {}) { + if (!this._serverLauncher) + throw new Error("Launching server is not supported"); + return await this._serverLauncher.launchServer(options2); + } + async connect(wsEndpoint, options2 = {}) { + return await this._wrapApiCall(async () => { + const deadline = options2.timeout ? monotonicTime() + options2.timeout : 0; + const headers = { "x-playwright-browser": "android", ...options2.headers }; + const connectParams = { wsEndpoint, headers, slowMo: options2.slowMo, timeout: options2.timeout || 0 }; + const connection = await connectOverWebSocket(this._connection, connectParams); + let device; + connection.on("close", () => { + device == null ? void 0 : device._didClose(); + }); + const result = await raceAgainstDeadline(async () => { + const playwright2 = await connection.initializePlaywright(); + if (!playwright2._initializer.preConnectedAndroidDevice) { + connection.close(); + throw new Error("Malformed endpoint. Did you use Android.launchServer method?"); + } + device = AndroidDevice.from(playwright2._initializer.preConnectedAndroidDevice); + device._shouldCloseConnectionOnClose = true; + device.on(Events.AndroidDevice.Close, () => connection.close()); + return device; + }, deadline); + if (!result.timedOut) { + return result.result; + } else { + connection.close(); + throw new Error(`Timeout ${options2.timeout}ms exceeded`); + } + }); + } +} +class AndroidDevice extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._webViews = /* @__PURE__ */ new Map(); + this._shouldCloseConnectionOnClose = false; + this._android = parent; + this.input = new AndroidInput(this); + this._timeoutSettings = new TimeoutSettings(this._platform, parent._timeoutSettings); + this._channel.on("webViewAdded", ({ webView }) => this._onWebViewAdded(webView)); + this._channel.on("webViewRemoved", ({ socketName }) => this._onWebViewRemoved(socketName)); + this._channel.on("close", () => this._didClose()); + } + static from(androidDevice) { + return androidDevice._object; + } + _onWebViewAdded(webView) { + const view = new AndroidWebView(this, webView); + this._webViews.set(webView.socketName, view); + this.emit(Events.AndroidDevice.WebView, view); + } + _onWebViewRemoved(socketName) { + const view = this._webViews.get(socketName); + this._webViews.delete(socketName); + if (view) + view.emit(Events.AndroidWebView.Close); + } + setDefaultTimeout(timeout) { + this._timeoutSettings.setDefaultTimeout(timeout); + } + serial() { + return this._initializer.serial; + } + model() { + return this._initializer.model; + } + webViews() { + return [...this._webViews.values()]; + } + async webView(selector, options2) { + const predicate = (v) => { + if (selector.pkg) + return v.pkg() === selector.pkg; + if (selector.socketName) + return v._socketName() === selector.socketName; + return false; + }; + const webView = [...this._webViews.values()].find(predicate); + if (webView) + return webView; + return await this.waitForEvent("webview", { ...options2, predicate }); + } + async wait(selector, options2 = {}) { + await this._channel.wait({ androidSelector: toSelectorChannel(selector), ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async fill(selector, text, options2 = {}) { + await this._channel.fill({ androidSelector: toSelectorChannel(selector), text, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async press(selector, key2, options2 = {}) { + await this.tap(selector, options2); + await this.input.press(key2); + } + async tap(selector, options2 = {}) { + await this._channel.tap({ androidSelector: toSelectorChannel(selector), ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async drag(selector, dest, options2 = {}) { + await this._channel.drag({ androidSelector: toSelectorChannel(selector), dest, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async fling(selector, direction, options2 = {}) { + await this._channel.fling({ androidSelector: toSelectorChannel(selector), direction, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async longTap(selector, options2 = {}) { + await this._channel.longTap({ androidSelector: toSelectorChannel(selector), ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async pinchClose(selector, percent, options2 = {}) { + await this._channel.pinchClose({ androidSelector: toSelectorChannel(selector), percent, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async pinchOpen(selector, percent, options2 = {}) { + await this._channel.pinchOpen({ androidSelector: toSelectorChannel(selector), percent, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async scroll(selector, direction, percent, options2 = {}) { + await this._channel.scroll({ androidSelector: toSelectorChannel(selector), direction, percent, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async swipe(selector, direction, percent, options2 = {}) { + await this._channel.swipe({ androidSelector: toSelectorChannel(selector), direction, percent, ...options2, timeout: this._timeoutSettings.timeout(options2) }); + } + async info(selector) { + return (await this._channel.info({ androidSelector: toSelectorChannel(selector) })).info; + } + async screenshot(options2 = {}) { + const { binary: binary2 } = await this._channel.screenshot(); + if (options2.path) + await this._platform.fs().promises.writeFile(options2.path, binary2); + return binary2; + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async close() { + try { + if (this._shouldCloseConnectionOnClose) + this._connection.close(); + else + await this._channel.close(); + } catch (e) { + if (isTargetClosedError(e)) + return; + throw e; + } + } + _didClose() { + this.emit(Events.AndroidDevice.Close, this); + } + async shell(command2) { + const { result } = await this._channel.shell({ command: command2 }); + return result; + } + async open(command2) { + return AndroidSocket.from((await this._channel.open({ command: command2 })).socket); + } + async installApk(file, options2) { + await this._channel.installApk({ file: await loadFile(this._platform, file), args: options2 && options2.args }); + } + async push(file, path2, options2) { + await this._channel.push({ file: await loadFile(this._platform, file), path: path2, mode: options2 ? options2.mode : void 0 }); + } + async launchBrowser(options2 = {}) { + const contextOptions = await prepareBrowserContextParams(this._platform, options2); + const result = await this._channel.launchBrowser(contextOptions); + const context = BrowserContext.from(result.context); + const selectors2 = this._android._playwright.selectors; + selectors2._contextsForSelectors.add(context); + context.once(Events.BrowserContext.Close, () => selectors2._contextsForSelectors.delete(context)); + await context._initializeHarFromOptions(options2.recordHar); + return context; + } + async waitForEvent(event, optionsOrPredicate = {}) { + return await this._wrapApiCall(async () => { + const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate); + const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate; + const waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`); + if (event !== Events.AndroidDevice.Close) + waiter.rejectOnEvent(this, Events.AndroidDevice.Close, () => new TargetClosedError2()); + const result = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result; + }); + } +} +class AndroidSocket extends ChannelOwner { + static from(androidDevice) { + return androidDevice._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._channel.on("data", ({ data: data2 }) => this.emit(Events.AndroidSocket.Data, data2)); + this._channel.on("close", () => this.emit(Events.AndroidSocket.Close)); + } + async write(data2) { + await this._channel.write({ data: data2 }); + } + async close() { + await this._channel.close(); + } + async [Symbol.asyncDispose]() { + await this.close(); + } +} +async function loadFile(platform, file) { + if (isString(file)) + return await platform.fs().promises.readFile(file); + return file; +} +class AndroidInput { + constructor(device) { + this._device = device; + } + async type(text) { + await this._device._channel.inputType({ text }); + } + async press(key2) { + await this._device._channel.inputPress({ key: key2 }); + } + async tap(point) { + await this._device._channel.inputTap({ point }); + } + async swipe(from2, segments, steps) { + await this._device._channel.inputSwipe({ segments, steps }); + } + async drag(from2, to, steps) { + await this._device._channel.inputDrag({ from: from2, to, steps }); + } +} +function toSelectorChannel(selector) { + const { + checkable, + checked, + clazz, + clickable, + depth, + desc, + enabled, + focusable, + focused, + hasChild, + hasDescendant, + longClickable, + pkg, + res, + scrollable, + selected, + text + } = selector; + const toRegex = (value) => { + if (value === void 0) + return void 0; + if (isRegExp$4(value)) + return value.source; + return "^" + value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d") + "$"; + }; + return { + checkable, + checked, + clazz: toRegex(clazz), + pkg: toRegex(pkg), + desc: toRegex(desc), + res: toRegex(res), + text: toRegex(text), + clickable, + depth, + enabled, + focusable, + focused, + hasChild: hasChild ? { androidSelector: toSelectorChannel(hasChild.selector) } : void 0, + hasDescendant: hasDescendant ? { androidSelector: toSelectorChannel(hasDescendant.selector), maxDepth: hasDescendant.maxDepth } : void 0, + longClickable, + scrollable, + selected + }; +} +class AndroidWebView extends EventEmitter { + constructor(device, data2) { + super(device._platform); + this._device = device; + this._data = data2; + } + pid() { + return this._data.pid; + } + pkg() { + return this._data.pkg; + } + _socketName() { + return this._data.socketName; + } + async page() { + if (!this._pagePromise) + this._pagePromise = this._fetchPage(); + return await this._pagePromise; + } + async _fetchPage() { + const { context } = await this._device._channel.connectToWebView({ socketName: this._data.socketName }); + return BrowserContext.from(context).pages()[0]; + } +} +class Browser extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._contexts = /* @__PURE__ */ new Set(); + this._isConnected = true; + this._shouldCloseConnectionOnClose = false; + this._options = {}; + this._name = initializer.name; + this._channel.on("context", ({ context }) => this._didCreateContext(BrowserContext.from(context))); + this._channel.on("close", () => this._didClose()); + this._closedPromise = new Promise((f) => this.once(Events.Browser.Disconnected, f)); + } + static from(browser2) { + return browser2._object; + } + browserType() { + return this._browserType; + } + async newContext(options2 = {}) { + return await this._innerNewContext(options2, false); + } + async _newContextForReuse(options2 = {}) { + return await this._wrapApiCall(async () => { + for (const context of this._contexts) { + await this._instrumentation.runBeforeCloseBrowserContext(context); + for (const page of context.pages()) + page._onClose(); + context._onClose(); + } + return await this._innerNewContext(options2, true); + }, { internal: true }); + } + async _stopPendingOperations(reason) { + await this._channel.stopPendingOperations({ reason }); + } + async _innerNewContext(options2 = {}, forReuse) { + options2 = this._browserType._playwright.selectors._withSelectorOptions({ + ...this._browserType._playwright._defaultContextOptions, + ...options2 + }); + const contextOptions = await prepareBrowserContextParams(this._platform, options2); + const response2 = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions); + const context = BrowserContext.from(response2.context); + if (options2.logger) + context._logger = options2.logger; + await context._initializeHarFromOptions(options2.recordHar); + await this._instrumentation.runAfterCreateBrowserContext(context); + return context; + } + _connectToBrowserType(browserType, browserOptions, logger) { + this._browserType = browserType; + this._options = browserOptions; + this._logger = logger; + for (const context of this._contexts) + this._setupBrowserContext(context); + } + _didCreateContext(context) { + context._browser = this; + this._contexts.add(context); + if (this._browserType) + this._setupBrowserContext(context); + } + _setupBrowserContext(context) { + context._logger = this._logger; + context.tracing._tracesDir = this._options.tracesDir; + this._browserType._contexts.add(context); + this._browserType._playwright.selectors._contextsForSelectors.add(context); + context.setDefaultTimeout(this._browserType._playwright._defaultContextTimeout); + context.setDefaultNavigationTimeout(this._browserType._playwright._defaultContextNavigationTimeout); + } + contexts() { + return [...this._contexts]; + } + version() { + return this._initializer.version; + } + async newPage(options2 = {}) { + return await this._wrapApiCall(async () => { + const context = await this.newContext(options2); + const page = await context.newPage(); + page._ownedContext = context; + context._ownerPage = page; + return page; + }, { title: "Create page" }); + } + isConnected() { + return this._isConnected; + } + async newBrowserCDPSession() { + return CDPSession.from((await this._channel.newBrowserCDPSession()).session); + } + async startTracing(page, options2 = {}) { + this._path = options2.path; + await this._channel.startTracing({ ...options2, page: page ? page._channel : void 0 }); + } + async stopTracing() { + const artifact = Artifact2.from((await this._channel.stopTracing()).artifact); + const buffer2 = await artifact.readIntoBuffer(); + await artifact.delete(); + if (this._path) { + await mkdirIfNeeded(this._platform, this._path); + await this._platform.fs().promises.writeFile(this._path, buffer2); + this._path = void 0; + } + return buffer2; + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async close(options2 = {}) { + this._closeReason = options2.reason; + try { + if (this._shouldCloseConnectionOnClose) + this._connection.close(); + else + await this._channel.close(options2); + await this._closedPromise; + } catch (e) { + if (isTargetClosedError(e)) + return; + throw e; + } + } + _didClose() { + this._isConnected = false; + this.emit(Events.Browser.Disconnected, this); + } +} +class BrowserType2 extends ChannelOwner { + constructor() { + super(...arguments); + this._contexts = /* @__PURE__ */ new Set(); + } + static from(browserType) { + return browserType._object; + } + executablePath() { + if (!this._initializer.executablePath) + throw new Error("Browser is not supported on current platform"); + return this._initializer.executablePath; + } + name() { + return this._initializer.name; + } + async launch(options2 = {}) { + var _a2; + assert(!options2.userDataDir, "userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead"); + assert(!options2.port, "Cannot specify a port without launching as a server."); + const logger = options2.logger || ((_a2 = this._playwright._defaultLaunchOptions) == null ? void 0 : _a2.logger); + options2 = { ...this._playwright._defaultLaunchOptions, ...options2 }; + const launchOptions = { + ...options2, + ignoreDefaultArgs: Array.isArray(options2.ignoreDefaultArgs) ? options2.ignoreDefaultArgs : void 0, + ignoreAllDefaultArgs: !!options2.ignoreDefaultArgs && !Array.isArray(options2.ignoreDefaultArgs), + env: options2.env ? envObjectToArray(options2.env) : void 0, + timeout: new TimeoutSettings(this._platform).launchTimeout(options2) + }; + return await this._wrapApiCall(async () => { + const browser2 = Browser.from((await this._channel.launch(launchOptions)).browser); + browser2._connectToBrowserType(this, options2, logger); + return browser2; + }); + } + async launchServer(options2 = {}) { + if (!this._serverLauncher) + throw new Error("Launching server is not supported"); + options2 = { ...this._playwright._defaultLaunchOptions, ...options2 }; + return await this._serverLauncher.launchServer(options2); + } + async launchPersistentContext(userDataDir, options2 = {}) { + var _a2; + const logger = options2.logger || ((_a2 = this._playwright._defaultLaunchOptions) == null ? void 0 : _a2.logger); + assert(!options2.port, "Cannot specify a port without launching as a server."); + options2 = this._playwright.selectors._withSelectorOptions({ + ...this._playwright._defaultLaunchOptions, + ...this._playwright._defaultContextOptions, + ...options2 + }); + const contextParams = await prepareBrowserContextParams(this._platform, options2); + const persistentParams = { + ...contextParams, + ignoreDefaultArgs: Array.isArray(options2.ignoreDefaultArgs) ? options2.ignoreDefaultArgs : void 0, + ignoreAllDefaultArgs: !!options2.ignoreDefaultArgs && !Array.isArray(options2.ignoreDefaultArgs), + env: options2.env ? envObjectToArray(options2.env) : void 0, + channel: options2.channel, + userDataDir: this._platform.path().isAbsolute(userDataDir) || !userDataDir ? userDataDir : this._platform.path().resolve(userDataDir), + timeout: new TimeoutSettings(this._platform).launchTimeout(options2) + }; + return await this._wrapApiCall(async () => { + const result = await this._channel.launchPersistentContext(persistentParams); + const browser2 = Browser.from(result.browser); + browser2._connectToBrowserType(this, options2, logger); + const context = BrowserContext.from(result.context); + await context._initializeHarFromOptions(options2.recordHar); + await this._instrumentation.runAfterCreateBrowserContext(context); + return context; + }); + } + async connect(optionsOrWsEndpoint, options2) { + if (typeof optionsOrWsEndpoint === "string") + return await this._connect({ ...options2, wsEndpoint: optionsOrWsEndpoint }); + assert(optionsOrWsEndpoint.wsEndpoint, "options.wsEndpoint is required"); + return await this._connect(optionsOrWsEndpoint); + } + async _connect(params) { + const logger = params.logger; + return await this._wrapApiCall(async () => { + const deadline = params.timeout ? monotonicTime() + params.timeout : 0; + const headers = { "x-playwright-browser": this.name(), ...params.headers }; + const connectParams = { + wsEndpoint: params.wsEndpoint, + headers, + exposeNetwork: params.exposeNetwork ?? params._exposeNetwork, + slowMo: params.slowMo, + timeout: params.timeout || 0 + }; + if (params.__testHookRedirectPortForwarding) + connectParams.socksProxyRedirectPortForTest = params.__testHookRedirectPortForwarding; + const connection = await connectOverWebSocket(this._connection, connectParams); + let browser2; + connection.on("close", () => { + for (const context of (browser2 == null ? void 0 : browser2.contexts()) || []) { + for (const page of context.pages()) + page._onClose(); + context._onClose(); + } + setTimeout(() => browser2 == null ? void 0 : browser2._didClose(), 0); + }); + const result = await raceAgainstDeadline(async () => { + if (params.__testHookBeforeCreateBrowser) + await params.__testHookBeforeCreateBrowser(); + const playwright2 = await connection.initializePlaywright(); + if (!playwright2._initializer.preLaunchedBrowser) { + connection.close(); + throw new Error("Malformed endpoint. Did you use BrowserType.launchServer method?"); + } + playwright2.selectors = this._playwright.selectors; + browser2 = Browser.from(playwright2._initializer.preLaunchedBrowser); + browser2._connectToBrowserType(this, {}, logger); + browser2._shouldCloseConnectionOnClose = true; + browser2.on(Events.Browser.Disconnected, () => connection.close()); + return browser2; + }, deadline); + if (!result.timedOut) { + return result.result; + } else { + connection.close(); + throw new Error(`Timeout ${params.timeout}ms exceeded`); + } + }); + } + async connectOverCDP(endpointURLOrOptions, options2) { + if (typeof endpointURLOrOptions === "string") + return await this._connectOverCDP(endpointURLOrOptions, options2); + const endpointURL = "endpointURL" in endpointURLOrOptions ? endpointURLOrOptions.endpointURL : endpointURLOrOptions.wsEndpoint; + assert(endpointURL, "Cannot connect over CDP without wsEndpoint."); + return await this.connectOverCDP(endpointURL, endpointURLOrOptions); + } + async _connectOverCDP(endpointURL, params = {}) { + if (this.name() !== "chromium") + throw new Error("Connecting over CDP is only supported in Chromium."); + const headers = params.headers ? headersObjectToArray(params.headers) : void 0; + const result = await this._channel.connectOverCDP({ + endpointURL, + headers, + slowMo: params.slowMo, + timeout: new TimeoutSettings(this._platform).timeout(params) + }); + const browser2 = Browser.from(result.browser); + browser2._connectToBrowserType(this, {}, params.logger); + if (result.defaultContext) + await this._instrumentation.runAfterCreateBrowserContext(BrowserContext.from(result.defaultContext)); + return browser2; + } +} +function createInstrumentation() { + const listeners = []; + return new Proxy({}, { + get: (obj, prop) => { + if (typeof prop !== "string") + return obj[prop]; + if (prop === "addListener") + return (listener) => listeners.push(listener); + if (prop === "removeListener") + return (listener) => listeners.splice(listeners.indexOf(listener), 1); + if (prop === "removeAllListeners") + return () => listeners.splice(0, listeners.length); + if (prop.startsWith("run")) { + return async (...params) => { + var _a2; + for (const listener of listeners) + await ((_a2 = listener[prop]) == null ? void 0 : _a2.call(listener, ...params)); + }; + } + if (prop.startsWith("on")) { + return (...params) => { + var _a2; + for (const listener of listeners) + (_a2 = listener[prop]) == null ? void 0 : _a2.call(listener, ...params); + }; + } + return obj[prop]; + } + }); +} +class Electron2 extends ChannelOwner { + static from(electron) { + return electron._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + } + async launch(options2 = {}) { + options2 = this._playwright.selectors._withSelectorOptions(options2); + const params = { + ...await prepareBrowserContextParams(this._platform, options2), + env: envObjectToArray(options2.env ? options2.env : this._platform.env), + tracesDir: options2.tracesDir, + timeout: new TimeoutSettings(this._platform).launchTimeout(options2) + }; + const app = ElectronApplication.from((await this._channel.launch(params)).electronApplication); + this._playwright.selectors._contextsForSelectors.add(app._context); + app.once(Events.ElectronApplication.Close, () => this._playwright.selectors._contextsForSelectors.delete(app._context)); + await app._context._initializeHarFromOptions(options2.recordHar); + app._context.tracing._tracesDir = options2.tracesDir; + return app; + } +} +class ElectronApplication extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this._windows = /* @__PURE__ */ new Set(); + this._timeoutSettings = new TimeoutSettings(this._platform); + this._context = BrowserContext.from(initializer.context); + for (const page of this._context._pages) + this._onPage(page); + this._context.on(Events.BrowserContext.Page, (page) => this._onPage(page)); + this._channel.on("close", () => { + this.emit(Events.ElectronApplication.Close); + }); + this._channel.on("console", (event) => this.emit(Events.ElectronApplication.Console, new ConsoleMessage2(this._platform, event))); + this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([ + [Events.ElectronApplication.Console, "console"] + ])); + } + static from(electronApplication) { + return electronApplication._object; + } + process() { + return this._toImpl().process(); + } + _onPage(page) { + this._windows.add(page); + this.emit(Events.ElectronApplication.Window, page); + page.once(Events.Page.Close, () => this._windows.delete(page)); + } + windows() { + return [...this._windows]; + } + async firstWindow(options2) { + if (this._windows.size) + return this._windows.values().next().value; + return await this.waitForEvent("window", options2); + } + context() { + return this._context; + } + async [Symbol.asyncDispose]() { + await this.close(); + } + async close() { + try { + await this._context.close(); + } catch (e) { + if (isTargetClosedError(e)) + return; + throw e; + } + } + async waitForEvent(event, optionsOrPredicate = {}) { + return await this._wrapApiCall(async () => { + const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate); + const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate; + const waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`); + if (event !== Events.ElectronApplication.Close) + waiter.rejectOnEvent(this, Events.ElectronApplication.Close, () => new TargetClosedError2()); + const result = await waiter.waitForEvent(this, event, predicate); + waiter.dispose(); + return result; + }); + } + async browserWindow(page) { + const result = await this._channel.browserWindow({ page: page._channel }); + return JSHandle2.from(result.handle); + } + async evaluate(pageFunction, arg) { + const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return parseResult(result.value); + } + async evaluateHandle(pageFunction, arg) { + const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) }); + return JSHandle2.from(result.handle); + } +} +class JsonPipe extends ChannelOwner { + static from(jsonPipe) { + return jsonPipe._object; + } + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + } + channel() { + return this._channel; + } +} +class LocalUtils extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + this.devices = {}; + for (const { name, descriptor } of initializer.deviceDescriptors) + this.devices[name] = descriptor; + } + async zip(params) { + return await this._channel.zip(params); + } + async harOpen(params) { + return await this._channel.harOpen(params); + } + async harLookup(params) { + return await this._channel.harLookup(params); + } + async harClose(params) { + return await this._channel.harClose(params); + } + async harUnzip(params) { + return await this._channel.harUnzip(params); + } + async tracingStarted(params) { + return await this._channel.tracingStarted(params); + } + async traceDiscarded(params) { + return await this._channel.traceDiscarded(params); + } + async addStackToTracingNoReply(params) { + return await this._channel.addStackToTracingNoReply(params); + } +} +class Selectors2 { + constructor(platform) { + this._selectorEngines = []; + this._contextsForSelectors = /* @__PURE__ */ new Set(); + this._platform = platform; + } + async register(name, script, options2 = {}) { + const source2 = await evaluationScript(this._platform, script, void 0, false); + const selectorEngine = { ...options2, name, source: source2 }; + for (const context of this._contextsForSelectors) + await context._channel.registerSelectorEngine({ selectorEngine }); + this._selectorEngines.push(selectorEngine); + } + setTestIdAttribute(attributeName) { + this._testIdAttributeName = attributeName; + setTestIdAttribute(attributeName); + for (const context of this._contextsForSelectors) + context._channel.setTestIdAttributeName({ testIdAttributeName: attributeName }).catch(() => { + }); + } + _withSelectorOptions(options2) { + return { ...options2, selectorEngines: this._selectorEngines, testIdAttributeName: this._testIdAttributeName }; + } +} +class Playwright2 extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + var _a2; + super(parent, type2, guid, initializer); + this.request = new APIRequest(this); + this.chromium = BrowserType2.from(initializer.chromium); + this.chromium._playwright = this; + this.firefox = BrowserType2.from(initializer.firefox); + this.firefox._playwright = this; + this.webkit = BrowserType2.from(initializer.webkit); + this.webkit._playwright = this; + this._android = Android2.from(initializer.android); + this._android._playwright = this; + this._electron = Electron2.from(initializer.electron); + this._electron._playwright = this; + this._bidiChromium = BrowserType2.from(initializer.bidiChromium); + this._bidiChromium._playwright = this; + this._bidiFirefox = BrowserType2.from(initializer.bidiFirefox); + this._bidiFirefox._playwright = this; + this.devices = ((_a2 = this._connection.localUtils()) == null ? void 0 : _a2.devices) ?? {}; + this.selectors = new Selectors2(this._connection._platform); + this.errors = { TimeoutError: TimeoutError2 }; + global._playwrightInstance = this; + } + static from(channel) { + return channel._object; + } + _browserTypes() { + return [this.chromium, this.firefox, this.webkit, this._bidiChromium, this._bidiFirefox]; + } + _preLaunchedBrowser() { + const browser2 = Browser.from(this._initializer.preLaunchedBrowser); + browser2._connectToBrowserType(this[browser2._name], {}, void 0); + return browser2; + } + _allContexts() { + return this._browserTypes().flatMap((type2) => [...type2._contexts]); + } + _allPages() { + return this._allContexts().flatMap((context) => context.pages()); + } +} +class Root extends ChannelOwner { + constructor(connection) { + super(connection, "Root", "", {}); + } + async initialize() { + return Playwright2.from((await this._channel.initialize({ + sdkLanguage: "javascript" + })).playwright); + } +} +class DummyChannelOwner extends ChannelOwner { +} +class Connection extends EventEmitter { + constructor(platform, localUtils, instrumentation, headers = []) { + super(platform); + this._objects = /* @__PURE__ */ new Map(); + this.onmessage = (message) => { + }; + this._lastId = 0; + this._callbacks = /* @__PURE__ */ new Map(); + this._isRemote = false; + this._rawBuffers = false; + this._tracingCount = 0; + this._instrumentation = instrumentation || createInstrumentation(); + this._localUtils = localUtils; + this._rootObject = new Root(this); + this.headers = headers; + } + markAsRemote() { + this._isRemote = true; + } + isRemote() { + return this._isRemote; + } + useRawBuffers() { + this._rawBuffers = true; + } + rawBuffers() { + return this._rawBuffers; + } + localUtils() { + return this._localUtils; + } + async initializePlaywright() { + return await this._rootObject.initialize(); + } + getObjectWithKnownName(guid) { + return this._objects.get(guid); + } + setIsTracing(isTracing) { + if (isTracing) + this._tracingCount++; + else + this._tracingCount--; + } + async sendMessageToServer(object, method, params, options2) { + var _a2, _b2; + if (this._closedError) + throw this._closedError; + if (object._wasCollected) + throw new Error("The object has been collected to prevent unbounded heap growth."); + const guid = object._guid; + const type2 = object._type; + const id = ++this._lastId; + const message = { id, guid, method, params }; + if (this._platform.isLogEnabled("channel")) { + this._platform.log("channel", "SEND> " + JSON.stringify(message)); + } + const location2 = ((_a2 = options2.frames) == null ? void 0 : _a2[0]) ? { file: options2.frames[0].file, line: options2.frames[0].line, column: options2.frames[0].column } : void 0; + const metadata = { title: options2.title, location: location2, internal: options2.internal, stepId: options2.stepId }; + if (this._tracingCount && options2.frames && type2 !== "LocalUtils") + (_b2 = this._localUtils) == null ? void 0 : _b2.addStackToTracingNoReply({ callData: { stack: options2.frames ?? [], id } }).catch(() => { + }); + this._platform.zones.empty.run(() => this.onmessage({ ...message, metadata })); + return await new Promise((resolve, reject) => this._callbacks.set(id, { resolve, reject, title: options2.title, type: type2, method })); + } + _validatorFromWireContext() { + return { + tChannelImpl: this._tChannelImplFromWire.bind(this), + binary: this._rawBuffers ? "buffer" : "fromBase64", + isUnderTest: () => this._platform.isUnderTest() + }; + } + dispatch(message) { + if (this._closedError) + return; + const { id, guid, method, params, result, error: error2, log } = message; + if (id) { + if (this._platform.isLogEnabled("channel")) + this._platform.log("channel", " !!l)) + return ""; + return ` +Call log: +${platform.colors.dim(log.join("\n"))} +`; +} +function from(obj) { + return obj._object; +} +let Crx$1 = class Crx extends ChannelOwner { + constructor() { + super(...arguments); + __publicField(this, "fs", fs); + __publicField(this, "_crxAppPromise"); + __publicField(this, "_incognitoCrxPromise"); + } + static from(crx2) { + return crx2._object; + } + async start(options2) { + if (options2 == null ? void 0 : options2.incognito) { + if (this._incognitoCrxPromise) + throw new Error(`incognito crxApplication is already started`); + this._incognitoCrxPromise = this._start(options2, () => this._incognitoCrxPromise = void 0); + return await this._incognitoCrxPromise; + } else { + if (this._crxAppPromise) + throw new Error(`crxApplication is already started`); + this._crxAppPromise = this._start(options2 ?? {}, () => this._crxAppPromise = void 0); + return await this._crxAppPromise; + } + } + async _start(options2, onClose) { + const crxApp = from((await this._channel.start(options2 ?? {})).crxApplication); + crxApp.on("close", onClose); + return crxApp; + } + async get(options2) { + if (options2 == null ? void 0 : options2.incognito) + return await this._incognitoCrxPromise; + else + return await this._crxAppPromise; + } +}; +class CrxRecorder extends eventsExports.EventEmitter { + constructor(channel) { + super(); + __publicField(this, "_channel"); + __publicField(this, "_hidden", true); + __publicField(this, "_mode", "none"); + this._channel = channel; + this._channel.on("hide", () => { + this._hidden = true; + this.emit("hide"); + }); + this._channel.on("show", () => { + this._hidden = false; + this.emit("show"); + }); + this._channel.on("modeChanged", (event) => { + this._mode = event.mode; + this.emit("modechanged", event); + }); + } + mode() { + return this._mode; + } + isHidden() { + return this._hidden; + } + async setMode(mode) { + await this._channel.setMode({ mode }); + } + async show(options2) { + await this._channel.showRecorder(options2 ?? {}); + } + async hide() { + await this._channel.hideRecorder(); + } + async list(code) { + const { tests } = await this._channel.list({ code }); + return tests; + } + async load(code) { + await this._channel.load({ code }); + } + async run(code, page) { + await this._channel.run({ code, page: page == null ? void 0 : page._channel }); + } +} +let CrxApplication$1 = class CrxApplication extends ChannelOwner { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + __publicField(this, "_context"); + __publicField(this, "recorder"); + this._context = initializer.context._object; + this.recorder = new CrxRecorder(this._channel); + this._channel.on("attached", ({ page, tabId }) => { + this.emit("attached", { tabId, page: Page.from(page) }); + }); + this._channel.on("detached", ({ tabId }) => { + this.emit("detached", tabId); + }); + this._context.on("close", () => { + this.emit("close"); + }); + } + static from(crxApplication) { + return crxApplication._object; + } + context() { + return this._context; + } + pages() { + return this._context.pages(); + } + async attach(tabId) { + return from((await this._channel.attach({ tabId })).page); + } + async attachAll(options2) { + const { url: urlOrUrls, ...remaining } = options2 ?? {}; + const url2 = urlOrUrls ? typeof urlOrUrls === "string" ? [urlOrUrls] : urlOrUrls : void 0; + const params = { ...remaining, url: url2 }; + return (await this._channel.attachAll(params)).pages.map((p) => from(p)); + } + async detach(tabIdOrPage) { + const params = typeof tabIdOrPage === "number" ? { tabId: tabIdOrPage } : { page: tabIdOrPage._channel }; + await this._channel.detach(params); + } + async detachAll() { + await this._channel.detachAll(); + } + async newPage(options2) { + return from((await this._channel.newPage(options2 ?? {})).page); + } + async close() { + await this._channel.close(); + } +}; +let CrxPlaywright$1 = class CrxPlaywright extends Playwright2 { + constructor(parent, type2, guid, initializer) { + super(parent, type2, guid, initializer); + __publicField(this, "_crx"); + this._crx = Crx$1.from(initializer._crx); + } +}; +class CrxConnection extends Connection { + constructor(platform) { + super(platform, void 0, void 0); + this.useRawBuffers(); + } + dispatch(message) { + const { guid: parentGuid, method, params } = message; + if (method === "__create__") { + const { type: type2, guid } = params; + let initializer = params.initializer; + const parent = this._objects.get(parentGuid); + const validator = findValidator(type2, "", "Initializer"); + initializer = validator(initializer, "", { + tChannelImpl: this._tChannelImplFromWire.bind(this), + binary: "buffer", + isUnderTest: () => this._platform.isUnderTest() + }); + switch (type2) { + case "Playwright": + new CrxPlaywright$1(parent, type2, guid, initializer); + return; + case "Crx": + new Crx$1(parent, type2, guid, initializer); + return; + case "CrxApplication": + new CrxApplication$1(parent, type2, guid, initializer); + return; + } + } + return super.dispatch(message); + } +} +class PopupRecorderWindow { + constructor(recorderUrl) { + __publicField(this, "_recorderUrl"); + __publicField(this, "_window"); + __publicField(this, "id"); + __publicField(this, "_portPromise"); + __publicField(this, "_isClosing", false); + __publicField(this, "onMessage"); + __publicField(this, "hideApp"); + this._recorderUrl = recorderUrl ?? "index.html"; + chrome.windows.onRemoved.addListener((window2) => { + var _a2; + if (((_a2 = this._window) == null ? void 0 : _a2.id) === window2) + this.close().catch(() => { + }); + }); + } + isClosed() { + return !this._window; + } + postMessage(msg) { + var _a2; + (_a2 = this._portPromise) == null ? void 0 : _a2.then((port) => port.postMessage({ ...msg })).catch(() => { + }); + } + async open() { + if (this._window) + return; + this._portPromise = new Promise((resolve) => { + const onConnect = (port) => { + chrome.runtime.onConnect.removeListener(onConnect); + port.onDisconnect.addListener(this.close.bind(this)); + if (this.onMessage) + port.onMessage.addListener(this.onMessage); + resolve(port); + }; + chrome.runtime.onConnect.addListener(onConnect); + }); + const [wnd] = await Promise.all([ + chrome.windows.create({ type: "popup", url: this._recorderUrl }), + this._portPromise + ]); + this._window = wnd; + } + async focus() { + await chrome.windows.update(this.id, { drawAttention: true, focused: true }); + } + async close() { + var _a2, _b2, _c2; + if (!this._portPromise || this._isClosing) + return; + this._isClosing = true; + try { + (_a2 = this.hideApp) == null ? void 0 : _a2.call(this); + if ((_b2 = this._window) == null ? void 0 : _b2.id) + chrome.windows.remove(this._window.id).catch(() => { + }); + (_c2 = this._portPromise) == null ? void 0 : _c2.then((port) => port.disconnect()).catch(() => { + }); + this._window = void 0; + this._portPromise = void 0; + } finally { + this._isClosing = false; + } + } +} +class SidepanelRecorderWindow { + constructor(recorderUrl) { + __publicField(this, "_recorderUrl"); + __publicField(this, "_portPromise"); + __publicField(this, "_closed", true); + __publicField(this, "onMessage"); + __publicField(this, "hideApp"); + this._recorderUrl = recorderUrl ?? "index.html"; + this._portPromise = this._waitConnect(); + } + isClosed() { + return this._closed; + } + postMessage(msg) { + this._portPromise.then((port) => port.postMessage({ ...msg })).catch(() => { + }); + } + async open() { + await chrome.sidePanel.setOptions({ path: this._recorderUrl }); + await this._portPromise; + this._closed = false; + } + async focus() { + } + async close() { + var _a2; + if (this._closed) + return; + this._closed = true; + this._portPromise.then((port) => port.disconnect()); + this._portPromise = this._waitConnect(); + (_a2 = this.hideApp) == null ? void 0 : _a2.call(this); + } + _waitConnect() { + return new Promise((resolve) => { + const onConnect = (port) => { + chrome.runtime.onConnect.removeListener(onConnect); + port.onDisconnect.addListener(this.close.bind(this)); + if (this.onMessage) + port.onMessage.addListener(this.onMessage.bind(this)); + resolve(port); + }; + chrome.runtime.onConnect.addListener(onConnect); + }); + } +} +var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; +var nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・"; +var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ"; +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +}; +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; +var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" +}; +var keywordRelationalOperator = /^in(stanceof)?$/; +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +function isInAstralSet(code, set2) { + var pos = 65536; + for (var i = 0; i < set2.length; i += 2) { + pos += set2[i]; + if (pos > code) { + return false; + } + pos += set2[i + 1]; + if (pos >= code) { + return true; + } + } + return false; +} +function isIdentifierStart(code, astral) { + if (code < 65) { + return code === 36; + } + if (code < 91) { + return true; + } + if (code < 97) { + return code === 95; + } + if (code < 123) { + return true; + } + if (code <= 65535) { + return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + if (astral === false) { + return false; + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code, astral) { + if (code < 48) { + return code === 36; + } + if (code < 58) { + return true; + } + if (code < 65) { + return false; + } + if (code < 91) { + return true; + } + if (code < 97) { + return code === 95; + } + if (code < 123) { + return true; + } + if (code <= 65535) { + return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)); + } + if (astral === false) { + return false; + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +var TokenType = function TokenType2(label, conf) { + if (conf === void 0) conf = {}; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; +}; +function binop(name, prec) { + return new TokenType(name, { beforeExpr: true, binop: prec }); +} +var beforeExpr = { beforeExpr: true }, startsExpr = { startsExpr: true }; +var keywords = {}; +function kw(name, options2) { + if (options2 === void 0) options2 = {}; + options2.keyword = name; + return keywords[name] = new TokenType(name, options2); +} +var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + // Punctuation token types. + bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }), + bracketR: new TokenType("]"), + braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }), + braceR: new TokenType("}"), + parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }), + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + eq: new TokenType("=", { beforeExpr: true, isAssign: true }), + assign: new TokenType("_=", { beforeExpr: true, isAssign: true }), + incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }), + prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", { beforeExpr: true }), + coalesce: binop("??", 1), + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", { isLoop: true, beforeExpr: true }), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", { isLoop: true }), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", { isLoop: true }), + _with: kw("with"), + _new: kw("new", { beforeExpr: true, startsExpr: true }), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", { beforeExpr: true, binop: 7 }), + _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }), + _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }), + _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }), + _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true }) +}; +var lineBreak = /\r\n?|\n|\u2028|\u2029/; +var lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + return code === 10 || code === 13 || code === 8232 || code === 8233; +} +function nextLineBreak(code, from2, end) { + if (end === void 0) end = code.length; + for (var i = from2; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) { + return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1; + } + } + return -1; +} +var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +var ref = Object.prototype; +var hasOwnProperty = ref.hasOwnProperty; +var toString = ref.toString; +var hasOwn = Object.hasOwn || function(obj, propName) { + return hasOwnProperty.call(obj, propName); +}; +var isArray = Array.isArray || function(obj) { + return toString.call(obj) === "[object Array]"; +}; +var regexpCache = /* @__PURE__ */ Object.create(null); +function wordsRegexp(words) { + return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")); +} +function codePointToString(code) { + if (code <= 65535) { + return String.fromCharCode(code); + } + code -= 65536; + return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320); +} +var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; +var Position = function Position2(line, col) { + this.line = line; + this.column = col; +}; +Position.prototype.offset = function offset(n) { + return new Position(this.line, this.column + n); +}; +var SourceLocation = function SourceLocation2(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { + this.source = p.sourceFile; + } +}; +function getLineInfo(input, offset2) { + for (var line = 1, cur = 0; ; ) { + var nextBreak = nextLineBreak(input, cur, offset2); + if (nextBreak < 0) { + return new Position(line, offset2 - cur); + } + ++line; + cur = nextBreak; + } +} +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called when + // a semicolon is automatically inserted. It will be passed the + // position of the inserted semicolon as an offset, and if + // `locations` is enabled, it is given the location as a `{line, + // column}` object as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + // When this option has an array as value, objects representing the + // comments are pushed to it. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false +}; +var warnedAboutEcmaVersion = false; +function getOptions(opts) { + var options2 = {}; + for (var opt in defaultOptions) { + options2[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; + } + if (options2.ecmaVersion === "latest") { + options2.ecmaVersion = 1e8; + } else if (options2.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options2.ecmaVersion = 11; + } else if (options2.ecmaVersion >= 2015) { + options2.ecmaVersion -= 2009; + } + if (options2.allowReserved == null) { + options2.allowReserved = options2.ecmaVersion < 5; + } + if (!opts || opts.allowHashBang == null) { + options2.allowHashBang = options2.ecmaVersion >= 14; + } + if (isArray(options2.onToken)) { + var tokens = options2.onToken; + options2.onToken = function(token) { + return tokens.push(token); + }; + } + if (isArray(options2.onComment)) { + options2.onComment = pushComment(options2, options2.onComment); + } + return options2; +} +function pushComment(options2, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment2 = { + type: block ? "Block" : "Line", + value: text, + start, + end + }; + if (options2.locations) { + comment2.loc = new SourceLocation(this, startLoc, endLoc); + } + if (options2.ranges) { + comment2.range = [start, end]; + } + array.push(comment2); + }; +} +var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; +function functionFlags(async2, generator) { + return SCOPE_FUNCTION | (async2 ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0); +} +var BIND_NONE = 0, BIND_VAR = 1, BIND_LEXICAL = 2, BIND_FUNCTION = 3, BIND_SIMPLE_CATCH = 4, BIND_OUTSIDE = 5; +var Parser2 = function Parser3(options2, input, startPos) { + this.options = options2 = getOptions(options2); + this.sourceFile = options2.sourceFile; + this.keywords = wordsRegexp(keywords$1[options2.ecmaVersion >= 6 ? 6 : options2.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options2.allowReserved !== true) { + reserved = reservedWords[options2.ecmaVersion >= 6 ? 6 : options2.ecmaVersion === 5 ? 5 : 3]; + if (options2.sourceType === "module") { + reserved += " await"; + } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + this.containsEsc = false; + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + this.type = types$1.eof; + this.value = null; + this.start = this.end = this.pos; + this.startLoc = this.endLoc = this.curPosition(); + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + this.context = this.initialContext(); + this.exprAllowed = true; + this.inModule = options2.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + this.labels = []; + this.undefinedExports = /* @__PURE__ */ Object.create(null); + if (this.pos === 0 && options2.allowHashBang && this.input.slice(0, 2) === "#!") { + this.skipLineComment(2); + } + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + this.regexpState = null; + this.privateNameStack = []; +}; +var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, inClassStaticBlock: { configurable: true } }; +Parser2.prototype.parse = function parse() { + var node2 = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node2); +}; +prototypeAccessors.inFunction.get = function() { + return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0; +}; +prototypeAccessors.inGenerator.get = function() { + return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit; +}; +prototypeAccessors.inAsync.get = function() { + return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit; +}; +prototypeAccessors.canAwait.get = function() { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { + return false; + } + if (scope.flags & SCOPE_FUNCTION) { + return (scope.flags & SCOPE_ASYNC) > 0; + } + } + return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction; +}; +prototypeAccessors.allowSuper.get = function() { + var ref2 = this.currentThisScope(); + var flags = ref2.flags; + var inClassFieldInit = ref2.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod; +}; +prototypeAccessors.allowDirectSuper.get = function() { + return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0; +}; +prototypeAccessors.treatFunctionsAsVar.get = function() { + return this.treatFunctionsAsVarInScope(this.currentScope()); +}; +prototypeAccessors.allowNewDotTarget.get = function() { + var ref2 = this.currentThisScope(); + var flags = ref2.flags; + var inClassFieldInit = ref2.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit; +}; +prototypeAccessors.inClassStaticBlock.get = function() { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0; +}; +Parser2.extend = function extend() { + var plugins = [], len = arguments.length; + while (len--) plugins[len] = arguments[len]; + var cls = this; + for (var i = 0; i < plugins.length; i++) { + cls = plugins[i](cls); + } + return cls; +}; +Parser2.parse = function parse2(input, options2) { + return new this(options2, input).parse(); +}; +Parser2.parseExpressionAt = function parseExpressionAt(input, pos, options2) { + var parser2 = new this(options2, input, pos); + parser2.nextToken(); + return parser2.parseExpression(); +}; +Parser2.tokenizer = function tokenizer(input, options2) { + return new this(options2, input); +}; +Object.defineProperties(Parser2.prototype, prototypeAccessors); +var pp$9 = Parser2.prototype; +var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/; +pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { + return false; + } + for (; ; ) { + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { + return false; + } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="); + } + start += match[0].length; + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") { + start++; + } + } +}; +pp$9.eat = function(type2) { + if (this.type === type2) { + this.next(); + return true; + } else { + return false; + } +}; +pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc; +}; +pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { + return false; + } + this.next(); + return true; +}; +pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { + this.unexpected(); + } +}; +pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); +}; +pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) { + this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); + } + return true; + } +}; +pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { + this.unexpected(); + } +}; +pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) { + this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); + } + if (!notNext) { + this.next(); + } + return true; + } +}; +pp$9.expect = function(type2) { + this.eat(type2) || this.unexpected(); +}; +pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); +}; +var DestructuringErrors = function DestructuringErrors2() { + this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; +}; +pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { + return; + } + if (refDestructuringErrors.trailingComma > -1) { + this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); + } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { + this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); + } +}; +pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { + return false; + } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { + return shorthandAssign >= 0 || doubleProto >= 0; + } + if (shorthandAssign >= 0) { + this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); + } + if (doubleProto >= 0) { + this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); + } +}; +pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { + this.raise(this.yieldPos, "Yield expression cannot be a default value"); + } + if (this.awaitPos) { + this.raise(this.awaitPos, "Await expression cannot be a default value"); + } +}; +pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") { + return this.isSimpleAssignTarget(expr.expression); + } + return expr.type === "Identifier" || expr.type === "MemberExpression"; +}; +var pp$8 = Parser2.prototype; +pp$8.parseTopLevel = function(node2) { + var exports = /* @__PURE__ */ Object.create(null); + if (!node2.body) { + node2.body = []; + } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node2.body.push(stmt); + } + if (this.inModule) { + for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { + var name = list[i]; + this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined"); + } + } + this.adaptDirectivePrologue(node2.body); + this.next(); + node2.sourceType = this.options.sourceType; + return this.finishNode(node2, "Program"); +}; +var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; +pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 91 || nextCh === 92) { + return true; + } + if (context) { + return false; + } + if (nextCh === 123 || nextCh > 55295 && nextCh < 56320) { + return true; + } + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { + ++pos; + } + if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) { + return true; + } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { + return true; + } + } + return false; +}; +pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320)); +}; +pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node2 = this.startNode(), kind; + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + switch (starttype) { + case types$1._break: + case types$1._continue: + return this.parseBreakContinueStatement(node2, starttype.keyword); + case types$1._debugger: + return this.parseDebuggerStatement(node2); + case types$1._do: + return this.parseDoStatement(node2); + case types$1._for: + return this.parseForStatement(node2); + case types$1._function: + if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) { + this.unexpected(); + } + return this.parseFunctionStatement(node2, false, !context); + case types$1._class: + if (context) { + this.unexpected(); + } + return this.parseClass(node2, true); + case types$1._if: + return this.parseIfStatement(node2); + case types$1._return: + return this.parseReturnStatement(node2); + case types$1._switch: + return this.parseSwitchStatement(node2); + case types$1._throw: + return this.parseThrowStatement(node2); + case types$1._try: + return this.parseTryStatement(node2); + case types$1._const: + case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { + this.unexpected(); + } + return this.parseVarStatement(node2, kind); + case types$1._while: + return this.parseWhileStatement(node2); + case types$1._with: + return this.parseWithStatement(node2); + case types$1.braceL: + return this.parseBlock(true, node2); + case types$1.semi: + return this.parseEmptyStatement(node2); + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) { + return this.parseExpressionStatement(node2, this.parseExpression()); + } + } + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) { + this.raise(this.start, "'import' and 'export' may only appear at the top level"); + } + if (!this.inModule) { + this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); + } + } + return starttype === types$1._import ? this.parseImport(node2) : this.parseExport(node2, exports); + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { + this.unexpected(); + } + this.next(); + return this.parseFunctionStatement(node2, true, !context); + } + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { + return this.parseLabeledStatement(node2, maybeName, expr, context); + } else { + return this.parseExpressionStatement(node2, expr); + } + } +}; +pp$8.parseBreakContinueStatement = function(node2, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { + node2.label = null; + } else if (this.type !== types$1.name) { + this.unexpected(); + } else { + node2.label = this.parseIdent(); + this.semicolon(); + } + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node2.label == null || lab.name === node2.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { + break; + } + if (node2.label && isBreak) { + break; + } + } + } + if (i === this.labels.length) { + this.raise(node2.start, "Unsyntactic " + keyword); + } + return this.finishNode(node2, isBreak ? "BreakStatement" : "ContinueStatement"); +}; +pp$8.parseDebuggerStatement = function(node2) { + this.next(); + this.semicolon(); + return this.finishNode(node2, "DebuggerStatement"); +}; +pp$8.parseDoStatement = function(node2) { + this.next(); + this.labels.push(loopLabel); + node2.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node2.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) { + this.eat(types$1.semi); + } else { + this.semicolon(); + } + return this.finishNode(node2, "DoWhileStatement"); +}; +pp$8.parseForStatement = function(node2) { + this.next(); + var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node2, null); + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + } else { + node2.await = awaitAt > -1; + } + } + return this.parseForIn(node2, init$1); + } + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node2, init$1); + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var containsEsc = this.containsEsc; + var refDestructuringErrors = new DestructuringErrors(); + var initPos = this.start; + var init = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (awaitAt > -1) { + if (this.type === types$1._in) { + this.unexpected(awaitAt); + } + node2.await = true; + } else if (isForOf && this.options.ecmaVersion >= 8) { + if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") { + this.unexpected(); + } else if (this.options.ecmaVersion >= 9) { + node2.await = false; + } + } + if (startsWithLet && isForOf) { + this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); + } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node2, init); + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node2, init); +}; +pp$8.parseFunctionStatement = function(node2, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node2, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync); +}; +pp$8.parseIfStatement = function(node2) { + this.next(); + node2.test = this.parseParenExpression(); + node2.consequent = this.parseStatement("if"); + node2.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node2, "IfStatement"); +}; +pp$8.parseReturnStatement = function(node2) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) { + this.raise(this.start, "'return' outside of function"); + } + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { + node2.argument = null; + } else { + node2.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node2, "ReturnStatement"); +}; +pp$8.parseSwitchStatement = function(node2) { + this.next(); + node2.discriminant = this.parseParenExpression(); + node2.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + var cur; + for (var sawDefault = false; this.type !== types$1.braceR; ) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { + this.finishNode(cur, "SwitchCase"); + } + node2.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); + } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { + this.unexpected(); + } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { + this.finishNode(cur, "SwitchCase"); + } + this.next(); + this.labels.pop(); + return this.finishNode(node2, "SwitchStatement"); +}; +pp$8.parseThrowStatement = function(node2) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { + this.raise(this.lastTokEnd, "Illegal newline after throw"); + } + node2.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node2, "ThrowStatement"); +}; +var empty$1 = []; +pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + return param; +}; +pp$8.parseTryStatement = function(node2) { + this.next(); + node2.block = this.parseBlock(); + node2.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { + this.unexpected(); + } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node2.handler = this.finishNode(clause, "CatchClause"); + } + node2.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node2.handler && !node2.finalizer) { + this.raise(node2.start, "Missing catch or finally clause"); + } + return this.finishNode(node2, "TryStatement"); +}; +pp$8.parseVarStatement = function(node2, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node2, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node2, "VariableDeclaration"); +}; +pp$8.parseWhileStatement = function(node2) { + this.next(); + node2.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node2.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node2, "WhileStatement"); +}; +pp$8.parseWithStatement = function(node2) { + if (this.strict) { + this.raise(this.start, "'with' in strict mode"); + } + this.next(); + node2.object = this.parseParenExpression(); + node2.body = this.parseStatement("with"); + return this.finishNode(node2, "WithStatement"); +}; +pp$8.parseEmptyStatement = function(node2) { + this.next(); + return this.finishNode(node2, "EmptyStatement"); +}; +pp$8.parseLabeledStatement = function(node2, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { + var label = list[i$1]; + if (label.name === maybeName) { + this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } + } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node2.start) { + label$1.statementStart = this.start; + label$1.kind = kind; + } else { + break; + } + } + this.labels.push({ name: maybeName, kind, statementStart: this.start }); + node2.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node2.label = expr; + return this.finishNode(node2, "LabeledStatement"); +}; +pp$8.parseExpressionStatement = function(node2, expr) { + node2.expression = expr; + this.semicolon(); + return this.finishNode(node2, "ExpressionStatement"); +}; +pp$8.parseBlock = function(createNewLexicalScope, node2, exitStrict) { + if (createNewLexicalScope === void 0) createNewLexicalScope = true; + if (node2 === void 0) node2 = this.startNode(); + node2.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { + this.enterScope(0); + } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node2.body.push(stmt); + } + if (exitStrict) { + this.strict = false; + } + this.next(); + if (createNewLexicalScope) { + this.exitScope(); + } + return this.finishNode(node2, "BlockStatement"); +}; +pp$8.parseFor = function(node2, init) { + node2.init = init; + this.expect(types$1.semi); + node2.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node2.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node2.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node2, "ForStatement"); +}; +pp$8.parseForIn = function(node2, init) { + var isForIn = this.type === types$1._in; + this.next(); + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise( + init.start, + (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer" + ); + } + node2.left = init; + node2.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node2.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node2, isForIn ? "ForInStatement" : "ForOfStatement"); +}; +pp$8.parseVar = function(node2, isFor, kind, allowMissingInitializer) { + node2.declarations = []; + node2.kind = kind; + for (; ; ) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + this.unexpected(); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node2.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { + break; + } + } + return node2; +}; +pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); +}; +var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; +pp$8.parseFunction = function(node2, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node2); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) { + this.unexpected(); + } + node2.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) { + node2.async = !!isAsync; + } + if (statement & FUNC_STATEMENT) { + node2.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent(); + if (node2.id && !(statement & FUNC_HANGING_STATEMENT)) { + this.checkLValSimple(node2.id, this.strict || node2.generator || node2.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); + } + } + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node2.async, node2.generator)); + if (!(statement & FUNC_STATEMENT)) { + node2.id = this.type === types$1.name ? this.parseIdent() : null; + } + this.parseFunctionParams(node2); + this.parseFunctionBody(node2, allowExpressionBody, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node2, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression"); +}; +pp$8.parseFunctionParams = function(node2) { + this.expect(types$1.parenL); + node2.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); +}; +pp$8.parseClass = function(node2, isStatement) { + this.next(); + var oldStrict = this.strict; + this.strict = true; + this.parseClassId(node2, isStatement); + this.parseClassSuper(node2); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node2.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { + this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); + } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared"); + } + } + } + this.strict = oldStrict; + this.next(); + node2.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node2, isStatement ? "ClassDeclaration" : "ClassExpression"); +}; +pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { + return null; + } + var ecmaVersion = this.options.ecmaVersion; + var node2 = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + if (this.eatContextual("static")) { + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node2); + return node2; + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node2.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + if (keyName) { + node2.computed = false; + node2.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node2.key.name = keyName; + this.finishNode(node2.key, "Identifier"); + } else { + this.parseClassElementName(node2); + } + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node2.static && checkKeyName(node2, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + if (isConstructor && kind !== "method") { + this.raise(node2.key.start, "Constructor can't have get/set modifier"); + } + node2.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node2, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node2); + } + return node2; +}; +pp$8.isClassElementNameStart = function() { + return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword; +}; +pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } +}; +pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + var key2 = method.key; + if (method.kind === "constructor") { + if (isGenerator) { + this.raise(key2.start, "Constructor can't be a generator"); + } + if (isAsync) { + this.raise(key2.start, "Constructor can't be an async method"); + } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key2.start, "Classes may not have a static property named prototype"); + } + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + if (method.kind === "get" && value.params.length !== 0) { + this.raiseRecoverable(value.start, "getter should have no params"); + } + if (method.kind === "set" && value.params.length !== 1) { + this.raiseRecoverable(value.start, "setter should have exactly one param"); + } + if (method.kind === "set" && value.params[0].type === "RestElement") { + this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); + } + return this.finishNode(method, "MethodDefinition"); +}; +pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + if (this.eat(types$1.eq)) { + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + return this.finishNode(field, "PropertyDefinition"); +}; +pp$8.parseClassStaticBlock = function(node2) { + node2.body = []; + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node2.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + return this.finishNode(node2, "StaticBlock"); +}; +pp$8.parseClassId = function(node2, isStatement) { + if (this.type === types$1.name) { + node2.id = this.parseIdent(); + if (isStatement) { + this.checkLValSimple(node2.id, BIND_LEXICAL, false); + } + } else { + if (isStatement === true) { + this.unexpected(); + } + node2.id = null; + } +}; +pp$8.parseClassSuper = function(node2) { + node2.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; +}; +pp$8.enterClassBody = function() { + var element = { declared: /* @__PURE__ */ Object.create(null), used: [] }; + this.privateNameStack.push(element); + return element.declared; +}; +pp$8.exitClassBody = function() { + var ref2 = this.privateNameStack.pop(); + var declared = ref2.declared; + var used = ref2.used; + if (!this.options.checkPrivateFields) { + return; + } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class"); + } + } + } +}; +function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") { + privateNameMap[name] = "true"; + return false; + } else if (!curr) { + privateNameMap[name] = next; + return false; + } else { + return true; + } +} +function checkKeyName(node2, name) { + var computed = node2.computed; + var key2 = node2.key; + return !computed && (key2.type === "Identifier" && key2.name === name || key2.type === "Literal" && key2.value === name); +} +pp$8.parseExportAllDeclaration = function(node2, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node2.exported = this.parseModuleExportName(); + this.checkExport(exports, node2.exported, this.lastTokStart); + } else { + node2.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { + this.unexpected(); + } + node2.source = this.parseExprAtom(); + if (this.options.ecmaVersion >= 16) { + node2.attributes = this.parseWithClause(); + } + this.semicolon(); + return this.finishNode(node2, "ExportAllDeclaration"); +}; +pp$8.parseExport = function(node2, exports) { + this.next(); + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node2, exports); + } + if (this.eat(types$1._default)) { + this.checkExport(exports, "default", this.lastTokStart); + node2.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node2, "ExportDefaultDeclaration"); + } + if (this.shouldParseExportStatement()) { + node2.declaration = this.parseExportDeclaration(node2); + if (node2.declaration.type === "VariableDeclaration") { + this.checkVariableExport(exports, node2.declaration.declarations); + } else { + this.checkExport(exports, node2.declaration.id, node2.declaration.id.start); + } + node2.specifiers = []; + node2.source = null; + } else { + node2.declaration = null; + node2.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { + this.unexpected(); + } + node2.source = this.parseExprAtom(); + if (this.options.ecmaVersion >= 16) { + node2.attributes = this.parseWithClause(); + } + } else { + for (var i = 0, list = node2.specifiers; i < list.length; i += 1) { + var spec = list[i]; + this.checkUnreserved(spec.local); + this.checkLocalExport(spec.local); + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + node2.source = null; + } + this.semicolon(); + } + return this.finishNode(node2, "ExportNamedDeclaration"); +}; +pp$8.parseExportDeclaration = function(node2) { + return this.parseStatement(null); +}; +pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { + this.next(); + } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID"); + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration; + } +}; +pp$8.checkExport = function(exports, name, pos) { + if (!exports) { + return; + } + if (typeof name !== "string") { + name = name.type === "Identifier" ? name.name : name.value; + } + if (hasOwn(exports, name)) { + this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); + } + exports[name] = true; +}; +pp$8.checkPatternExport = function(exports, pat) { + var type2 = pat.type; + if (type2 === "Identifier") { + this.checkExport(exports, pat, pat.start); + } else if (type2 === "ObjectPattern") { + for (var i = 0, list = pat.properties; i < list.length; i += 1) { + var prop = list[i]; + this.checkPatternExport(exports, prop); + } + } else if (type2 === "ArrayPattern") { + for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + if (elt) { + this.checkPatternExport(exports, elt); + } + } + } else if (type2 === "Property") { + this.checkPatternExport(exports, pat.value); + } else if (type2 === "AssignmentPattern") { + this.checkPatternExport(exports, pat.left); + } else if (type2 === "RestElement") { + this.checkPatternExport(exports, pat.argument); + } +}; +pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { + return; + } + for (var i = 0, list = decls; i < list.length; i += 1) { + var decl = list[i]; + this.checkPatternExport(exports, decl.id); + } +}; +pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction(); +}; +pp$8.parseExportSpecifier = function(exports) { + var node2 = this.startNode(); + node2.local = this.parseModuleExportName(); + node2.exported = this.eatContextual("as") ? this.parseModuleExportName() : node2.local; + this.checkExport( + exports, + node2.exported, + node2.exported.start + ); + return this.finishNode(node2, "ExportSpecifier"); +}; +pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes; +}; +pp$8.parseImport = function(node2) { + this.next(); + if (this.type === types$1.string) { + node2.specifiers = empty$1; + node2.source = this.parseExprAtom(); + } else { + node2.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node2.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + if (this.options.ecmaVersion >= 16) { + node2.attributes = this.parseWithClause(); + } + this.semicolon(); + return this.finishNode(node2, "ImportDeclaration"); +}; +pp$8.parseImportSpecifier = function() { + var node2 = this.startNode(); + node2.imported = this.parseModuleExportName(); + if (this.eatContextual("as")) { + node2.local = this.parseIdent(); + } else { + this.checkUnreserved(node2.imported); + node2.local = node2.imported; + } + this.checkLValSimple(node2.local, BIND_LEXICAL); + return this.finishNode(node2, "ImportSpecifier"); +}; +pp$8.parseImportDefaultSpecifier = function() { + var node2 = this.startNode(); + node2.local = this.parseIdent(); + this.checkLValSimple(node2.local, BIND_LEXICAL); + return this.finishNode(node2, "ImportDefaultSpecifier"); +}; +pp$8.parseImportNamespaceSpecifier = function() { + var node2 = this.startNode(); + this.next(); + this.expectContextual("as"); + node2.local = this.parseIdent(); + this.checkLValSimple(node2.local, BIND_LEXICAL); + return this.finishNode(node2, "ImportNamespaceSpecifier"); +}; +pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { + return nodes; + } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes; + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + nodes.push(this.parseImportSpecifier()); + } + return nodes; +}; +pp$8.parseWithClause = function() { + var nodes = []; + if (!this.eat(types$1._with)) { + return nodes; + } + this.expect(types$1.braceL); + var attributeKeys = {}; + var first = true; + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var attr = this.parseImportAttribute(); + var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value; + if (hasOwn(attributeKeys, keyName)) { + this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'"); + } + attributeKeys[keyName] = true; + nodes.push(attr); + } + return nodes; +}; +pp$8.parseImportAttribute = function() { + var node2 = this.startNode(); + node2.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); + this.expect(types$1.colon); + if (this.type !== types$1.string) { + this.unexpected(); + } + node2.value = this.parseExprAtom(); + return this.finishNode(node2, "ImportAttribute"); +}; +pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral; + } + return this.parseIdent(true); +}; +pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } +}; +pp$8.isDirectiveCandidate = function(statement) { + return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. + (this.input[statement.start] === '"' || this.input[statement.start] === "'"); +}; +var pp$7 = Parser2.prototype; +pp$7.toAssignable = function(node2, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node2) { + switch (node2.type) { + case "Identifier": + if (this.inAsync && node2.name === "await") { + this.raise(node2.start, "Cannot use 'await' as identifier inside an async function"); + } + break; + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break; + case "ObjectExpression": + node2.type = "ObjectPattern"; + if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + for (var i = 0, list = node2.properties; i < list.length; i += 1) { + var prop = list[i]; + this.toAssignable(prop, isBinding); + if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break; + case "Property": + if (node2.kind !== "init") { + this.raise(node2.key.start, "Object pattern can't contain getter or setter"); + } + this.toAssignable(node2.value, isBinding); + break; + case "ArrayExpression": + node2.type = "ArrayPattern"; + if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + this.toAssignableList(node2.elements, isBinding); + break; + case "SpreadElement": + node2.type = "RestElement"; + this.toAssignable(node2.argument, isBinding); + if (node2.argument.type === "AssignmentPattern") { + this.raise(node2.argument.start, "Rest elements cannot have a default value"); + } + break; + case "AssignmentExpression": + if (node2.operator !== "=") { + this.raise(node2.left.end, "Only '=' operator can be used for specifying default value."); + } + node2.type = "AssignmentPattern"; + delete node2.operator; + this.toAssignable(node2.left, isBinding); + break; + case "ParenthesizedExpression": + this.toAssignable(node2.expression, isBinding, refDestructuringErrors); + break; + case "ChainExpression": + this.raiseRecoverable(node2.start, "Optional chaining cannot appear in left-hand side"); + break; + case "MemberExpression": + if (!isBinding) { + break; + } + default: + this.raise(node2.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + return node2; +}; +pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { + this.toAssignable(elt, isBinding); + } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { + this.unexpected(last.argument.start); + } + } + return exprList; +}; +pp$7.parseSpread = function(refDestructuringErrors) { + var node2 = this.startNode(); + this.next(); + node2.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node2, "SpreadElement"); +}; +pp$7.parseRestBinding = function() { + var node2 = this.startNode(); + this.next(); + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { + this.unexpected(); + } + node2.argument = this.parseBindingAtom(); + return this.finishNode(node2, "RestElement"); +}; +pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node2 = this.startNode(); + this.next(); + node2.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node2, "ArrayPattern"); + case types$1.braceL: + return this.parseObj(true); + } + } + return this.parseIdent(); +}; +pp$7.parseBindingList = function(close2, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close2)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close2)) { + break; + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + this.expect(close2); + break; + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts; +}; +pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem; +}; +pp$7.parseBindingListItem = function(param) { + return param; +}; +pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { + return left; + } + var node2 = this.startNodeAt(startPos, startLoc); + node2.left = left; + node2.right = this.parseMaybeAssign(); + return this.finishNode(node2, "AssignmentPattern"); +}; +pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) bindingType = BIND_NONE; + var isBind = bindingType !== BIND_NONE; + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { + this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); + } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") { + this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); + } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) { + this.raiseRecoverable(expr.start, "Argument name clash"); + } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { + this.declareName(expr.name, bindingType, expr.start); + } + } + break; + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break; + case "MemberExpression": + if (isBind) { + this.raiseRecoverable(expr.start, "Binding member expression"); + } + break; + case "ParenthesizedExpression": + if (isBind) { + this.raiseRecoverable(expr.start, "Binding parenthesized expression"); + } + return this.checkLValSimple(expr.expression, bindingType, checkClashes); + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } +}; +pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) bindingType = BIND_NONE; + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break; + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + if (elem) { + this.checkLValInnerPattern(elem, bindingType, checkClashes); + } + } + break; + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } +}; +pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) bindingType = BIND_NONE; + switch (expr.type) { + case "Property": + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break; + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break; + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break; + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } +}; +var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; +}; +var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function(p) { + return p.tryReadTemplateToken(); + }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) +}; +var pp$6 = Parser2.prototype; +pp$6.initialContext = function() { + return [types.b_stat]; +}; +pp$6.curContext = function() { + return this.context[this.context.length - 1]; +}; +pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) { + return true; + } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) { + return !parent.isExpr; + } + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { + return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); + } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { + return true; + } + if (prevType === types$1.braceL) { + return parent === types.b_stat; + } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { + return false; + } + return !this.exprAllowed; +}; +pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") { + return context.generator; + } + } + return false; +}; +pp$6.updateContext = function(prevType) { + var update, type2 = this.type; + if (type2.keyword && prevType === types$1.dot) { + this.exprAllowed = false; + } else if (update = type2.updateContext) { + update.call(this, prevType); + } else { + this.exprAllowed = type2.beforeExpr; + } +}; +pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } +}; +types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return; + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; +}; +types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; +}; +types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; +}; +types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; +}; +types$1.incDec.updateContext = function() { +}; +types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) { + this.context.push(types.f_expr); + } else { + this.context.push(types.f_stat); + } + this.exprAllowed = false; +}; +types$1.colon.updateContext = function() { + if (this.curContext().token === "function") { + this.context.pop(); + } + this.exprAllowed = true; +}; +types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) { + this.context.pop(); + } else { + this.context.push(types.q_tmpl); + } + this.exprAllowed = false; +}; +types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index2 = this.context.length - 1; + if (this.context[index2] === types.f_expr) { + this.context[index2] = types.f_expr_gen; + } else { + this.context[index2] = types.f_gen; + } + } + this.exprAllowed = true; +}; +types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { + allowed = true; + } + } + this.exprAllowed = allowed; +}; +var pp$5 = Parser2.prototype; +pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { + return; + } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { + return; + } + var key2 = prop.key; + var name; + switch (key2.type) { + case "Identifier": + name = key2.name; + break; + case "Literal": + name = String(key2.value); + break; + default: + return; + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key2.start; + } + } else { + this.raiseRecoverable(key2.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return; + } + name = "$" + name; + var other2 = propHash[name]; + if (other2) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other2.init || other2.get || other2.set; + } else { + redefinition = other2.init || other2[kind]; + } + if (redefinition) { + this.raiseRecoverable(key2.start, "Redefinition of property"); + } + } else { + other2 = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other2[kind] = true; +}; +pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node2 = this.startNodeAt(startPos, startLoc); + node2.expressions = [expr]; + while (this.eat(types$1.comma)) { + node2.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); + } + return this.finishNode(node2, "SequenceExpression"); + } + return expr; +}; +pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { + return this.parseYield(forInit); + } else { + this.exprAllowed = false; + } + } + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors(); + ownDestructuringErrors = true; + } + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startPos, startLoc); + } + if (this.type.isAssign) { + var node2 = this.startNodeAt(startPos, startLoc); + node2.operator = this.value; + if (this.type === types$1.eq) { + left = this.toAssignable(left, false, refDestructuringErrors); + } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) { + refDestructuringErrors.shorthandAssign = -1; + } + if (this.type === types$1.eq) { + this.checkLValPattern(left); + } else { + this.checkLValSimple(left); + } + node2.left = left; + this.next(); + node2.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { + refDestructuringErrors.doubleProto = oldDoubleProto; + } + return this.finishNode(node2, "AssignmentExpression"); + } else { + if (ownDestructuringErrors) { + this.checkExpressionErrors(refDestructuringErrors, true); + } + } + if (oldParenAssign > -1) { + refDestructuringErrors.parenthesizedAssign = oldParenAssign; + } + if (oldTrailingComma > -1) { + refDestructuringErrors.trailingComma = oldTrailingComma; + } + return left; +}; +pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + if (this.eat(types$1.question)) { + var node2 = this.startNodeAt(startPos, startLoc); + node2.test = expr; + node2.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node2.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node2, "ConditionalExpression"); + } + return expr; +}; +pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit); +}; +pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node2 = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if (logical && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node2, leftStartPos, leftStartLoc, minPrec, forInit); + } + } + return left; +}; +pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { + this.raise(right.start, "Private identifier can only be left side of binary expression"); + } + var node2 = this.startNodeAt(startPos, startLoc); + node2.left = left; + node2.operator = op; + node2.right = right; + return this.finishNode(node2, logical ? "LogicalExpression" : "BinaryExpression"); +}; +pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node2 = this.startNode(), update = this.type === types$1.incDec; + node2.operator = this.value; + node2.prefix = true; + this.next(); + node2.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { + this.checkLValSimple(node2.argument); + } else if (this.strict && node2.operator === "delete" && isLocalVariableAccess(node2.argument)) { + this.raiseRecoverable(node2.start, "Deleting local variable in strict mode"); + } else if (node2.operator === "delete" && isPrivateFieldAccess(node2.argument)) { + this.raiseRecoverable(node2.start, "Private fields can not be deleted"); + } else { + sawUnary = true; + } + expr = this.finishNode(node2, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { + this.unexpected(); + } + expr = this.parsePrivateIdent(); + if (this.type !== types$1._in) { + this.unexpected(); + } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$12 = this.startNodeAt(startPos, startLoc); + node$12.operator = this.value; + node$12.prefix = false; + node$12.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$12, "UpdateExpression"); + } + } + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) { + this.unexpected(this.lastTokStart); + } else { + return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false); + } + } else { + return expr; + } +}; +function isLocalVariableAccess(node2) { + return node2.type === "Identifier" || node2.type === "ParenthesizedExpression" && isLocalVariableAccess(node2.expression); +} +function isPrivateFieldAccess(node2) { + return node2.type === "MemberExpression" && node2.property.type === "PrivateIdentifier" || node2.type === "ChainExpression" && isPrivateFieldAccess(node2.expression) || node2.type === "ParenthesizedExpression" && isPrivateFieldAccess(node2.expression); +} +pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { + return expr; + } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { + refDestructuringErrors.parenthesizedAssign = -1; + } + if (refDestructuringErrors.parenthesizedBind >= result.start) { + refDestructuringErrors.parenthesizedBind = -1; + } + if (refDestructuringErrors.trailingComma >= result.start) { + refDestructuringErrors.trailingComma = -1; + } + } + return result; +}; +pp$5.parseSubscripts = function(base2, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base2.type === "Identifier" && base2.name === "async" && this.lastTokEnd === base2.end && !this.canInsertSemicolon() && base2.end - base2.start === 5 && this.potentialArrowAt === base2.start; + var optionalChained = false; + while (true) { + var element = this.parseSubscript(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + if (element.optional) { + optionalChained = true; + } + if (element === base2 || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element; + } + base2 = element; + } +}; +pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow); +}; +pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit); +}; +pp$5.parseSubscript = function(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { + this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); + } + var computed = this.eat(types$1.bracketL); + if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) { + var node2 = this.startNodeAt(startPos, startLoc); + node2.object = base2; + if (computed) { + node2.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base2.type !== "Super") { + node2.property = this.parsePrivateIdent(); + } else { + node2.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node2.computed = !!computed; + if (optionalSupported) { + node2.optional = optional; + } + base2 = this.finishNode(node2, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) { + this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); + } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit); + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$12 = this.startNodeAt(startPos, startLoc); + node$12.callee = base2; + node$12.arguments = exprList; + if (optionalSupported) { + node$12.optional = optional; + } + base2 = this.finishNode(node$12, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base2; + node$2.quasi = this.parseTemplate({ isTagged: true }); + base2 = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base2; +}; +pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + if (this.type === types$1.slash) { + this.readRegexp(); + } + var node2, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) { + this.raise(this.start, "'super' keyword outside a method"); + } + node2 = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) { + this.raise(node2.start, "super() call outside constructor of a subclass"); + } + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { + this.unexpected(); + } + return this.finishNode(node2, "Super"); + case types$1._this: + node2 = this.startNode(); + this.next(); + return this.finishNode(node2, "ThisExpression"); + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit); + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit); + } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { + this.unexpected(); + } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit); + } + } + return id; + case types$1.regexp: + var value = this.value; + node2 = this.parseLiteral(value.value); + node2.regex = { pattern: value.pattern, flags: value.flags }; + return node2; + case types$1.num: + case types$1.string: + return this.parseLiteral(this.value); + case types$1._null: + case types$1._true: + case types$1._false: + node2 = this.startNode(); + node2.value = this.type === types$1._null ? null : this.type === types$1._true; + node2.raw = this.type.keyword; + this.next(); + return this.finishNode(node2, "Literal"); + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { + refDestructuringErrors.parenthesizedAssign = start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = start; + } + } + return expr; + case types$1.bracketL: + node2 = this.startNode(); + this.next(); + node2.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node2, "ArrayExpression"); + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors); + case types$1._function: + node2 = this.startNode(); + this.next(); + return this.parseFunction(node2, 0); + case types$1._class: + return this.parseClass(this.startNode(), false); + case types$1._new: + return this.parseNew(); + case types$1.backQuote: + return this.parseTemplate(); + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew); + } else { + return this.unexpected(); + } + default: + return this.parseExprAtomDefault(); + } +}; +pp$5.parseExprAtomDefault = function() { + this.unexpected(); +}; +pp$5.parseExprImport = function(forNew) { + var node2 = this.startNode(); + if (this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword import"); + } + this.next(); + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node2); + } else if (this.type === types$1.dot) { + var meta = this.startNodeAt(node2.start, node2.loc && node2.loc.start); + meta.name = "import"; + node2.meta = this.finishNode(meta, "Identifier"); + return this.parseImportMeta(node2); + } else { + this.unexpected(); + } +}; +pp$5.parseDynamicImport = function(node2) { + this.next(); + node2.source = this.parseMaybeAssign(); + if (this.options.ecmaVersion >= 16) { + if (!this.eat(types$1.parenR)) { + this.expect(types$1.comma); + if (!this.afterTrailingComma(types$1.parenR)) { + node2.options = this.parseMaybeAssign(); + if (!this.eat(types$1.parenR)) { + this.expect(types$1.comma); + if (!this.afterTrailingComma(types$1.parenR)) { + this.unexpected(); + } + } + } else { + node2.options = null; + } + } else { + node2.options = null; + } + } else { + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + } + return this.finishNode(node2, "ImportExpression"); +}; +pp$5.parseImportMeta = function(node2) { + this.next(); + var containsEsc = this.containsEsc; + node2.property = this.parseIdent(true); + if (node2.property.name !== "meta") { + this.raiseRecoverable(node2.property.start, "The only valid meta property for import is 'import.meta'"); + } + if (containsEsc) { + this.raiseRecoverable(node2.start, "'import.meta' must not contain escaped characters"); + } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { + this.raiseRecoverable(node2.start, "Cannot use 'import.meta' outside a module"); + } + return this.finishNode(node2, "MetaProperty"); +}; +pp$5.parseLiteral = function(value) { + var node2 = this.startNode(); + node2.value = value; + node2.raw = this.input.slice(this.start, this.end); + if (node2.raw.charCodeAt(node2.raw.length - 1) === 110) { + node2.bigint = node2.raw.slice(0, -1).replace(/_/g, ""); + } + this.next(); + return this.finishNode(node2, "Literal"); +}; +pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val; +}; +pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon(); +}; +pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break; + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break; + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit); + } + if (!exprList.length || lastIsComma) { + this.unexpected(this.lastTokStart); + } + if (spreadStart) { + this.unexpected(spreadStart); + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression"); + } else { + return val; + } +}; +pp$5.parseParenItem = function(item) { + return item; +}; +pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit); +}; +var empty = []; +pp$5.parseNew = function() { + if (this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword new"); + } + var node2 = this.startNode(); + this.next(); + if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { + var meta = this.startNodeAt(node2.start, node2.loc && node2.loc.start); + meta.name = "new"; + node2.meta = this.finishNode(meta, "Identifier"); + this.next(); + var containsEsc = this.containsEsc; + node2.property = this.parseIdent(true); + if (node2.property.name !== "target") { + this.raiseRecoverable(node2.property.start, "The only valid meta property for new is 'new.target'"); + } + if (containsEsc) { + this.raiseRecoverable(node2.start, "'new.target' must not contain escaped characters"); + } + if (!this.allowNewDotTarget) { + this.raiseRecoverable(node2.start, "'new.target' can only be used in functions and class static block"); + } + return this.finishNode(node2, "MetaProperty"); + } + var startPos = this.start, startLoc = this.startLoc; + node2.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { + node2.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); + } else { + node2.arguments = empty; + } + return this.finishNode(node2, "NewExpression"); +}; +pp$5.parseTemplateElement = function(ref2) { + var isTagged = ref2.isTagged; + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value.replace(/\r\n?/g, "\n"), + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement"); +}; +pp$5.parseTemplate = function(ref2) { + if (ref2 === void 0) ref2 = {}; + var isTagged = ref2.isTagged; + if (isTagged === void 0) isTagged = false; + var node2 = this.startNode(); + this.next(); + node2.expressions = []; + var curElt = this.parseTemplateElement({ isTagged }); + node2.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { + this.raise(this.pos, "Unterminated template literal"); + } + this.expect(types$1.dollarBraceL); + node2.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node2.quasis.push(curElt = this.parseTemplateElement({ isTagged })); + } + this.next(); + return this.finishNode(node2, "TemplateLiteral"); +}; +pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); +}; +pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node2 = this.startNode(), first = true, propHash = {}; + node2.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { + this.checkPropClash(prop, propHash, refDestructuringErrors); + } + node2.properties.push(prop); + } + return this.finishNode(node2, isPattern ? "ObjectPattern" : "ObjectExpression"); +}; +pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement"); + } + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + return this.finishNode(prop, "SpreadElement"); + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) { + isGenerator = this.eat(types$1.star); + } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property"); +}; +pp$5.parseGetterSetter = function(prop) { + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") { + this.raiseRecoverable(start, "getter should have no params"); + } else { + this.raiseRecoverable(start, "setter should have exactly one param"); + } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { + this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); + } + } +}; +pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) { + this.unexpected(); + } + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { + this.unexpected(); + } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { + this.unexpected(); + } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { + this.unexpected(); + } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) { + this.awaitIdentPos = startPos; + } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) { + refDestructuringErrors.shorthandAssign = this.start; + } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { + this.unexpected(); + } +}; +pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key; + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); +}; +pp$5.initFunction = function(node2) { + node2.id = null; + if (this.options.ecmaVersion >= 6) { + node2.generator = node2.expression = false; + } + if (this.options.ecmaVersion >= 8) { + node2.async = false; + } +}; +pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node2 = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.initFunction(node2); + if (this.options.ecmaVersion >= 6) { + node2.generator = isGenerator; + } + if (this.options.ecmaVersion >= 8) { + node2.async = !!isAsync; + } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node2.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + this.expect(types$1.parenL); + node2.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node2, false, true, false); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node2, "FunctionExpression"); +}; +pp$5.parseArrowExpression = function(node2, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node2); + if (this.options.ecmaVersion >= 8) { + node2.async = !!isAsync; + } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + node2.params = this.toAssignableList(params, true); + this.parseFunctionBody(node2, true, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node2, "ArrowFunctionExpression"); +}; +pp$5.parseFunctionBody = function(node2, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + if (isExpression) { + node2.body = this.parseMaybeAssign(forInit); + node2.expression = true; + this.checkParams(node2, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node2.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + if (useStrict && nonSimple) { + this.raiseRecoverable(node2.start, "Illegal 'use strict' directive in function with non-simple parameter list"); + } + } + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { + this.strict = true; + } + this.checkParams(node2, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node2.params)); + if (this.strict && node2.id) { + this.checkLValSimple(node2.id, BIND_OUTSIDE); + } + node2.body = this.parseBlock(false, void 0, useStrict && !oldStrict); + node2.expression = false; + this.adaptDirectivePrologue(node2.body.body); + this.labels = oldLabels; + } + this.exitScope(); +}; +pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) { + var param = list[i]; + if (param.type !== "Identifier") { + return false; + } + } + return true; +}; +pp$5.checkParams = function(node2, allowDuplicates) { + var nameHash = /* @__PURE__ */ Object.create(null); + for (var i = 0, list = node2.params; i < list.length; i += 1) { + var param = list[i]; + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } +}; +pp$5.parseExprList = function(close2, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close2)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close2)) { + break; + } + } else { + first = false; + } + var elt = void 0; + if (allowEmpty && this.type === types$1.comma) { + elt = null; + } else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts; +}; +pp$5.checkUnreserved = function(ref2) { + var start = ref2.start; + var end = ref2.end; + var name = ref2.name; + if (this.inGenerator && name === "yield") { + this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); + } + if (this.inAsync && name === "await") { + this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); + } + if (this.currentThisScope().inClassFieldInit && name === "arguments") { + this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); + } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { + this.raise(start, "Cannot use " + name + " in class static initialization block"); + } + if (this.keywords.test(name)) { + this.raise(start, "Unexpected keyword '" + name + "'"); + } + if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { + return; + } + var re2 = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re2.test(name)) { + if (!this.inAsync && name === "await") { + this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); + } + this.raiseRecoverable(start, "The keyword '" + name + "' is reserved"); + } +}; +pp$5.parseIdent = function(liberal) { + var node2 = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node2, "Identifier"); + if (!liberal) { + this.checkUnreserved(node2); + if (node2.name === "await" && !this.awaitIdentPos) { + this.awaitIdentPos = node2.start; + } + } + return node2; +}; +pp$5.parseIdentNode = function() { + var node2 = this.startNode(); + if (this.type === types$1.name) { + node2.name = this.value; + } else if (this.type.keyword) { + node2.name = this.type.keyword; + if ((node2.name === "class" || node2.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + this.type = types$1.name; + } else { + this.unexpected(); + } + return node2; +}; +pp$5.parsePrivateIdent = function() { + var node2 = this.startNode(); + if (this.type === types$1.privateId) { + node2.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node2, "PrivateIdentifier"); + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node2.start, "Private field '#" + node2.name + "' must be declared in an enclosing class"); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node2); + } + } + return node2; +}; +pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { + this.yieldPos = this.start; + } + var node2 = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) { + node2.delegate = false; + node2.argument = null; + } else { + node2.delegate = this.eat(types$1.star); + node2.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node2, "YieldExpression"); +}; +pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { + this.awaitPos = this.start; + } + var node2 = this.startNode(); + this.next(); + node2.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node2, "AwaitExpression"); +}; +var pp$4 = Parser2.prototype; +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; + err.loc = loc; + err.raisedAt = this.pos; + throw err; +}; +pp$4.raiseRecoverable = pp$4.raise; +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart); + } +}; +var pp$3 = Parser2.prototype; +var Scope = function Scope2(flags) { + this.flags = flags; + this.var = []; + this.lexical = []; + this.functions = []; + this.inClassFieldInit = false; +}; +pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); +}; +pp$3.exitScope = function() { + this.scopeStack.pop(); +}; +pp$3.treatFunctionsAsVarInScope = function(scope) { + return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP; +}; +pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && scope.flags & SCOPE_TOP) { + delete this.undefinedExports[name]; + } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) { + redeclared = scope$2.lexical.indexOf(name) > -1; + } else { + redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; + } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break; + } + scope$3.var.push(name); + if (this.inModule && scope$3.flags & SCOPE_TOP) { + delete this.undefinedExports[name]; + } + if (scope$3.flags & SCOPE_VAR) { + break; + } + } + } + if (redeclared) { + this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared"); + } +}; +pp$3.checkLocalExport = function(id) { + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } +}; +pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1]; +}; +pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1; ; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { + return scope; + } + } +}; +pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1; ; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { + return scope; + } + } +}; +var Node$1 = function Node2(parser2, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser2.options.locations) { + this.loc = new SourceLocation(parser2, loc); + } + if (parser2.options.directSourceFile) { + this.sourceFile = parser2.options.directSourceFile; + } + if (parser2.options.ranges) { + this.range = [pos, 0]; + } +}; +var pp$2 = Parser2.prototype; +pp$2.startNode = function() { + return new Node$1(this, this.start, this.startLoc); +}; +pp$2.startNodeAt = function(pos, loc) { + return new Node$1(this, pos, loc); +}; +function finishNodeAt(node2, type2, pos, loc) { + node2.type = type2; + node2.end = pos; + if (this.options.locations) { + node2.loc.end = loc; + } + if (this.options.ranges) { + node2.range[1] = pos; + } + return node2; +} +pp$2.finishNode = function(node2, type2) { + return finishNodeAt.call(this, node2, type2, this.lastTokEnd, this.lastTokEndLoc); +}; +pp$2.finishNodeAt = function(node2, type2, pos, loc) { + return finishNodeAt.call(this, node2, type2, pos, loc); +}; +pp$2.copyNode = function(node2) { + var newNode = new Node$1(this, node2.start, this.startLoc); + for (var prop in node2) { + newNode[prop] = node2[prop]; + } + return newNode; +}; +var scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"; +var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; +var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; +var ecma11BinaryProperties = ecma10BinaryProperties; +var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; +var ecma13BinaryProperties = ecma12BinaryProperties; +var ecma14BinaryProperties = ecma13BinaryProperties; +var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties +}; +var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; +var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings +}; +var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; +var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; +var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; +var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; +var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; +var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; +var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode; +var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues +}; +var data = {}; +function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; +} +for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + var ecmaVersion = list[i]; + buildUnicodeData(ecmaVersion); +} +var pp$1 = Parser2.prototype; +var BranchID = function BranchID2(parent, base2) { + this.parent = parent; + this.base = base2 || this; +}; +BranchID.prototype.separatedFrom = function separatedFrom(alt) { + for (var self2 = this; self2; self2 = self2.parent) { + for (var other2 = alt; other2; other2 = other2.parent) { + if (self2.base === other2.base && self2 !== other2) { + return true; + } + } + } + return false; +}; +BranchID.prototype.sibling = function sibling() { + return new BranchID(this.parent, this.base); +}; +var RegExpValidationState = function RegExpValidationState2(parser2) { + this.parser = parser2; + this.validFlags = "gim" + (parser2.options.ecmaVersion >= 6 ? "uy" : "") + (parser2.options.ecmaVersion >= 9 ? "s" : "") + (parser2.options.ecmaVersion >= 13 ? "d" : "") + (parser2.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser2.options.ecmaVersion >= 14 ? 14 : parser2.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = /* @__PURE__ */ Object.create(null); + this.backReferenceNames = []; + this.branchID = null; +}; +RegExpValidationState.prototype.reset = function reset(start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } +}; +RegExpValidationState.prototype.raise = function raise(message) { + this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message); +}; +RegExpValidationState.prototype.at = function at(i, forceU) { + if (forceU === void 0) forceU = false; + var s = this.source; + var l = s.length; + if (i >= l) { + return -1; + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i + 1 >= l) { + return c; + } + var next = s.charCodeAt(i + 1); + return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c; +}; +RegExpValidationState.prototype.nextIndex = function nextIndex(i, forceU) { + if (forceU === void 0) forceU = false; + var s = this.source; + var l = s.length; + if (i >= l) { + return l; + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 56320 || next > 57343) { + return i + 1; + } + return i + 2; +}; +RegExpValidationState.prototype.current = function current(forceU) { + if (forceU === void 0) forceU = false; + return this.at(this.pos, forceU); +}; +RegExpValidationState.prototype.lookahead = function lookahead(forceU) { + if (forceU === void 0) forceU = false; + return this.at(this.nextIndex(this.pos, forceU), forceU); +}; +RegExpValidationState.prototype.advance = function advance(forceU) { + if (forceU === void 0) forceU = false; + this.pos = this.nextIndex(this.pos, forceU); +}; +RegExpValidationState.prototype.eat = function eat(ch, forceU) { + if (forceU === void 0) forceU = false; + if (this.current(forceU) === ch) { + this.advance(forceU); + return true; + } + return false; +}; +RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) { + if (forceU === void 0) forceU = false; + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + var current2 = this.at(pos, forceU); + if (current2 === -1 || current2 !== ch) { + return false; + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true; +}; +pp$1.validateRegExpFlags = function(state2) { + var validFlags = state2.validFlags; + var flags = state2.flags; + var u = false; + var v = false; + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state2.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state2.start, "Duplicate regular expression flag"); + } + if (flag === "u") { + u = true; + } + if (flag === "v") { + v = true; + } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state2.start, "Invalid regular expression flag"); + } +}; +function hasProp(obj) { + for (var _ in obj) { + return true; + } + return false; +} +pp$1.validateRegExpPattern = function(state2) { + this.regexp_pattern(state2); + if (!state2.switchN && this.options.ecmaVersion >= 9 && hasProp(state2.groupNames)) { + state2.switchN = true; + this.regexp_pattern(state2); + } +}; +pp$1.regexp_pattern = function(state2) { + state2.pos = 0; + state2.lastIntValue = 0; + state2.lastStringValue = ""; + state2.lastAssertionIsQuantifiable = false; + state2.numCapturingParens = 0; + state2.maxBackReference = 0; + state2.groupNames = /* @__PURE__ */ Object.create(null); + state2.backReferenceNames.length = 0; + state2.branchID = null; + this.regexp_disjunction(state2); + if (state2.pos !== state2.source.length) { + if (state2.eat( + 41 + /* ) */ + )) { + state2.raise("Unmatched ')'"); + } + if (state2.eat( + 93 + /* ] */ + ) || state2.eat( + 125 + /* } */ + )) { + state2.raise("Lone quantifier brackets"); + } + } + if (state2.maxBackReference > state2.numCapturingParens) { + state2.raise("Invalid escape"); + } + for (var i = 0, list = state2.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + if (!state2.groupNames[name]) { + state2.raise("Invalid named capture referenced"); + } + } +}; +pp$1.regexp_disjunction = function(state2) { + var trackDisjunction = this.options.ecmaVersion >= 16; + if (trackDisjunction) { + state2.branchID = new BranchID(state2.branchID, null); + } + this.regexp_alternative(state2); + while (state2.eat( + 124 + /* | */ + )) { + if (trackDisjunction) { + state2.branchID = state2.branchID.sibling(); + } + this.regexp_alternative(state2); + } + if (trackDisjunction) { + state2.branchID = state2.branchID.parent; + } + if (this.regexp_eatQuantifier(state2, true)) { + state2.raise("Nothing to repeat"); + } + if (state2.eat( + 123 + /* { */ + )) { + state2.raise("Lone quantifier brackets"); + } +}; +pp$1.regexp_alternative = function(state2) { + while (state2.pos < state2.source.length && this.regexp_eatTerm(state2)) { + } +}; +pp$1.regexp_eatTerm = function(state2) { + if (this.regexp_eatAssertion(state2)) { + if (state2.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state2)) { + if (state2.switchU) { + state2.raise("Invalid quantifier"); + } + } + return true; + } + if (state2.switchU ? this.regexp_eatAtom(state2) : this.regexp_eatExtendedAtom(state2)) { + this.regexp_eatQuantifier(state2); + return true; + } + return false; +}; +pp$1.regexp_eatAssertion = function(state2) { + var start = state2.pos; + state2.lastAssertionIsQuantifiable = false; + if (state2.eat( + 94 + /* ^ */ + ) || state2.eat( + 36 + /* $ */ + )) { + return true; + } + if (state2.eat( + 92 + /* \ */ + )) { + if (state2.eat( + 66 + /* B */ + ) || state2.eat( + 98 + /* b */ + )) { + return true; + } + state2.pos = start; + } + if (state2.eat( + 40 + /* ( */ + ) && state2.eat( + 63 + /* ? */ + )) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state2.eat( + 60 + /* < */ + ); + } + if (state2.eat( + 61 + /* = */ + ) || state2.eat( + 33 + /* ! */ + )) { + this.regexp_disjunction(state2); + if (!state2.eat( + 41 + /* ) */ + )) { + state2.raise("Unterminated group"); + } + state2.lastAssertionIsQuantifiable = !lookbehind; + return true; + } + } + state2.pos = start; + return false; +}; +pp$1.regexp_eatQuantifier = function(state2, noError) { + if (noError === void 0) noError = false; + if (this.regexp_eatQuantifierPrefix(state2, noError)) { + state2.eat( + 63 + /* ? */ + ); + return true; + } + return false; +}; +pp$1.regexp_eatQuantifierPrefix = function(state2, noError) { + return state2.eat( + 42 + /* * */ + ) || state2.eat( + 43 + /* + */ + ) || state2.eat( + 63 + /* ? */ + ) || this.regexp_eatBracedQuantifier(state2, noError); +}; +pp$1.regexp_eatBracedQuantifier = function(state2, noError) { + var start = state2.pos; + if (state2.eat( + 123 + /* { */ + )) { + var min2 = 0, max2 = -1; + if (this.regexp_eatDecimalDigits(state2)) { + min2 = state2.lastIntValue; + if (state2.eat( + 44 + /* , */ + ) && this.regexp_eatDecimalDigits(state2)) { + max2 = state2.lastIntValue; + } + if (state2.eat( + 125 + /* } */ + )) { + if (max2 !== -1 && max2 < min2 && !noError) { + state2.raise("numbers out of order in {} quantifier"); + } + return true; + } + } + if (state2.switchU && !noError) { + state2.raise("Incomplete quantifier"); + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatAtom = function(state2) { + return this.regexp_eatPatternCharacters(state2) || state2.eat( + 46 + /* . */ + ) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2); +}; +pp$1.regexp_eatReverseSolidusAtomEscape = function(state2) { + var start = state2.pos; + if (state2.eat( + 92 + /* \ */ + )) { + if (this.regexp_eatAtomEscape(state2)) { + return true; + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatUncapturingGroup = function(state2) { + var start = state2.pos; + if (state2.eat( + 40 + /* ( */ + )) { + if (state2.eat( + 63 + /* ? */ + )) { + if (this.options.ecmaVersion >= 16) { + var addModifiers = this.regexp_eatModifiers(state2); + var hasHyphen = state2.eat( + 45 + /* - */ + ); + if (addModifiers || hasHyphen) { + for (var i = 0; i < addModifiers.length; i++) { + var modifier = addModifiers.charAt(i); + if (addModifiers.indexOf(modifier, i + 1) > -1) { + state2.raise("Duplicate regular expression modifiers"); + } + } + if (hasHyphen) { + var removeModifiers = this.regexp_eatModifiers(state2); + if (!addModifiers && !removeModifiers && state2.current() === 58) { + state2.raise("Invalid regular expression modifiers"); + } + for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) { + var modifier$1 = removeModifiers.charAt(i$1); + if (removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) { + state2.raise("Duplicate regular expression modifiers"); + } + } + } + } + } + if (state2.eat( + 58 + /* : */ + )) { + this.regexp_disjunction(state2); + if (state2.eat( + 41 + /* ) */ + )) { + return true; + } + state2.raise("Unterminated group"); + } + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatCapturingGroup = function(state2) { + if (state2.eat( + 40 + /* ( */ + )) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state2); + } else if (state2.current() === 63) { + state2.raise("Invalid group"); + } + this.regexp_disjunction(state2); + if (state2.eat( + 41 + /* ) */ + )) { + state2.numCapturingParens += 1; + return true; + } + state2.raise("Unterminated group"); + } + return false; +}; +pp$1.regexp_eatModifiers = function(state2) { + var modifiers = ""; + var ch = 0; + while ((ch = state2.current()) !== -1 && isRegularExpressionModifier(ch)) { + modifiers += codePointToString(ch); + state2.advance(); + } + return modifiers; +}; +function isRegularExpressionModifier(ch) { + return ch === 105 || ch === 109 || ch === 115; +} +pp$1.regexp_eatExtendedAtom = function(state2) { + return state2.eat( + 46 + /* . */ + ) || this.regexp_eatReverseSolidusAtomEscape(state2) || this.regexp_eatCharacterClass(state2) || this.regexp_eatUncapturingGroup(state2) || this.regexp_eatCapturingGroup(state2) || this.regexp_eatInvalidBracedQuantifier(state2) || this.regexp_eatExtendedPatternCharacter(state2); +}; +pp$1.regexp_eatInvalidBracedQuantifier = function(state2) { + if (this.regexp_eatBracedQuantifier(state2, true)) { + state2.raise("Nothing to repeat"); + } + return false; +}; +pp$1.regexp_eatSyntaxCharacter = function(state2) { + var ch = state2.current(); + if (isSyntaxCharacter(ch)) { + state2.lastIntValue = ch; + state2.advance(); + return true; + } + return false; +}; +function isSyntaxCharacter(ch) { + return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125; +} +pp$1.regexp_eatPatternCharacters = function(state2) { + var start = state2.pos; + var ch = 0; + while ((ch = state2.current()) !== -1 && !isSyntaxCharacter(ch)) { + state2.advance(); + } + return state2.pos !== start; +}; +pp$1.regexp_eatExtendedPatternCharacter = function(state2) { + var ch = state2.current(); + if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) { + state2.advance(); + return true; + } + return false; +}; +pp$1.regexp_groupSpecifier = function(state2) { + if (state2.eat( + 63 + /* ? */ + )) { + if (!this.regexp_eatGroupName(state2)) { + state2.raise("Invalid group"); + } + var trackDisjunction = this.options.ecmaVersion >= 16; + var known = state2.groupNames[state2.lastStringValue]; + if (known) { + if (trackDisjunction) { + for (var i = 0, list = known; i < list.length; i += 1) { + var altID = list[i]; + if (!altID.separatedFrom(state2.branchID)) { + state2.raise("Duplicate capture group name"); + } + } + } else { + state2.raise("Duplicate capture group name"); + } + } + if (trackDisjunction) { + (known || (state2.groupNames[state2.lastStringValue] = [])).push(state2.branchID); + } else { + state2.groupNames[state2.lastStringValue] = true; + } + } +}; +pp$1.regexp_eatGroupName = function(state2) { + state2.lastStringValue = ""; + if (state2.eat( + 60 + /* < */ + )) { + if (this.regexp_eatRegExpIdentifierName(state2) && state2.eat( + 62 + /* > */ + )) { + return true; + } + state2.raise("Invalid capture group name"); + } + return false; +}; +pp$1.regexp_eatRegExpIdentifierName = function(state2) { + state2.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state2)) { + state2.lastStringValue += codePointToString(state2.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state2)) { + state2.lastStringValue += codePointToString(state2.lastIntValue); + } + return true; + } + return false; +}; +pp$1.regexp_eatRegExpIdentifierStart = function(state2) { + var start = state2.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state2.current(forceU); + state2.advance(forceU); + if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) { + ch = state2.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state2.lastIntValue = ch; + return true; + } + state2.pos = start; + return false; +}; +function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 36 || ch === 95; +} +pp$1.regexp_eatRegExpIdentifierPart = function(state2) { + var start = state2.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state2.current(forceU); + state2.advance(forceU); + if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state2, forceU)) { + ch = state2.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state2.lastIntValue = ch; + return true; + } + state2.pos = start; + return false; +}; +function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205; +} +pp$1.regexp_eatAtomEscape = function(state2) { + if (this.regexp_eatBackReference(state2) || this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2) || state2.switchN && this.regexp_eatKGroupName(state2)) { + return true; + } + if (state2.switchU) { + if (state2.current() === 99) { + state2.raise("Invalid unicode escape"); + } + state2.raise("Invalid escape"); + } + return false; +}; +pp$1.regexp_eatBackReference = function(state2) { + var start = state2.pos; + if (this.regexp_eatDecimalEscape(state2)) { + var n = state2.lastIntValue; + if (state2.switchU) { + if (n > state2.maxBackReference) { + state2.maxBackReference = n; + } + return true; + } + if (n <= state2.numCapturingParens) { + return true; + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatKGroupName = function(state2) { + if (state2.eat( + 107 + /* k */ + )) { + if (this.regexp_eatGroupName(state2)) { + state2.backReferenceNames.push(state2.lastStringValue); + return true; + } + state2.raise("Invalid named reference"); + } + return false; +}; +pp$1.regexp_eatCharacterEscape = function(state2) { + return this.regexp_eatControlEscape(state2) || this.regexp_eatCControlLetter(state2) || this.regexp_eatZero(state2) || this.regexp_eatHexEscapeSequence(state2) || this.regexp_eatRegExpUnicodeEscapeSequence(state2, false) || !state2.switchU && this.regexp_eatLegacyOctalEscapeSequence(state2) || this.regexp_eatIdentityEscape(state2); +}; +pp$1.regexp_eatCControlLetter = function(state2) { + var start = state2.pos; + if (state2.eat( + 99 + /* c */ + )) { + if (this.regexp_eatControlLetter(state2)) { + return true; + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatZero = function(state2) { + if (state2.current() === 48 && !isDecimalDigit(state2.lookahead())) { + state2.lastIntValue = 0; + state2.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatControlEscape = function(state2) { + var ch = state2.current(); + if (ch === 116) { + state2.lastIntValue = 9; + state2.advance(); + return true; + } + if (ch === 110) { + state2.lastIntValue = 10; + state2.advance(); + return true; + } + if (ch === 118) { + state2.lastIntValue = 11; + state2.advance(); + return true; + } + if (ch === 102) { + state2.lastIntValue = 12; + state2.advance(); + return true; + } + if (ch === 114) { + state2.lastIntValue = 13; + state2.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatControlLetter = function(state2) { + var ch = state2.current(); + if (isControlLetter(ch)) { + state2.lastIntValue = ch % 32; + state2.advance(); + return true; + } + return false; +}; +function isControlLetter(ch) { + return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122; +} +pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state2, forceU) { + if (forceU === void 0) forceU = false; + var start = state2.pos; + var switchU = forceU || state2.switchU; + if (state2.eat( + 117 + /* u */ + )) { + if (this.regexp_eatFixedHexDigits(state2, 4)) { + var lead = state2.lastIntValue; + if (switchU && lead >= 55296 && lead <= 56319) { + var leadSurrogateEnd = state2.pos; + if (state2.eat( + 92 + /* \ */ + ) && state2.eat( + 117 + /* u */ + ) && this.regexp_eatFixedHexDigits(state2, 4)) { + var trail = state2.lastIntValue; + if (trail >= 56320 && trail <= 57343) { + state2.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536; + return true; + } + } + state2.pos = leadSurrogateEnd; + state2.lastIntValue = lead; + } + return true; + } + if (switchU && state2.eat( + 123 + /* { */ + ) && this.regexp_eatHexDigits(state2) && state2.eat( + 125 + /* } */ + ) && isValidUnicode(state2.lastIntValue)) { + return true; + } + if (switchU) { + state2.raise("Invalid unicode escape"); + } + state2.pos = start; + } + return false; +}; +function isValidUnicode(ch) { + return ch >= 0 && ch <= 1114111; +} +pp$1.regexp_eatIdentityEscape = function(state2) { + if (state2.switchU) { + if (this.regexp_eatSyntaxCharacter(state2)) { + return true; + } + if (state2.eat( + 47 + /* / */ + )) { + state2.lastIntValue = 47; + return true; + } + return false; + } + var ch = state2.current(); + if (ch !== 99 && (!state2.switchN || ch !== 107)) { + state2.lastIntValue = ch; + state2.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatDecimalEscape = function(state2) { + state2.lastIntValue = 0; + var ch = state2.current(); + if (ch >= 49 && ch <= 57) { + do { + state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48); + state2.advance(); + } while ((ch = state2.current()) >= 48 && ch <= 57); + return true; + } + return false; +}; +var CharSetNone = 0; +var CharSetOk = 1; +var CharSetString = 2; +pp$1.regexp_eatCharacterClassEscape = function(state2) { + var ch = state2.current(); + if (isCharacterClassEscape(ch)) { + state2.lastIntValue = -1; + state2.advance(); + return CharSetOk; + } + var negate = false; + if (state2.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) { + state2.lastIntValue = -1; + state2.advance(); + var result; + if (state2.eat( + 123 + /* { */ + ) && (result = this.regexp_eatUnicodePropertyValueExpression(state2)) && state2.eat( + 125 + /* } */ + )) { + if (negate && result === CharSetString) { + state2.raise("Invalid property name"); + } + return result; + } + state2.raise("Invalid property name"); + } + return CharSetNone; +}; +function isCharacterClassEscape(ch) { + return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87; +} +pp$1.regexp_eatUnicodePropertyValueExpression = function(state2) { + var start = state2.pos; + if (this.regexp_eatUnicodePropertyName(state2) && state2.eat( + 61 + /* = */ + )) { + var name = state2.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state2)) { + var value = state2.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state2, name, value); + return CharSetOk; + } + } + state2.pos = start; + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state2)) { + var nameOrValue = state2.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state2, nameOrValue); + } + return CharSetNone; +}; +pp$1.regexp_validateUnicodePropertyNameAndValue = function(state2, name, value) { + if (!hasOwn(state2.unicodeProperties.nonBinary, name)) { + state2.raise("Invalid property name"); + } + if (!state2.unicodeProperties.nonBinary[name].test(value)) { + state2.raise("Invalid property value"); + } +}; +pp$1.regexp_validateUnicodePropertyNameOrValue = function(state2, nameOrValue) { + if (state2.unicodeProperties.binary.test(nameOrValue)) { + return CharSetOk; + } + if (state2.switchV && state2.unicodeProperties.binaryOfStrings.test(nameOrValue)) { + return CharSetString; + } + state2.raise("Invalid property name"); +}; +pp$1.regexp_eatUnicodePropertyName = function(state2) { + var ch = 0; + state2.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state2.current())) { + state2.lastStringValue += codePointToString(ch); + state2.advance(); + } + return state2.lastStringValue !== ""; +}; +function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 95; +} +pp$1.regexp_eatUnicodePropertyValue = function(state2) { + var ch = 0; + state2.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state2.current())) { + state2.lastStringValue += codePointToString(ch); + state2.advance(); + } + return state2.lastStringValue !== ""; +}; +function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch); +} +pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state2) { + return this.regexp_eatUnicodePropertyValue(state2); +}; +pp$1.regexp_eatCharacterClass = function(state2) { + if (state2.eat( + 91 + /* [ */ + )) { + var negate = state2.eat( + 94 + /* ^ */ + ); + var result = this.regexp_classContents(state2); + if (!state2.eat( + 93 + /* ] */ + )) { + state2.raise("Unterminated character class"); + } + if (negate && result === CharSetString) { + state2.raise("Negated character class may contain strings"); + } + return true; + } + return false; +}; +pp$1.regexp_classContents = function(state2) { + if (state2.current() === 93) { + return CharSetOk; + } + if (state2.switchV) { + return this.regexp_classSetExpression(state2); + } + this.regexp_nonEmptyClassRanges(state2); + return CharSetOk; +}; +pp$1.regexp_nonEmptyClassRanges = function(state2) { + while (this.regexp_eatClassAtom(state2)) { + var left = state2.lastIntValue; + if (state2.eat( + 45 + /* - */ + ) && this.regexp_eatClassAtom(state2)) { + var right = state2.lastIntValue; + if (state2.switchU && (left === -1 || right === -1)) { + state2.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state2.raise("Range out of order in character class"); + } + } + } +}; +pp$1.regexp_eatClassAtom = function(state2) { + var start = state2.pos; + if (state2.eat( + 92 + /* \ */ + )) { + if (this.regexp_eatClassEscape(state2)) { + return true; + } + if (state2.switchU) { + var ch$1 = state2.current(); + if (ch$1 === 99 || isOctalDigit(ch$1)) { + state2.raise("Invalid class escape"); + } + state2.raise("Invalid escape"); + } + state2.pos = start; + } + var ch = state2.current(); + if (ch !== 93) { + state2.lastIntValue = ch; + state2.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatClassEscape = function(state2) { + var start = state2.pos; + if (state2.eat( + 98 + /* b */ + )) { + state2.lastIntValue = 8; + return true; + } + if (state2.switchU && state2.eat( + 45 + /* - */ + )) { + state2.lastIntValue = 45; + return true; + } + if (!state2.switchU && state2.eat( + 99 + /* c */ + )) { + if (this.regexp_eatClassControlLetter(state2)) { + return true; + } + state2.pos = start; + } + return this.regexp_eatCharacterClassEscape(state2) || this.regexp_eatCharacterEscape(state2); +}; +pp$1.regexp_classSetExpression = function(state2) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state2)) ; + else if (subResult = this.regexp_eatClassSetOperand(state2)) { + if (subResult === CharSetString) { + result = CharSetString; + } + var start = state2.pos; + while (state2.eatChars( + [38, 38] + /* && */ + )) { + if (state2.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state2))) { + if (subResult !== CharSetString) { + result = CharSetOk; + } + continue; + } + state2.raise("Invalid character in character class"); + } + if (start !== state2.pos) { + return result; + } + while (state2.eatChars( + [45, 45] + /* -- */ + )) { + if (this.regexp_eatClassSetOperand(state2)) { + continue; + } + state2.raise("Invalid character in character class"); + } + if (start !== state2.pos) { + return result; + } + } else { + state2.raise("Invalid character in character class"); + } + for (; ; ) { + if (this.regexp_eatClassSetRange(state2)) { + continue; + } + subResult = this.regexp_eatClassSetOperand(state2); + if (!subResult) { + return result; + } + if (subResult === CharSetString) { + result = CharSetString; + } + } +}; +pp$1.regexp_eatClassSetRange = function(state2) { + var start = state2.pos; + if (this.regexp_eatClassSetCharacter(state2)) { + var left = state2.lastIntValue; + if (state2.eat( + 45 + /* - */ + ) && this.regexp_eatClassSetCharacter(state2)) { + var right = state2.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state2.raise("Range out of order in character class"); + } + return true; + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatClassSetOperand = function(state2) { + if (this.regexp_eatClassSetCharacter(state2)) { + return CharSetOk; + } + return this.regexp_eatClassStringDisjunction(state2) || this.regexp_eatNestedClass(state2); +}; +pp$1.regexp_eatNestedClass = function(state2) { + var start = state2.pos; + if (state2.eat( + 91 + /* [ */ + )) { + var negate = state2.eat( + 94 + /* ^ */ + ); + var result = this.regexp_classContents(state2); + if (state2.eat( + 93 + /* ] */ + )) { + if (negate && result === CharSetString) { + state2.raise("Negated character class may contain strings"); + } + return result; + } + state2.pos = start; + } + if (state2.eat( + 92 + /* \ */ + )) { + var result$1 = this.regexp_eatCharacterClassEscape(state2); + if (result$1) { + return result$1; + } + state2.pos = start; + } + return null; +}; +pp$1.regexp_eatClassStringDisjunction = function(state2) { + var start = state2.pos; + if (state2.eatChars( + [92, 113] + /* \q */ + )) { + if (state2.eat( + 123 + /* { */ + )) { + var result = this.regexp_classStringDisjunctionContents(state2); + if (state2.eat( + 125 + /* } */ + )) { + return result; + } + } else { + state2.raise("Invalid escape"); + } + state2.pos = start; + } + return null; +}; +pp$1.regexp_classStringDisjunctionContents = function(state2) { + var result = this.regexp_classString(state2); + while (state2.eat( + 124 + /* | */ + )) { + if (this.regexp_classString(state2) === CharSetString) { + result = CharSetString; + } + } + return result; +}; +pp$1.regexp_classString = function(state2) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state2)) { + count++; + } + return count === 1 ? CharSetOk : CharSetString; +}; +pp$1.regexp_eatClassSetCharacter = function(state2) { + var start = state2.pos; + if (state2.eat( + 92 + /* \ */ + )) { + if (this.regexp_eatCharacterEscape(state2) || this.regexp_eatClassSetReservedPunctuator(state2)) { + return true; + } + if (state2.eat( + 98 + /* b */ + )) { + state2.lastIntValue = 8; + return true; + } + state2.pos = start; + return false; + } + var ch = state2.current(); + if (ch < 0 || ch === state2.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { + return false; + } + if (isClassSetSyntaxCharacter(ch)) { + return false; + } + state2.advance(); + state2.lastIntValue = ch; + return true; +}; +function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126; +} +function isClassSetSyntaxCharacter(ch) { + return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125; +} +pp$1.regexp_eatClassSetReservedPunctuator = function(state2) { + var ch = state2.current(); + if (isClassSetReservedPunctuator(ch)) { + state2.lastIntValue = ch; + state2.advance(); + return true; + } + return false; +}; +function isClassSetReservedPunctuator(ch) { + return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126; +} +pp$1.regexp_eatClassControlLetter = function(state2) { + var ch = state2.current(); + if (isDecimalDigit(ch) || ch === 95) { + state2.lastIntValue = ch % 32; + state2.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatHexEscapeSequence = function(state2) { + var start = state2.pos; + if (state2.eat( + 120 + /* x */ + )) { + if (this.regexp_eatFixedHexDigits(state2, 2)) { + return true; + } + if (state2.switchU) { + state2.raise("Invalid escape"); + } + state2.pos = start; + } + return false; +}; +pp$1.regexp_eatDecimalDigits = function(state2) { + var start = state2.pos; + var ch = 0; + state2.lastIntValue = 0; + while (isDecimalDigit(ch = state2.current())) { + state2.lastIntValue = 10 * state2.lastIntValue + (ch - 48); + state2.advance(); + } + return state2.pos !== start; +}; +function isDecimalDigit(ch) { + return ch >= 48 && ch <= 57; +} +pp$1.regexp_eatHexDigits = function(state2) { + var start = state2.pos; + var ch = 0; + state2.lastIntValue = 0; + while (isHexDigit(ch = state2.current())) { + state2.lastIntValue = 16 * state2.lastIntValue + hexToInt(ch); + state2.advance(); + } + return state2.pos !== start; +}; +function isHexDigit(ch) { + return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102; +} +function hexToInt(ch) { + if (ch >= 65 && ch <= 70) { + return 10 + (ch - 65); + } + if (ch >= 97 && ch <= 102) { + return 10 + (ch - 97); + } + return ch - 48; +} +pp$1.regexp_eatLegacyOctalEscapeSequence = function(state2) { + if (this.regexp_eatOctalDigit(state2)) { + var n1 = state2.lastIntValue; + if (this.regexp_eatOctalDigit(state2)) { + var n2 = state2.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state2)) { + state2.lastIntValue = n1 * 64 + n2 * 8 + state2.lastIntValue; + } else { + state2.lastIntValue = n1 * 8 + n2; + } + } else { + state2.lastIntValue = n1; + } + return true; + } + return false; +}; +pp$1.regexp_eatOctalDigit = function(state2) { + var ch = state2.current(); + if (isOctalDigit(ch)) { + state2.lastIntValue = ch - 48; + state2.advance(); + return true; + } + state2.lastIntValue = 0; + return false; +}; +function isOctalDigit(ch) { + return ch >= 48 && ch <= 55; +} +pp$1.regexp_eatFixedHexDigits = function(state2, length) { + var start = state2.pos; + state2.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state2.current(); + if (!isHexDigit(ch)) { + state2.pos = start; + return false; + } + state2.lastIntValue = 16 * state2.lastIntValue + hexToInt(ch); + state2.advance(); + } + return true; +}; +var Token = function Token2(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) { + this.loc = new SourceLocation(p, p.startLoc, p.endLoc); + } + if (p.options.ranges) { + this.range = [p.start, p.end]; + } +}; +var pp = Parser2.prototype; +pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); + } + if (this.options.onToken) { + this.options.onToken(new Token(this)); + } + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); +}; +pp.getToken = function() { + this.next(); + return new Token(this); +}; +if (typeof Symbol !== "undefined") { + pp[Symbol.iterator] = function() { + var this$1$1 = this; + return { + next: function() { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + }; + } + }; + }; +} +pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { + this.skipSpace(); + } + this.start = this.pos; + if (this.options.locations) { + this.startLoc = this.curPosition(); + } + if (this.pos >= this.input.length) { + return this.finishToken(types$1.eof); + } + if (curContext.override) { + return curContext.override(this); + } else { + this.readToken(this.fullCharCodeAtPos()); + } +}; +pp.readToken = function(code) { + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) { + return this.readWord(); + } + return this.getTokenFromCode(code); +}; +pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 55295 || code >= 56320) { + return code; + } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888; +}; +pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { + this.raise(this.pos - 2, "Unterminated comment"); + } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) { + this.options.onComment( + true, + this.input.slice(start + 2, end), + start, + this.pos, + startLoc, + this.curPosition() + ); + } +}; +pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) { + this.options.onComment( + false, + this.input.slice(start + startSkip, this.pos), + start, + this.pos, + startLoc, + this.curPosition() + ); + } +}; +pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: + case 160: + ++this.pos; + break; + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: + case 8232: + case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break; + case 47: + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: + this.skipBlockComment(); + break; + case 47: + this.skipLineComment(2); + break; + default: + break loop; + } + break; + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop; + } + } + } +}; +pp.finishToken = function(type2, val) { + this.end = this.pos; + if (this.options.locations) { + this.endLoc = this.curPosition(); + } + var prevType = this.type; + this.type = type2; + this.value = val; + this.updateContext(prevType); +}; +pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { + return this.readNumber(true); + } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { + this.pos += 3; + return this.finishToken(types$1.ellipsis); + } else { + ++this.pos; + return this.finishToken(types$1.dot); + } +}; +pp.readToken_slash = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { + ++this.pos; + return this.readRegexp(); + } + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.slash, 1); +}; +pp.readToken_mult_modulo_exp = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + if (next === 61) { + return this.finishOp(types$1.assign, size + 1); + } + return this.finishOp(tokentype, size); +}; +pp.readToken_pipe_amp = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { + return this.finishOp(types$1.assign, 3); + } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2); + } + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1); +}; +pp.readToken_caret = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.bitwiseXOR, 1); +}; +pp.readToken_plus_min = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken(); + } + return this.finishOp(types$1.incDec, 2); + } + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.plusMin, 1); +}; +pp.readToken_lt_gt = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { + return this.finishOp(types$1.assign, size + 1); + } + return this.finishOp(types$1.bitShift, size); + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { + this.skipLineComment(4); + this.skipSpace(); + return this.nextToken(); + } + if (next === 61) { + size = 2; + } + return this.finishOp(types$1.relational, size); +}; +pp.readToken_eq_excl = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { + return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2); + } + if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { + this.pos += 2; + return this.finishToken(types$1.arrow); + } + return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1); +}; +pp.readToken_question = function() { + var ecmaVersion = this.options.ecmaVersion; + if (ecmaVersion >= 11) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === 46) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 < 48 || next2 > 57) { + return this.finishOp(types$1.questionDot, 2); + } + } + if (next === 63) { + if (ecmaVersion >= 12) { + var next2$1 = this.input.charCodeAt(this.pos + 2); + if (next2$1 === 61) { + return this.finishOp(types$1.assign, 3); + } + } + return this.finishOp(types$1.coalesce, 2); + } + } + return this.finishOp(types$1.question, 1); +}; +pp.readToken_numberSign = function() { + var ecmaVersion = this.options.ecmaVersion; + var code = 35; + if (ecmaVersion >= 13) { + ++this.pos; + code = this.fullCharCodeAtPos(); + if (isIdentifierStart(code, true) || code === 92) { + return this.finishToken(types$1.privateId, this.readWord1()); + } + } + this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); +}; +pp.getTokenFromCode = function(code) { + switch (code) { + // The interpretation of a dot depends on whether it is followed + // by a digit or another two dots. + case 46: + return this.readToken_dot(); + // Punctuation tokens. + case 40: + ++this.pos; + return this.finishToken(types$1.parenL); + case 41: + ++this.pos; + return this.finishToken(types$1.parenR); + case 59: + ++this.pos; + return this.finishToken(types$1.semi); + case 44: + ++this.pos; + return this.finishToken(types$1.comma); + case 91: + ++this.pos; + return this.finishToken(types$1.bracketL); + case 93: + ++this.pos; + return this.finishToken(types$1.bracketR); + case 123: + ++this.pos; + return this.finishToken(types$1.braceL); + case 125: + ++this.pos; + return this.finishToken(types$1.braceR); + case 58: + ++this.pos; + return this.finishToken(types$1.colon); + case 96: + if (this.options.ecmaVersion < 6) { + break; + } + ++this.pos; + return this.finishToken(types$1.backQuote); + case 48: + var next = this.input.charCodeAt(this.pos + 1); + if (next === 120 || next === 88) { + return this.readRadixNumber(16); + } + if (this.options.ecmaVersion >= 6) { + if (next === 111 || next === 79) { + return this.readRadixNumber(8); + } + if (next === 98 || next === 66) { + return this.readRadixNumber(2); + } + } + // Anything else beginning with a digit is an integer, octal + // number, or float. + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return this.readNumber(false); + // Quotes produce strings. + case 34: + case 39: + return this.readString(code); + // Operators are parsed inline in tiny state machines. '=' (61) is + // often referred to. `finishOp` simply skips the amount of + // characters it is given as second argument, and returns a token + // of the type given by its first argument. + case 47: + return this.readToken_slash(); + case 37: + case 42: + return this.readToken_mult_modulo_exp(code); + case 124: + case 38: + return this.readToken_pipe_amp(code); + case 94: + return this.readToken_caret(); + case 43: + case 45: + return this.readToken_plus_min(code); + case 60: + case 62: + return this.readToken_lt_gt(code); + case 61: + case 33: + return this.readToken_eq_excl(code); + case 63: + return this.readToken_question(); + case 126: + return this.finishOp(types$1.prefix, 1); + case 35: + return this.readToken_numberSign(); + } + this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); +}; +pp.finishOp = function(type2, size) { + var str = this.input.slice(this.pos, this.pos + size); + this.pos += size; + return this.finishToken(type2, str); +}; +pp.readRegexp = function() { + var escaped2, inClass, start = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(start, "Unterminated regular expression"); + } + var ch = this.input.charAt(this.pos); + if (lineBreak.test(ch)) { + this.raise(start, "Unterminated regular expression"); + } + if (!escaped2) { + if (ch === "[") { + inClass = true; + } else if (ch === "]" && inClass) { + inClass = false; + } else if (ch === "/" && !inClass) { + break; + } + escaped2 = ch === "\\"; + } else { + escaped2 = false; + } + ++this.pos; + } + var pattern = this.input.slice(start, this.pos); + ++this.pos; + var flagsStart = this.pos; + var flags = this.readWord1(); + if (this.containsEsc) { + this.unexpected(flagsStart); + } + var state2 = this.regexpState || (this.regexpState = new RegExpValidationState(this)); + state2.reset(start, pattern, flags); + this.validateRegExpFlags(state2); + this.validateRegExpPattern(state2); + var value = null; + try { + value = new RegExp(pattern, flags); + } catch (e) { + } + return this.finishToken(types$1.regexp, { pattern, flags, value }); +}; +pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { + var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0; + var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; + var start = this.pos, total = 0, lastCode = 0; + for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) { + var code = this.input.charCodeAt(this.pos), val = void 0; + if (allowSeparators && code === 95) { + if (isLegacyOctalNumericLiteral) { + this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); + } + if (lastCode === 95) { + this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); + } + if (i === 0) { + this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); + } + lastCode = code; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (code >= 48 && code <= 57) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + break; + } + lastCode = code; + total = total * radix + val; + } + if (allowSeparators && lastCode === 95) { + this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); + } + if (this.pos === start || len != null && this.pos - start !== len) { + return null; + } + return total; +}; +function stringToNumber(str, isLegacyOctalNumericLiteral) { + if (isLegacyOctalNumericLiteral) { + return parseInt(str, 8); + } + return parseFloat(str.replace(/_/g, "")); +} +function stringToBigInt(str) { + if (typeof BigInt !== "function") { + return null; + } + return BigInt(str.replace(/_/g, "")); +} +pp.readRadixNumber = function(radix) { + var start = this.pos; + this.pos += 2; + var val = this.readInt(radix); + if (val == null) { + this.raise(this.start + 2, "Expected number in radix " + radix); + } + if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { + val = stringToBigInt(this.input.slice(start, this.pos)); + ++this.pos; + } else if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + return this.finishToken(types$1.num, val); +}; +pp.readNumber = function(startsWithDot) { + var start = this.pos; + if (!startsWithDot && this.readInt(10, void 0, true) === null) { + this.raise(start, "Invalid number"); + } + var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (octal && this.strict) { + this.raise(start, "Invalid number"); + } + var next = this.input.charCodeAt(this.pos); + if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) { + var val$1 = stringToBigInt(this.input.slice(start, this.pos)); + ++this.pos; + if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + return this.finishToken(types$1.num, val$1); + } + if (octal && /[89]/.test(this.input.slice(start, this.pos))) { + octal = false; + } + if (next === 46 && !octal) { + ++this.pos; + this.readInt(10); + next = this.input.charCodeAt(this.pos); + } + if ((next === 69 || next === 101) && !octal) { + next = this.input.charCodeAt(++this.pos); + if (next === 43 || next === 45) { + ++this.pos; + } + if (this.readInt(10) === null) { + this.raise(start, "Invalid number"); + } + } + if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + var val = stringToNumber(this.input.slice(start, this.pos), octal); + return this.finishToken(types$1.num, val); +}; +pp.readCodePoint = function() { + var ch = this.input.charCodeAt(this.pos), code; + if (ch === 123) { + if (this.options.ecmaVersion < 6) { + this.unexpected(); + } + var codePos = ++this.pos; + code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); + ++this.pos; + if (code > 1114111) { + this.invalidStringToken(codePos, "Code point out of bounds"); + } + } else { + code = this.readHexChar(4); + } + return code; +}; +pp.readString = function(quote2) { + var out = "", chunkStart = ++this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(this.start, "Unterminated string constant"); + } + var ch = this.input.charCodeAt(this.pos); + if (ch === quote2) { + break; + } + if (ch === 92) { + out += this.input.slice(chunkStart, this.pos); + out += this.readEscapedChar(false); + chunkStart = this.pos; + } else if (ch === 8232 || ch === 8233) { + if (this.options.ecmaVersion < 10) { + this.raise(this.start, "Unterminated string constant"); + } + ++this.pos; + if (this.options.locations) { + this.curLine++; + this.lineStart = this.pos; + } + } else { + if (isNewLine(ch)) { + this.raise(this.start, "Unterminated string constant"); + } + ++this.pos; + } + } + out += this.input.slice(chunkStart, this.pos++); + return this.finishToken(types$1.string, out); +}; +var INVALID_TEMPLATE_ESCAPE_ERROR = {}; +pp.tryReadTemplateToken = function() { + this.inTemplateElement = true; + try { + this.readTmplToken(); + } catch (err) { + if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { + this.readInvalidTemplateToken(); + } else { + throw err; + } + } + this.inTemplateElement = false; +}; +pp.invalidStringToken = function(position, message) { + if (this.inTemplateElement && this.options.ecmaVersion >= 9) { + throw INVALID_TEMPLATE_ESCAPE_ERROR; + } else { + this.raise(position, message); + } +}; +pp.readTmplToken = function() { + var out = "", chunkStart = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(this.start, "Unterminated template"); + } + var ch = this.input.charCodeAt(this.pos); + if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { + if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) { + if (ch === 36) { + this.pos += 2; + return this.finishToken(types$1.dollarBraceL); + } else { + ++this.pos; + return this.finishToken(types$1.backQuote); + } + } + out += this.input.slice(chunkStart, this.pos); + return this.finishToken(types$1.template, out); + } + if (ch === 92) { + out += this.input.slice(chunkStart, this.pos); + out += this.readEscapedChar(true); + chunkStart = this.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + ++this.pos; + switch (ch) { + case 13: + if (this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + } + case 10: + out += "\n"; + break; + default: + out += String.fromCharCode(ch); + break; + } + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + chunkStart = this.pos; + } else { + ++this.pos; + } + } +}; +pp.readInvalidTemplateToken = function() { + for (; this.pos < this.input.length; this.pos++) { + switch (this.input[this.pos]) { + case "\\": + ++this.pos; + break; + case "$": + if (this.input[this.pos + 1] !== "{") { + break; + } + // fall through + case "`": + return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)); + case "\r": + if (this.input[this.pos + 1] === "\n") { + ++this.pos; + } + // fall through + case "\n": + case "\u2028": + case "\u2029": + ++this.curLine; + this.lineStart = this.pos + 1; + break; + } + } + this.raise(this.start, "Unterminated template"); +}; +pp.readEscapedChar = function(inTemplate) { + var ch = this.input.charCodeAt(++this.pos); + ++this.pos; + switch (ch) { + case 110: + return "\n"; + // 'n' -> '\n' + case 114: + return "\r"; + // 'r' -> '\r' + case 120: + return String.fromCharCode(this.readHexChar(2)); + // 'x' + case 117: + return codePointToString(this.readCodePoint()); + // 'u' + case 116: + return " "; + // 't' -> '\t' + case 98: + return "\b"; + // 'b' -> '\b' + case 118: + return "\v"; + // 'v' -> '\u000b' + case 102: + return "\f"; + // 'f' -> '\f' + case 13: + if (this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + } + // '\r\n' + case 10: + if (this.options.locations) { + this.lineStart = this.pos; + ++this.curLine; + } + return ""; + case 56: + case 57: + if (this.strict) { + this.invalidStringToken( + this.pos - 1, + "Invalid escape sequence" + ); + } + if (inTemplate) { + var codePos = this.pos - 1; + this.invalidStringToken( + codePos, + "Invalid escape sequence in template string" + ); + } + default: + if (ch >= 48 && ch <= 55) { + var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; + var octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + this.pos += octalStr.length - 1; + ch = this.input.charCodeAt(this.pos); + if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { + this.invalidStringToken( + this.pos - 1 - octalStr.length, + inTemplate ? "Octal literal in template string" : "Octal literal in strict mode" + ); + } + return String.fromCharCode(octal); + } + if (isNewLine(ch)) { + if (this.options.locations) { + this.lineStart = this.pos; + ++this.curLine; + } + return ""; + } + return String.fromCharCode(ch); + } +}; +pp.readHexChar = function(len) { + var codePos = this.pos; + var n = this.readInt(16, len); + if (n === null) { + this.invalidStringToken(codePos, "Bad character escape sequence"); + } + return n; +}; +pp.readWord1 = function() { + this.containsEsc = false; + var word = "", first = true, chunkStart = this.pos; + var astral = this.options.ecmaVersion >= 6; + while (this.pos < this.input.length) { + var ch = this.fullCharCodeAtPos(); + if (isIdentifierChar(ch, astral)) { + this.pos += ch <= 65535 ? 1 : 2; + } else if (ch === 92) { + this.containsEsc = true; + word += this.input.slice(chunkStart, this.pos); + var escStart = this.pos; + if (this.input.charCodeAt(++this.pos) !== 117) { + this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); + } + ++this.pos; + var esc = this.readCodePoint(); + if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { + this.invalidStringToken(escStart, "Invalid Unicode escape"); + } + word += codePointToString(esc); + chunkStart = this.pos; + } else { + break; + } + first = false; + } + return word + this.input.slice(chunkStart, this.pos); +}; +pp.readWord = function() { + var word = this.readWord1(); + var type2 = types$1.name; + if (this.keywords.test(word)) { + type2 = keywords[word]; + } + return this.finishToken(type2, word); +}; +var version = "8.14.0"; +Parser2.acorn = { + Parser: Parser2, + version, + defaultOptions, + Position, + SourceLocation, + getLineInfo, + Node: Node$1, + TokenType, + tokTypes: types$1, + keywordTypes: keywords, + TokContext, + tokContexts: types, + isIdentifierChar, + isIdentifierStart, + Token, + isNewLine, + lineBreak, + lineBreakG, + nonASCIIwhitespace +}; +function parse$1(input, options2) { + return Parser2.parse(input, options2); +} +function ancestor(node2, visitors, baseVisitor, state2, override) { + var ancestors = []; + if (!baseVisitor) { + baseVisitor = base; + } + (function c(node3, st, override2) { + var type2 = override2 || node3.type; + var isNew = node3 !== ancestors[ancestors.length - 1]; + if (isNew) { + ancestors.push(node3); + } + baseVisitor[type2](node3, st, c); + if (visitors[type2]) { + visitors[type2](node3, st || ancestors, ancestors); + } + if (isNew) { + ancestors.pop(); + } + })(node2, state2, override); +} +function skipThrough(node2, st, c) { + c(node2, st); +} +function ignore(_node, _st, _c2) { +} +var base = {}; +base.Program = base.BlockStatement = base.StaticBlock = function(node2, st, c) { + for (var i = 0, list = node2.body; i < list.length; i += 1) { + var stmt = list[i]; + c(stmt, st, "Statement"); + } +}; +base.Statement = skipThrough; +base.EmptyStatement = ignore; +base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = function(node2, st, c) { + return c(node2.expression, st, "Expression"); +}; +base.IfStatement = function(node2, st, c) { + c(node2.test, st, "Expression"); + c(node2.consequent, st, "Statement"); + if (node2.alternate) { + c(node2.alternate, st, "Statement"); + } +}; +base.LabeledStatement = function(node2, st, c) { + return c(node2.body, st, "Statement"); +}; +base.BreakStatement = base.ContinueStatement = ignore; +base.WithStatement = function(node2, st, c) { + c(node2.object, st, "Expression"); + c(node2.body, st, "Statement"); +}; +base.SwitchStatement = function(node2, st, c) { + c(node2.discriminant, st, "Expression"); + for (var i = 0, list = node2.cases; i < list.length; i += 1) { + var cs = list[i]; + c(cs, st); + } +}; +base.SwitchCase = function(node2, st, c) { + if (node2.test) { + c(node2.test, st, "Expression"); + } + for (var i = 0, list = node2.consequent; i < list.length; i += 1) { + var cons = list[i]; + c(cons, st, "Statement"); + } +}; +base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function(node2, st, c) { + if (node2.argument) { + c(node2.argument, st, "Expression"); + } +}; +base.ThrowStatement = base.SpreadElement = function(node2, st, c) { + return c(node2.argument, st, "Expression"); +}; +base.TryStatement = function(node2, st, c) { + c(node2.block, st, "Statement"); + if (node2.handler) { + c(node2.handler, st); + } + if (node2.finalizer) { + c(node2.finalizer, st, "Statement"); + } +}; +base.CatchClause = function(node2, st, c) { + if (node2.param) { + c(node2.param, st, "Pattern"); + } + c(node2.body, st, "Statement"); +}; +base.WhileStatement = base.DoWhileStatement = function(node2, st, c) { + c(node2.test, st, "Expression"); + c(node2.body, st, "Statement"); +}; +base.ForStatement = function(node2, st, c) { + if (node2.init) { + c(node2.init, st, "ForInit"); + } + if (node2.test) { + c(node2.test, st, "Expression"); + } + if (node2.update) { + c(node2.update, st, "Expression"); + } + c(node2.body, st, "Statement"); +}; +base.ForInStatement = base.ForOfStatement = function(node2, st, c) { + c(node2.left, st, "ForInit"); + c(node2.right, st, "Expression"); + c(node2.body, st, "Statement"); +}; +base.ForInit = function(node2, st, c) { + if (node2.type === "VariableDeclaration") { + c(node2, st); + } else { + c(node2, st, "Expression"); + } +}; +base.DebuggerStatement = ignore; +base.FunctionDeclaration = function(node2, st, c) { + return c(node2, st, "Function"); +}; +base.VariableDeclaration = function(node2, st, c) { + for (var i = 0, list = node2.declarations; i < list.length; i += 1) { + var decl = list[i]; + c(decl, st); + } +}; +base.VariableDeclarator = function(node2, st, c) { + c(node2.id, st, "Pattern"); + if (node2.init) { + c(node2.init, st, "Expression"); + } +}; +base.Function = function(node2, st, c) { + if (node2.id) { + c(node2.id, st, "Pattern"); + } + for (var i = 0, list = node2.params; i < list.length; i += 1) { + var param = list[i]; + c(param, st, "Pattern"); + } + c(node2.body, st, node2.expression ? "Expression" : "Statement"); +}; +base.Pattern = function(node2, st, c) { + if (node2.type === "Identifier") { + c(node2, st, "VariablePattern"); + } else if (node2.type === "MemberExpression") { + c(node2, st, "MemberPattern"); + } else { + c(node2, st); + } +}; +base.VariablePattern = ignore; +base.MemberPattern = skipThrough; +base.RestElement = function(node2, st, c) { + return c(node2.argument, st, "Pattern"); +}; +base.ArrayPattern = function(node2, st, c) { + for (var i = 0, list = node2.elements; i < list.length; i += 1) { + var elt = list[i]; + if (elt) { + c(elt, st, "Pattern"); + } + } +}; +base.ObjectPattern = function(node2, st, c) { + for (var i = 0, list = node2.properties; i < list.length; i += 1) { + var prop = list[i]; + if (prop.type === "Property") { + if (prop.computed) { + c(prop.key, st, "Expression"); + } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } +}; +base.Expression = skipThrough; +base.ThisExpression = base.Super = base.MetaProperty = ignore; +base.ArrayExpression = function(node2, st, c) { + for (var i = 0, list = node2.elements; i < list.length; i += 1) { + var elt = list[i]; + if (elt) { + c(elt, st, "Expression"); + } + } +}; +base.ObjectExpression = function(node2, st, c) { + for (var i = 0, list = node2.properties; i < list.length; i += 1) { + var prop = list[i]; + c(prop, st); + } +}; +base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; +base.SequenceExpression = function(node2, st, c) { + for (var i = 0, list = node2.expressions; i < list.length; i += 1) { + var expr = list[i]; + c(expr, st, "Expression"); + } +}; +base.TemplateLiteral = function(node2, st, c) { + for (var i = 0, list = node2.quasis; i < list.length; i += 1) { + var quasi = list[i]; + c(quasi, st); + } + for (var i$1 = 0, list$1 = node2.expressions; i$1 < list$1.length; i$1 += 1) { + var expr = list$1[i$1]; + c(expr, st, "Expression"); + } +}; +base.TemplateElement = ignore; +base.UnaryExpression = base.UpdateExpression = function(node2, st, c) { + c(node2.argument, st, "Expression"); +}; +base.BinaryExpression = base.LogicalExpression = function(node2, st, c) { + c(node2.left, st, "Expression"); + c(node2.right, st, "Expression"); +}; +base.AssignmentExpression = base.AssignmentPattern = function(node2, st, c) { + c(node2.left, st, "Pattern"); + c(node2.right, st, "Expression"); +}; +base.ConditionalExpression = function(node2, st, c) { + c(node2.test, st, "Expression"); + c(node2.consequent, st, "Expression"); + c(node2.alternate, st, "Expression"); +}; +base.NewExpression = base.CallExpression = function(node2, st, c) { + c(node2.callee, st, "Expression"); + if (node2.arguments) { + for (var i = 0, list = node2.arguments; i < list.length; i += 1) { + var arg = list[i]; + c(arg, st, "Expression"); + } + } +}; +base.MemberExpression = function(node2, st, c) { + c(node2.object, st, "Expression"); + if (node2.computed) { + c(node2.property, st, "Expression"); + } +}; +base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function(node2, st, c) { + if (node2.declaration) { + c(node2.declaration, st, node2.type === "ExportNamedDeclaration" || node2.declaration.id ? "Statement" : "Expression"); + } + if (node2.source) { + c(node2.source, st, "Expression"); + } +}; +base.ExportAllDeclaration = function(node2, st, c) { + if (node2.exported) { + c(node2.exported, st); + } + c(node2.source, st, "Expression"); +}; +base.ImportDeclaration = function(node2, st, c) { + for (var i = 0, list = node2.specifiers; i < list.length; i += 1) { + var spec = list[i]; + c(spec, st); + } + c(node2.source, st, "Expression"); +}; +base.ImportExpression = function(node2, st, c) { + c(node2.source, st, "Expression"); +}; +base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; +base.TaggedTemplateExpression = function(node2, st, c) { + c(node2.tag, st, "Expression"); + c(node2.quasi, st, "Expression"); +}; +base.ClassDeclaration = base.ClassExpression = function(node2, st, c) { + return c(node2, st, "Class"); +}; +base.Class = function(node2, st, c) { + if (node2.id) { + c(node2.id, st, "Pattern"); + } + if (node2.superClass) { + c(node2.superClass, st, "Expression"); + } + c(node2.body, st); +}; +base.ClassBody = function(node2, st, c) { + for (var i = 0, list = node2.body; i < list.length; i += 1) { + var elt = list[i]; + c(elt, st); + } +}; +base.MethodDefinition = base.PropertyDefinition = base.Property = function(node2, st, c) { + if (node2.computed) { + c(node2.key, st, "Expression"); + } + if (node2.value) { + c(node2.value, st, "Expression"); + } +}; +const expectFnActions = { + "toHaveText": (text) => ["assertText", { text }], + "toContainText": (text) => ["assertText", { text, substring: true }], + "toBeChecked": () => ["assertChecked", { checked: true }], + "toBeVisible": () => ["assertVisible"], + "toHaveValue": (value) => ["assertValue", { value }], + "toBeEmpty": () => ["assertValue"], + "toMatchAriaSnapshot": (snapshot) => ["assertSnapshot", { snapshot }] +}; +const fnActions = { + "check": () => ["check"], + "click": (options2) => ["click", parseClickOptions(options2)], + "dblclick": (options2) => ["click", parseClickOptions({ ...options2, clickCount: 2 })], + "close": () => ["closePage"], + "fill": (text) => ["fill", { text }], + "goto": (url2) => ["navigate", { url: url2 }], + "newPage": () => ["openPage"], + "press": (shortcut) => ["press", parseShortcut(shortcut)], + "selectOption": (options2) => ["select", { options: typeof options2 === "string" ? [options2] : options2 }], + "uncheck": () => ["uncheck"], + "setInputFiles": (files) => ["setInputFiles", { files: typeof files === "string" ? [files] : files }], + "routeFromHAR": (har, options2) => ["routeFromHAR", { har, ...options2 }] +}; +const variableCallRegex = /^([a-zA-Z_$][\w$]*)\./; +function parseShortcut(shortcut) { + const parts = shortcut.split("+").map((s) => s.trim()); + return { + modifiers: fromKeyboardModifiers(parts.slice(0, parts.length - 1)), + key: parts[parts.length - 1] + }; +} +function cleanParams(params) { + if (!params) + return {}; + return Object.fromEntries(Object.entries(params).filter(([_, v]) => v !== void 0)); +} +function parseClickOptions(options2) { + const { modifiers, button, clickCount, position } = options2 ?? {}; + return { + button: button ?? "left", + modifiers: modifiers ? fromKeyboardModifiers(modifiers) : 0, + clickCount: clickCount ?? 1, + position: position ?? void 0 + }; +} +function indexToLineColumn(code, index2) { + const lines = code.split(/\r?\n/); + let line = 0; + let column = index2; + while (line < lines.length && column >= lines[line].length + 1) { + column -= lines[line].length + 1; + line++; + } + return { line: line + 1, column: column + 1 }; +} +class ParserError2 extends Error { + constructor(message, loc) { + super(`${message}${loc ? ` (${loc.start.line}:${loc.start.column})` : ""}`); + __publicField(this, "loc"); + this.loc = loc; + } +} +function parserError(message, loc) { + throw new ParserError2(message, loc ?? void 0); +} +const argsParser = (arg) => { + var _a2, _b2; + if (arg === null) + return arg; + if (arg.type === "SpreadElement") + parserError("Invalid spread element", arg.loc); + switch (arg.type) { + case "Literal": + return arg.value; + case "TemplateLiteral": + if (arg.quasis.length !== 1) + parserError("Invalid template literal", arg.loc); + const templateLiteral = arg.quasis[0].value.cooked ?? ""; + const indent = ((_b2 = (_a2 = templateLiteral.split(/\r?\n/).filter(Boolean)[0]) == null ? void 0 : _a2.match(/^( +)[^ ]/)) == null ? void 0 : _b2[1]) ?? ""; + return templateLiteral.replace(new RegExp(`^${indent}`, "gm"), "").trim(); + case "ArrayExpression": + return arg.elements.map(argsParser); + case "UnaryExpression": + if (arg.operator !== "-" || arg.argument.type !== "Literal" || typeof arg.argument.value !== "number") + parserError("Invalid number", arg.loc); + return -arg.argument.value; + case "ObjectExpression": + if (arg.properties.some((p) => p.type !== "Property" || p.key.type !== "Identifier" || !["Literal", "ObjectExpression", "ArrayExpression", "UnaryExpression"].includes(p.value.type))) + parserError("Invalid object property", arg.loc); + return Object.fromEntries(arg.properties.map((p) => p).map((p) => [p.key.name, argsParser(p.value)])); + } +}; +function parse3(code, file = "playwright-test") { + const ast = parse$1(code, { + ecmaVersion: 2020, + sourceType: "module", + locations: true + }); + function parseActionExpression(expr, pages) { + var _a2; + let pageAlias; + if (expr.type === "VariableDeclaration") { + if (expr.declarations.length !== 1 || expr.declarations[0].type !== "VariableDeclarator" || expr.declarations[0].id.type !== "Identifier" || ((_a2 = expr.declarations[0].init) == null ? void 0 : _a2.type) !== "AwaitExpression") + parserError("Invalid action expression", expr.loc); + pageAlias = expr.declarations[0].id.name; + expr = expr.declarations[0].init; + } + if (expr.type !== "AwaitExpression" || expr.argument.type !== "CallExpression" || expr.argument.callee.type !== "MemberExpression" || expr.argument.callee.property.type !== "Identifier") + parserError("Invalid action expression", expr.loc); + const actionFnName = expr.argument.callee.property.name; + let locator; + let expectAction = false; + let expectActionNegated = false; + if (pageAlias && actionFnName !== "newPage") + parserError("Invalid action expression, only newPage can be assigned variables", expr.argument.callee.loc); + if (!["newPage"].includes(actionFnName)) { + const [, variable] = variableCallRegex.exec(code.substring(expr.argument.start)) ?? []; + if (variable && !pages.has(variable)) + parserError("Invalid page variable", expr.argument.callee.loc); + if (variable) { + pageAlias = variable; + if (!["goto", "close", "routeFromHAR"].includes(actionFnName)) + locator = code.substring(expr.argument.callee.object.start + (variable.length + 1), expr.argument.callee.object.end); + } else if (code.startsWith("expect(", expr.argument.start)) { + let object = expr.argument.callee.object; + if (object.type === "MemberExpression" && object.property.type === "Identifier" && object.property.name === "not") { + if (actionFnName !== "toBeChecked") + parserError("Invalid expect expression, .not can only applied to toBeChecked", expr.argument.callee.loc); + expectActionNegated = true; + object = object.object; + } + if (object.type !== "CallExpression" || object.arguments.length !== 1 || object.arguments[0].type !== "CallExpression") + parserError("Invalid expect expression", expr.argument.callee.loc); + const expectArg = code.substring(object.arguments[0].start, object.arguments[0].end); + const [, variable2] = variableCallRegex.exec(expectArg) ?? []; + if (!variable2 || !pages.has(variable2)) + parserError("Invalid page variable", expr.argument.callee.loc); + pageAlias = variable2; + locator = expectArg.substring(variable2.length + 1); + expectAction = true; + } + } + let action; + const args = expr.argument.arguments.map(argsParser); + const selector = locator ? locatorOrSelectorAsSelector("javascript", locator, "data-testid") : void 0; + if (selector === "") + parserError("Invalid locator", expr.argument.callee.loc); + if (expectAction) { + if (!expectFnActions[actionFnName]) + parserError(`Invalid assertion ${actionFnName}`, expr.argument.callee.loc); + const [name, params] = expectFnActions[actionFnName](...args); + action = { name, selector, signals: [], ...cleanParams(params) }; + if (expectActionNegated) + action.checked = false; + } else { + if (!fnActions[actionFnName]) + parserError(`Invalid action ${actionFnName}`, expr.argument.callee.loc); + const [name, params] = fnActions[actionFnName](...args); + action = { name, selector, signals: [], ...cleanParams(params) }; + } + if (pageAlias) + pages.add(pageAlias); + return { + action, + frame: { pageAlias: pageAlias ?? "page", framePath: [] }, + startTime: 0, + location: { file, ...indexToLineColumn(code, expr.start) } + }; + } + let deviceName; + let harAction; + const contextOptions = {}; + function handleOptions(options2) { + let props = options2.properties; + const [first] = options2.properties; + if ((first == null ? void 0 : first.type) === "SpreadElement") { + const deviceProp = first; + if (deviceProp.argument.type !== "MemberExpression" || deviceProp.argument.object.type !== "Identifier" || deviceProp.argument.object.name !== "devices" || deviceProp.argument.property.type !== "Literal" || typeof deviceProp.argument.property.value !== "string") + parserError("Invalid device property", deviceProp.loc); + deviceName = deviceProp.argument.property.value; + props = props.slice(1); + } + const assertString = (v, loc) => { + if (typeof v !== "string") + parserError("Invalid string", loc); + }; + const assertEnum = (v, values, loc) => { + if (!values.includes(v)) + parserError(`Invalid enum value, expected one of ${values.join(", ")}`, loc); + }; + const assertStringArray = (v, loc) => { + if (!Array.isArray(v) || !v.every((e) => typeof e === "string")) + parserError("Invalid string array", loc); + }; + const assertObjectWithRequiredNumberProperties = (v, props2, loc) => { + if (typeof v !== "object" || Object.keys(v).length !== props2.length || !props2.every((p) => typeof v[p] === "number")) + parserError(`Invalid object with required number properties, expected ${props2.join(", ")}`, loc); + }; + const propValidators = { + colorScheme: (v, loc) => assertEnum(v, ["dark", "light", "no-preference"], loc), + locale: assertString, + timezoneId: assertString, + geolocation: (v, loc) => assertObjectWithRequiredNumberProperties(v, ["latitude", "longitude"], loc), + viewport: (v, loc) => assertObjectWithRequiredNumberProperties(v, ["width", "height"], loc), + permissions: assertStringArray, + serviceWorkers: (v, loc) => assertEnum(v, ["allow", "block"], loc), + storageState: assertString + }; + for (const prop of props) { + if (prop.type !== "Property" || prop.key.type !== "Identifier" || !Object.keys(propValidators).includes(prop.key.name)) + parserError("Invalid context option", prop.loc); + const propKey = prop.key.name; + const propValidator = propValidators[propKey]; + if (!propValidator) + parserError(`Invalid context option ${prop.key.name}`, prop.loc); + const value = argsParser(prop.value); + propValidator(value, prop.loc ?? void 0); + contextOptions[propKey] = value; + } + } + const tests = []; + ancestor(ast, { + CallExpression({ callee, arguments: args }, _, ancestors) { + var _a2, _b2; + if (ancestors.length !== 3 || ((_a2 = ancestors[0]) == null ? void 0 : _a2.type) !== "Program" || ((_b2 = ancestors[1]) == null ? void 0 : _b2.type) !== "ExpressionStatement") + return; + if (callee.type === "MemberExpression" && callee.object.type === "Identifier" && callee.object.name === "test" && callee.property.type === "Identifier" && callee.property.name === "use" && args.length === 1 && args[0].type === "ObjectExpression") { + handleOptions(args[0]); + return; + } + if (args.length !== 2) + parserError("Invalid call expression", callee.loc); + const [title, fn] = args; + if (callee.type !== "Identifier" || callee.name !== "test") + parserError("Invalid call expression", callee.loc); + if (title.type !== "Literal" || typeof title.value !== "string") + parserError("Invalid test title", title.loc); + if (fn.type !== "ArrowFunctionExpression" || fn.params.length !== 1 || fn.params[0].type !== "ObjectPattern" || fn.params[0].properties.some((p) => p.type !== "Property" || p.key.type !== "Identifier" || p.value.type !== "Identifier" || !["page", "context"].includes(p.key.name))) + parserError("Invalid test function", fn.loc); + const actions = []; + actions.push({ + action: { name: "openPage", signals: [], url: "" }, + frame: { pageAlias: "page", framePath: [] }, + location: { file, ...indexToLineColumn(code, fn.start) }, + startTime: 0 + }); + if (fn.body.type !== "BlockStatement" || !fn.body.body.every((e) => e.type === "ExpressionStatement" && e.expression.type === "AwaitExpression" || e.type === "VariableDeclaration")) + parserError("Invalid test function body", fn.body.loc); + const stmts = fn.body.body; + const pages = /* @__PURE__ */ new Set(["page"]); + for (const stmt of stmts) { + const actionExpr = stmt.type === "VariableDeclaration" ? stmt : stmt.expression; + const candidateAction = parseActionExpression(actionExpr, pages); + if (candidateAction.action.name === "routeFromHAR") { + if (!(actions.length === 0 || actions.length === 1 && actions[0].action.name === "openPage")) + parserError("routeFromHAR must be the first action", actionExpr.loc); + if (harAction) + parserError("Only one routeFromHAR is allowed", actionExpr.loc); + harAction = candidateAction.action; + continue; + } + actions.push(candidateAction); + } + if (contextOptions && harAction) { + contextOptions.recordHar = { + path: harAction.har, + content: harAction.updateContent, + mode: harAction.updateMode, + urlGlob: harAction.url + }; + } + tests.push({ + title: title.value, + actions, + options: deviceName || harAction || contextOptions && Object.keys(contextOptions).length > 0 ? { + deviceName, + contextOptions + } : void 0, + location: { file, ...indexToLineColumn(code, callee.start) } + }); + } + }); + return tests; +} +class CrxRecorderApp extends eventsExports.EventEmitter { + constructor(crx2, recorder) { + super(); + __publicField(this, "wsEndpointForTest"); + __publicField(this, "_crx"); + __publicField(this, "_recorder"); + __publicField(this, "_filename"); + __publicField(this, "_sources"); + __publicField(this, "_mode", "none"); + __publicField(this, "_window"); + __publicField(this, "_editedCode"); + __publicField(this, "_recordedActions", []); + __publicField(this, "_playInIncognito", false); + __publicField(this, "_currentCursorPosition"); + this._crx = crx2; + this._recorder = recorder; + this._crx.player.on("start", () => { + this._recorder.clearErrors(); + this.resetCallLogs().catch(() => { + }); + }); + } + async open(options2) { + var _a2, _b2; + const mode = (options2 == null ? void 0 : options2.mode) ?? "none"; + const language = (options2 == null ? void 0 : options2.language) ?? "playwright-test"; + if (this._window) + await this._window.close(); + this._playInIncognito = (options2 == null ? void 0 : options2.playInIncognito) ?? false; + this._window = ((_a2 = options2 == null ? void 0 : options2.window) == null ? void 0 : _a2.type) === "sidepanel" ? new SidepanelRecorderWindow(options2.window.url) : new PopupRecorderWindow((_b2 = options2 == null ? void 0 : options2.window) == null ? void 0 : _b2.url); + this._window.onMessage = this._onMessage.bind(this); + this._window.hideApp = this._hide.bind(this); + this._onMessage({ type: "recorderEvent", event: "clear", params: {} }); + this._onMessage({ type: "recorderEvent", event: "fileChanged", params: { file: language } }); + this._recorder.setOutput(language, void 0); + this._recorder.setMode(mode); + if (this._window.isClosed()) { + await this._window.open(); + this.emit("show"); + } else { + await this._window.focus(); + } + this.setMode(mode); + } + load(code) { + var _a2; + this._updateCode(code); + (_a2 = this._editedCode) == null ? void 0 : _a2.load(); + } + async close() { + if (!this._window || this._window.isClosed()) + return; + this._hide(); + this._window = void 0; + } + _hide() { + var _a2; + this._recorder.setMode("none"); + this.setMode("none"); + (_a2 = this._window) == null ? void 0 : _a2.close(); + this.emit("hide"); + } + async setPaused(paused) { + this._sendMessage({ type: "recorder", method: "setPaused", paused }); + } + async setMode(mode) { + if (!this._recorder._isRecording()) + this._crx.player.pause().catch(() => { + }); + else + this._crx.player.stop().catch(() => { + }); + if (this._mode !== mode) { + this._mode = mode; + this.emit("modeChanged", { mode }); + } + this._sendMessage({ type: "recorder", method: "setMode", mode }); + } + async setRunningFile() { + } + async setSources(sources) { + sources = sources.filter((s) => s.isRecorded).map((s) => { + var _a2; + return ((_a2 = this._editedCode) == null ? void 0 : _a2.decorate(s)) ?? s; + }); + this._sendMessage({ type: "recorder", method: "setSources", sources }); + } + async elementPicked(elementInfo, userGesture) { + var _a2; + if (userGesture) { + if (this._recorder.mode() === "inspecting") { + this._recorder.setMode("standby"); + (_a2 = this._window) == null ? void 0 : _a2.focus(); + } + } + this._sendMessage({ type: "recorder", method: "elementPicked", elementInfo, userGesture }); + } + async resetCallLogs() { + this._sendMessage({ type: "recorder", method: "resetCallLogs" }); + } + async updateCallLogs(callLogs) { + this._sendMessage({ type: "recorder", method: "updateCallLogs", callLogs }); + } + async setActions(actions, sources) { + this._recordedActions = Array.from(actions); + this._sources = Array.from(sources); + if (this._recorder._isRecording()) + this._updateCode(null); + } + _updateCode(code) { + var _a2, _b2; + if (((_a2 = this._editedCode) == null ? void 0 : _a2.code) === code) + return; + (_b2 = this._editedCode) == null ? void 0 : _b2.stopLoad(); + this._editedCode = void 0; + if (!code) + return; + this._editedCode = new EditedCode(this._recorder, code, () => this._updateLocator(this._currentCursorPosition)); + } + async _updateLocator(position) { + if (!position) + return; + const action = this._getActions(true).find((a) => { + var _a2; + return ((_a2 = a.location) == null ? void 0 : _a2.line) === position.line + 1; + }); + if (!action || !action.action.selector) + return; + const selector = action.action.selector; + this.elementPicked({ selector, ariaSnapshot: "" }, false); + this._onMessage({ type: "recorderEvent", event: "highlightRequested", params: { selector } }); + } + _onMessage({ type: type2, event, params }) { + var _a2; + if (type2 === "recorderEvent") { + switch (event) { + case "fileChanged": + this._filename = params.file; + if ((_a2 = this._editedCode) == null ? void 0 : _a2.hasErrors()) { + this._updateCode(null); + if (this._sources) + this.setSources(this._sources); + } + break; + case "codeChanged": + this._updateCode(params.code); + break; + case "cursorActivity": + this._currentCursorPosition = params.position; + this._updateLocator(this._currentCursorPosition); + break; + case "resume": + case "step": + this._run().catch(() => { + }); + break; + case "setMode": + const { mode } = params; + if (this._mode !== mode) { + this._mode = mode; + this.emit("modeChanged", { mode }); + } + break; + } + this.emit("event", { event, params }); + } + } + async _run() { + if (this._crx.player.isPlaying()) + return; + const incognito = this._playInIncognito; + if (incognito) { + const incognitoCrxApp = await this._crx.get({ incognito }); + await (incognitoCrxApp == null ? void 0 : incognitoCrxApp.close({ closeWindows: true })); + } + const crxApp = await this._crx.get({ incognito }) ?? await this._crx.start({ incognito }, serverSideCallMetadata()); + await this._crx.player.run(crxApp._context, this._getActions()); + } + _sendMessage(msg) { + var _a2; + return (_a2 = this._window) == null ? void 0 : _a2.postMessage(msg); + } + async uninstall(page) { + await this._recorder._uninstallInjectedRecorder(page); + } + _getActions(skipLoad = false) { + var _a2, _b2; + if (this._editedCode && !skipLoad) { + this._editedCode.load(); + const actions2 = this._editedCode.actions(); + if (!this._filename || this._filename === "playwright-test") + return actions2; + } + const source2 = (_a2 = this._sources) == null ? void 0 : _a2.find((s) => s.id === this._filename); + if (!source2) + return []; + const actions = ((_b2 = this._editedCode) == null ? void 0 : _b2.hasLoaded()) && !this._editedCode.hasErrors() ? this._editedCode.actions() : this._recordedActions; + const { header } = source2; + const languageGenerator = [...languageSet()].find((l) => l.id === this._filename); + const actionTexts = actions.map((a) => languageGenerator.generateAction(a)); + const sourceLine = (index2) => { + const numLines = (str) => str ? str.split(/\r?\n/).length : 0; + return numLines(header) + numLines(actionTexts.slice(0, index2).filter(Boolean).join("\n")) + 1; + }; + return actions.map((action, index2) => ({ + ...action, + location: { + file: this._filename, + line: sourceLine(index2), + column: 1 + } + })); + } +} +class EditedCode { + constructor(recorder, code, onLoaded) { + __publicField(this, "code"); + __publicField(this, "_recorder"); + __publicField(this, "_actions", []); + __publicField(this, "_highlight", []); + __publicField(this, "_codeLoadDebounceTimeout"); + __publicField(this, "_onLoaded"); + this.code = code; + this._recorder = recorder; + this._onLoaded = onLoaded; + this._codeLoadDebounceTimeout = setTimeout(this.load.bind(this), 500); + } + actions() { + return Array.from(this._actions); + } + hasErrors() { + var _a2; + return ((_a2 = this._highlight) == null ? void 0 : _a2.length) > 0; + } + hasLoaded() { + return !this._codeLoadDebounceTimeout; + } + decorate(source2) { + if (source2.id !== "playwright-test") + return; + return { + ...source2, + highlight: this.hasLoaded() && this.hasErrors() ? this._highlight : source2.highlight, + text: this.code + }; + } + stopLoad() { + clearTimeout(this._codeLoadDebounceTimeout); + this._codeLoadDebounceTimeout = void 0; + } + load() { + var _a2; + if (this.hasLoaded()) + return; + this.stopLoad(); + try { + const [{ actions, options: options2 }] = parse3(this.code); + this._actions = actions; + const { deviceName, contextOptions } = { deviceName: "", contextOptions: {}, ...options2 }; + this._recorder.loadScript({ actions, deviceName, contextOptions, text: this.code }); + } catch (error2) { + this._actions = []; + const line = error2.loc.line ?? error2.loc.start.line ?? this.code.split("\n").length; + this._highlight = [{ line, type: "error", message: error2.message }]; + this._recorder.loadScript({ actions: this._actions, deviceName: "", contextOptions: {}, text: this.code, highlight: this._highlight }); + } + (_a2 = this._onLoaded) == null ? void 0 : _a2.call(this); + } +} +async function createTab({ incognito, ...params }) { + var _a2; + const windows = (await chrome.windows.getAll()).filter((wnd) => wnd.incognito === incognito); + const windowId = (_a2 = windows.find((w) => !params.windowId || w.id === params.windowId)) == null ? void 0 : _a2.id; + if (!windowId && params.windowId) + throw new Error(`Window with id ${params.windowId} not found or bound to a different context`); + const url2 = params.url || "about:blank"; + const [tab] = await Promise.all([ + new Promise((resolve) => { + const tabCreated = (tab2) => { + if (tab2.incognito !== incognito) + return; + chrome.tabs.onCreated.removeListener(tabCreated); + resolve(tab2); + }; + chrome.tabs.onCreated.addListener(tabCreated); + }), + windowId ? chrome.tabs.create({ ...params, url: url2, windowId }) : chrome.windows.create({ url: url2, incognito }) + ]); + const tabId = tab.id; + if (!windowId) { + const { index: index2, windowId: windowId2, ...updateParams } = params; + if (typeof index2 === "number") + await chrome.tabs.move(tabId, { index: index2 }); + await chrome.tabs.update(tabId, updateParams); + } + return tab; +} +class CrxTransport { + constructor(progress2) { + __publicField(this, "_progress"); + __publicField(this, "_detachedPromise"); + __publicField(this, "_targetToTab"); + __publicField(this, "_tabToTarget"); + __publicField(this, "_sessions"); + __publicField(this, "_defaultBrowserContextId"); + __publicField(this, "onmessage"); + __publicField(this, "onclose"); + __publicField(this, "_onPopupCreated", async ({ openerTabId, id }) => { + if (!openerTabId || !id) + return; + if (this._tabToTarget.has(openerTabId)) + await this.attach(id).catch(() => { + }); + }); + __publicField(this, "_onRemoved", (tabIdOrDebuggee) => { + const tabId = typeof tabIdOrDebuggee === "number" ? tabIdOrDebuggee : tabIdOrDebuggee.tabId; + if (!tabId) + return; + const targetInfo = this._tabToTarget.get(tabId); + this._tabToTarget.delete(tabId); + if (targetInfo) { + this._targetToTab.delete(targetInfo.targetId); + this._emitDetachedToTarget(tabId, targetInfo.targetId); + } + }); + __publicField(this, "_onDebuggerEvent", ({ tabId, sessionId }, message, params) => { + if (!tabId) + return; + if (!sessionId) + sessionId = this._sessionIdFor(tabId); + if (message === "Target.attachedToTarget") + this._sessions.set(params.sessionId, tabId); + else if (message === "Target.detachedFromTarget") + this._sessions.delete(params.sessionId); + if (debugLogger.isEnabled(`chromedebugger`)) + debugLogger.log("chromedebugger", `= 126 ? [{}] : [] + ] }); + } else if (message.method === "Target.getTargetInfo" && !debuggee.tabId) { + result = await Promise.resolve(); + } else if (message.method === "Target.createTarget") { + const { browserContextId } = message.params; + const incognito = !!browserContextId && browserContextId !== this._defaultBrowserContextId; + const tab = await createTab({ incognito }); + const { targetId } = await this.attach(tab.id); + result = { targetId }; + } else if (message.method === "Target.closeTarget") { + const { targetId } = message.params; + const tabId = this._targetToTab.get(targetId); + if (tabId) { + await chrome.tabs.remove(tabId); + result = true; + } else { + result = false; + } + } else if (message.method === "Target.disposeBrowserContext") { + result = await Promise.resolve(); + } else if (message.method === "Browser.getVersion") { + const userAgent = navigator.userAgent; + const [, product] = userAgent.match(/(Chrome\/[0-9\.]+)\b/) ?? []; + result = await Promise.resolve({ product, userAgent }).then(); + } else if (message.method === "Browser.getWindowForTarget") { + result = await Promise.resolve({}).then(); + } else if (message.method === "Browser.setDownloadBehavior") { + result = await Promise.resolve(); + } else if (message.method === "Emulation.setEmulatedMedia") { + result = await Promise.resolve(); + } else if (message.method === "Storage.getCookies") { + const { browserContextId, ...params } = message.params; + const debuggees = this._debuggeesFromBrowserContextId(browserContextId); + const results = await Promise.all(debuggees.map((debuggee2) => this._send(debuggee2, "Network.getCookies", params))); + const cookies = new Map(results.flatMap(({ cookies: cookies2 }) => cookies2.map((cookie) => [JSON.stringify(cookie), cookie]))); + result = { cookies: [...cookies.values()] }; + } else if (message.method === "Storage.setCookies") { + const { browserContextId, ...params } = message.params; + const debuggees = this._debuggeesFromBrowserContextId(browserContextId); + await Promise.all(debuggees.map((debuggee2) => this._send(debuggee2, "Network.setCookies", params))); + result = {}; + } else { + result = await this._send(debuggee, message.method, { ...message.params }); + } + this._emitMessage({ + ...message, + result + }); + } catch (error2) { + this._emitMessage({ + ...message, + error: error2 + }); + } + } + async attach(tabId, onBeforeEmitAttachedToTarget) { + var _a2; + let targetInfo = this._tabToTarget.get(tabId); + if (!targetInfo) { + const debuggee = { tabId }; + await chrome.debugger.attach(debuggee, "1.3"); + (_a2 = this._progress) == null ? void 0 : _a2.log(``); + const response2 = await this._send(debuggee, "Target.getTargetInfo"); + targetInfo = response2.targetInfo; + if (!this._defaultBrowserContextId) { + const tab = await chrome.tabs.get(tabId); + if (!tab.incognito) + this._defaultBrowserContextId = targetInfo.browserContextId; + } + await (onBeforeEmitAttachedToTarget == null ? void 0 : onBeforeEmitAttachedToTarget(targetInfo)); + this._emitAttachedToTarget(tabId, targetInfo); + this._tabToTarget.set(tabId, targetInfo); + this._targetToTab.set(targetInfo.targetId, tabId); + } + return targetInfo; + } + async detach(tabOrTarget) { + var _a2; + const tabId = typeof tabOrTarget === "number" ? tabOrTarget : this._targetToTab.get(tabOrTarget); + if (!tabId) + return; + const targetInfo = this._tabToTarget.get(tabId); + this._tabToTarget.delete(tabId); + if (targetInfo) { + this._targetToTab.delete(targetInfo.targetId); + this._emitDetachedToTarget(tabId, targetInfo.targetId); + } + await chrome.debugger.detach({ tabId }).catch(() => { + }); + (_a2 = this._progress) == null ? void 0 : _a2.log(``); + } + close() { + if (this._detachedPromise) + return; + this._detachedPromise = Promise.all([...this._tabToTarget.keys()].map(this.detach)).then(() => { + var _a2; + return (_a2 = this.onclose) == null ? void 0 : _a2.call(this); + }); + } + async closeAndWait() { + var _a2, _b2; + (_a2 = this._progress) == null ? void 0 : _a2.log(``); + chrome.debugger.onEvent.removeListener(this._onDebuggerEvent); + chrome.tabs.onCreated.removeListener(this._onPopupCreated); + this.close(); + await this._detachedPromise; + chrome.tabs.onRemoved.removeListener(this._onRemoved); + chrome.tabs.onDetached.removeListener(this._onRemoved); + (_b2 = this._progress) == null ? void 0 : _b2.log(``); + } + async _send(debuggee, method, commandParams) { + if (debugLogger.isEnabled("chromedebugger")) + debugLogger.log("chromedebugger", `SEND> ${method} #${debuggee.tabId}`); + return await chrome.debugger.sendCommand(debuggee, method, commandParams); + } + _emitMessage(message) { + if (this.onmessage) + this.onmessage(message); + } + _sessionIdFor(tabId) { + return `crx-tab-${tabId}`; + } + _emitAttachedToTarget(tabId, targetInfo) { + const sessionId = this._sessionIdFor(tabId); + this._emitMessage({ + method: "Target.attachedToTarget", + sessionId: "", + params: { + sessionId, + targetInfo + } + }); + } + _emitDetachedToTarget(tabId, targetId) { + const sessionId = this._sessionIdFor(tabId); + this._emitMessage({ + method: "Target.detachedFromTarget", + sessionId: "", + params: { + sessionId, + targetId + } + }); + } + _debuggeesFromBrowserContextId(browserContextId) { + if (!browserContextId) + browserContextId = this._defaultBrowserContextId; + if (!browserContextId) + throw new Error(`No attached tab found for browserContextId ${browserContextId}`); + return [...this._tabToTarget].filter(([, targetInfo]) => targetInfo.browserContextId === browserContextId).map(([tabId, targetInfo]) => ({ tabId, targetId: targetInfo == null ? void 0 : targetInfo.targetId })); + } +} +const kDefaultTimeout = 5e3; +function traceParamsForAction(actionInContext) { + const { action } = actionInContext; + switch (action.name) { + case "navigate": { + const params = { + url: action.url + }; + return { method: "goto", apiName: "page.goto", params }; + } + case "openPage": { + return { method: "newPage", params: {}, apiName: "browserContext.newPage" }; + } + case "closePage": { + return { method: "close", params: {}, apiName: "page.close" }; + } + } + const selector = buildFullSelector(actionInContext.frame.framePath, action.selector); + switch (action.name) { + case "click": { + const params = { + selector, + strict: true, + modifiers: toKeyboardModifiers(action.modifiers), + button: action.button, + clickCount: action.clickCount, + position: action.position + }; + return { method: "click", apiName: "locator.click", params }; + } + case "press": { + const params = { + selector, + strict: true, + key: [...toKeyboardModifiers(action.modifiers), action.key].join("+") + }; + return { method: "press", apiName: "locator.press", params }; + } + case "fill": { + const params = { + selector, + strict: true, + value: action.text + }; + return { method: "fill", apiName: "locator.fill", params }; + } + case "setInputFiles": { + const params = { + selector, + strict: true, + localPaths: action.files + }; + return { method: "setInputFiles", apiName: "locator.setInputFiles", params }; + } + case "check": { + const params = { + selector, + strict: true + }; + return { method: "check", apiName: "locator.check", params }; + } + case "uncheck": { + const params = { + selector, + strict: true + }; + return { method: "uncheck", apiName: "locator.uncheck", params }; + } + case "select": { + const params = { + selector, + strict: true, + options: action.options.map((option2) => ({ value: option2 })) + }; + return { method: "selectOption", apiName: "locator.selectOption", params }; + } + case "assertChecked": { + const params = { + selector: action.selector, + expression: "to.be.checked", + isNot: !action.checked, + timeout: kDefaultTimeout + }; + return { method: "expect", apiName: "expect.toBeChecked", params }; + } + case "assertText": { + const params = { + selector, + expression: "to.have.text", + expectedText: [], + isNot: false, + timeout: kDefaultTimeout + }; + return { method: "expect", apiName: "expect.toContainText", params }; + } + case "assertValue": { + const params = { + selector, + expression: "to.have.value", + expectedValue: void 0, + isNot: false, + timeout: kDefaultTimeout + }; + return { method: "expect", apiName: "expect.toHaveValue", params }; + } + case "assertVisible": { + const params = { + selector, + expression: "to.be.visible", + isNot: false, + timeout: kDefaultTimeout + }; + return { method: "expect", apiName: "expect.toBeVisible", params }; + } + case "assertSnapshot": { + const params = { + selector, + expression: "to.match.aria", + isNot: false, + timeout: kDefaultTimeout + }; + return { method: "expect", apiName: "expect.toMatchAriaSnapshot", params }; + } + } +} +class Stopped extends Error { +} +class CrxPlayer extends EventEmitter$1 { + constructor(crx2) { + super(); + __publicField(this, "_crx"); + __publicField(this, "_currAction"); + __publicField(this, "_stopping"); + __publicField(this, "_pageAliases", /* @__PURE__ */ new Map()); + __publicField(this, "_pause"); + this._crx = crx2; + } + async pause() { + if (!this._pause) { + const context = (await this._crx.get({ incognito: false }))._context; + const pauseAction = { + action: { name: "pause" }, + frame: { pageAlias: "page", framePath: [] } + }; + this._pause = this._performAction(context, pauseAction).finally(() => this._pause = void 0).catch(() => { + }); + } + await this._pause; + } + async run(pageOrContext, actions) { + if (this.isPlaying()) + return; + let page; + let context; + if (pageOrContext instanceof Page$1) { + page = pageOrContext; + context = page.context(); + } else { + context = pageOrContext; + page = context.pages()[0] ?? await context.newPage(serverSideCallMetadata()); + } + const crxApp = await this._crx.get({ incognito: false }); + const recorder = crxApp == null ? void 0 : crxApp._recorder(); + if (recorder && crxApp && crxApp._context !== context) { + const instrumentationListener2 = { + onBeforeCall: recorder.onBeforeCall.bind(recorder), + onBeforeInputAction: recorder.onBeforeInputAction.bind(recorder), + onCallLog: recorder.onCallLog.bind(recorder), + onAfterCall: recorder.onAfterCall.bind(recorder) + }; + if (instrumentationListener2) + context.instrumentation.addListener(instrumentationListener2, context); + } + this._pageAliases.clear(); + this._pageAliases.set(page, "page"); + this.emit("start"); + try { + for (const action of actions) { + if (action.action.name === "openPage" && action.frame.pageAlias === "page") + continue; + this._currAction = action; + await this._performAction(context, action); + } + } catch (e) { + if (e instanceof Stopped) + return; + throw e; + } finally { + this._currAction = void 0; + this.pause().catch(() => { + }); + } + } + isPlaying() { + return !!this._currAction; + } + async stop() { + if (this._currAction || this._pause) { + this._currAction = void 0; + this._stopping = new ManualPromise(); + await Promise.all([ + this._stopping, + this._pause + ]); + this._stopping = void 0; + this._pause = void 0; + this.emit("stop"); + } + } + // "borrowed" from ContextRecorder + async _performAction(browserContext, actionInContext) { + var _a2; + this._checkStopped(); + const innerPerformAction = async (mainFrame2, actionInContext2, cb) => { + const context2 = mainFrame2 ?? browserContext; + const traceParams = actionInContext2.action.name === "pause" ? { method: "pause", params: {}, apiName: "page.pause" } : traceParamsForAction(actionInContext2); + const callMetadata = { + id: `call@${createGuid()}`, + internal: actionInContext2.action.name === "pause", + objectId: context2.guid, + pageId: mainFrame2 == null ? void 0 : mainFrame2._page.guid, + frameId: mainFrame2 == null ? void 0 : mainFrame2.guid, + startTime: monotonicTime(), + endTime: 0, + type: "Frame", + log: [], + location: actionInContext2.location, + playing: true, + ...traceParams + }; + try { + this._checkStopped(); + await context2.instrumentation.onBeforeCall(context2, callMetadata); + this._checkStopped(); + await cb(callMetadata); + } catch (e) { + callMetadata.error = serializeError$1(e); + } finally { + callMetadata.endTime = monotonicTime(); + await context2.instrumentation.onAfterCall(context2, callMetadata); + if (callMetadata.error) + throw callMetadata.error.error; + } + }; + const kActionTimeout = isUnderTest() ? 2e3 : 5e3; + const { action } = actionInContext; + const pageAliases = this._pageAliases; + const context = browserContext; + if (action.name === "pause") + return await innerPerformAction(null, actionInContext, () => Promise.resolve()); + if (action.name === "openPage") { + return await innerPerformAction(null, actionInContext, async (callMetadata) => { + const pageAlias2 = actionInContext.frame.pageAlias; + if ([...pageAliases.values()].includes(pageAlias2)) + throw new Error(`Page with alias ${pageAlias2} already exists`); + const newPage = await context.newPage(callMetadata); + if (action.url && action.url !== "about:blank" && action.url !== "chrome://newtab/") { + const navigateCallMetadata = { + ...callMetadata, + ...traceParamsForAction({ ...actionInContext, action: { name: "navigate", url: action.url } }) + }; + await newPage.mainFrame().goto(navigateCallMetadata, action.url, { timeout: kActionTimeout }); + } + pageAliases.set(newPage, pageAlias2); + }); + } + const pageAlias = actionInContext.frame.pageAlias; + const page = (_a2 = [...pageAliases.entries()].find(([, alias]) => pageAlias === alias)) == null ? void 0 : _a2[0]; + if (!page) + throw new Error("Internal error: page not found"); + const mainFrame = page.mainFrame(); + if (action.name === "navigate") + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.goto(callMetadata, action.url, { timeout: kActionTimeout })); + if (action.name === "closePage") { + return await innerPerformAction(mainFrame, actionInContext, async (callMetadata) => { + pageAliases.delete(page); + await page.close(callMetadata, { runBeforeUnload: true }); + }); + } + const selector = buildFullSelector(actionInContext.frame.framePath, action.selector); + if (action.name === "click") { + const options2 = toClickOptions(action); + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.click(callMetadata, selector, { ...options2, timeout: kActionTimeout, strict: true })); + } + if (action.name === "press") { + const modifiers = toKeyboardModifiers(action.modifiers); + const shortcut = [...modifiers, action.key].join("+"); + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.press(callMetadata, selector, shortcut, { timeout: kActionTimeout, strict: true })); + } + if (action.name === "fill") + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.fill(callMetadata, selector, action.text, { timeout: kActionTimeout, strict: true })); + if (action.name === "setInputFiles") + return await innerPerformAction(mainFrame, actionInContext, () => Promise.reject(new Error(`player does not support setInputFiles yet`))); + if (action.name === "check") + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.check(callMetadata, selector, { timeout: kActionTimeout, strict: true })); + if (action.name === "uncheck") + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.uncheck(callMetadata, selector, { timeout: kActionTimeout, strict: true })); + if (action.name === "select") { + const values = action.options.map((value) => ({ value })); + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.selectOption(callMetadata, selector, [], values, { timeout: kActionTimeout, strict: true })); + } + if (action.name === "assertChecked") { + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.expect(callMetadata, selector, { + selector, + expression: "to.be.checked", + expectedValue: { checked: true }, + isNot: !action.checked, + timeout: kActionTimeout + })); + } + if (action.name === "assertText") { + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.expect(callMetadata, selector, { + selector, + expression: "to.have.text", + expectedText: serializeExpectedTextValues([action.text], { matchSubstring: true, normalizeWhiteSpace: true }), + isNot: false, + timeout: kActionTimeout + })); + } + if (action.name === "assertValue") { + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.expect(callMetadata, selector, { + selector, + expression: "to.have.value", + expectedText: serializeExpectedTextValues([action.value], { matchSubstring: false, normalizeWhiteSpace: true }), + isNot: false, + timeout: kActionTimeout + })); + } + if (action.name === "assertVisible") { + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.expect(callMetadata, selector, { + selector, + expression: "to.be.visible", + isNot: false, + timeout: kActionTimeout + })); + } + if (action.name === "assertSnapshot") { + return await innerPerformAction(mainFrame, actionInContext, (callMetadata) => mainFrame.expect(callMetadata, selector, { + selector, + expression: "to.match.aria", + expectedValue: parseAriaSnapshotUnsafe(yaml, action.snapshot), + isNot: false, + timeout: kActionTimeout + })); + } + throw new Error("Internal error: unexpected action " + action.name); + } + _checkStopped() { + if (this._stopping) { + this._stopping.resolve(); + throw new Stopped(); + } + } +} +const kTabIdSymbol = Symbol("kTabIdSymbol"); +class Crx2 extends SdkObject { + constructor(playwright2) { + super(playwright2, "crx"); + __publicField(this, "_transport"); + __publicField(this, "_browserPromise"); + __publicField(this, "_crxApplicationPromise"); + __publicField(this, "_incognitoCrxApplicationPromise"); + __publicField(this, "player"); + this.player = new CrxPlayer(this); + } + async start(options2) { + const { incognito, contextOptions } = options2 ?? {}; + const device = deviceDescriptors[options2 == null ? void 0 : options2.deviceName] ?? {}; + const viewport = (contextOptions == null ? void 0 : contextOptions.viewport) ?? device.viewport; + const newContextOptions = { + noDefaultViewport: !viewport, + ...device, + ...contextOptions, + viewport + }; + if (!this._transport && !this._browserPromise) { + const browserLogsCollector = new RecentLogsCollector(); + const browserProcess = { + onclose: void 0, + process: void 0, + // browser.close() calls this function, and closing transport will trigger + // Browser.Events.Disconnected and force the browser to resolve the close promise. + close: () => this._transport.closeAndWait(), + kill: () => Promise.resolve() + }; + const browserOptions = { + name: "chromium", + isChromium: true, + headful: true, + persistent: newContextOptions, + browserProcess, + protocolLogger: helper.debugProtocolLogger(), + browserLogsCollector, + originalLaunchOptions: {}, + artifactsDir: "/tmp/artifacts", + downloadsPath: "/tmp/downloads", + tracesDir: "/tmp/traces", + ...options2 + }; + this._transport = new CrxTransport(); + this._browserPromise = CRBrowser.connect(this.attribution.playwright, this._transport, browserOptions); + } + const browser2 = await this._browserPromise; + const transport = this._transport; + if (incognito) { + if (this._incognitoCrxApplicationPromise) + throw new Error(`incognito crxApplication is already started`); + this._incognitoCrxApplicationPromise = this._startIncognitoCrxApplication(browser2, transport, newContextOptions); + return await this._incognitoCrxApplicationPromise; + } else { + if (this._crxApplicationPromise) + throw new Error(`crxApplication is already started`); + this._crxApplicationPromise = this._startCrxApplication(browser2, transport); + return await this._crxApplicationPromise; + } + } + async _startCrxApplication(browser2, transport) { + const context = browser2._defaultContext; + const crxApp = new CrxApplication2(this, context, transport); + context.on(BrowserContext$1.Events.Close, () => { + this._crxApplicationPromise = void 0; + }); + browser2.on(CRBrowser.Events.Disconnected, () => { + this._browserPromise = void 0; + this._transport = void 0; + }); + RecorderApp.factory = () => { + return async (recorder) => { + if (recorder instanceof Recorder && recorder._context === context) + return await crxApp._createRecorderApp(recorder); + else + return new EmptyRecorderApp(); + }; + }; + return crxApp; + } + async _startIncognitoCrxApplication(browser2, transport, options2) { + var _a2; + const windows = await chrome.windows.getAll().catch(() => { + }) ?? []; + const activeTabs = await chrome.tabs.query({ active: true }); + const incognitoTab = activeTabs.find((t) => { + var _a3; + return t.incognito && !((_a3 = t.url) == null ? void 0 : _a3.startsWith("chrome://")); + }) ?? await createTab({ incognito: true, windowId: (_a2 = windows.find((w) => w.incognito)) == null ? void 0 : _a2.id, url: "about:blank" }); + const incognitoTabId = incognitoTab.id; + let context; + await transport.attach(incognitoTabId, async ({ browserContextId }) => { + assert(browserContextId); + context = new CRBrowserContext(browser2, browserContextId, options2 ?? {}); + await context._initialize(); + browser2._contexts.set(browserContextId, context); + }); + context.on(BrowserContext$1.Events.Close, () => { + this._incognitoCrxApplicationPromise = void 0; + }); + const crxApp = new CrxApplication2(this, context, transport); + await crxApp.attach(incognitoTabId); + return crxApp; + } + async get(options2) { + return options2.incognito ? await this._incognitoCrxApplicationPromise : await this._crxApplicationPromise; + } +} +const _CrxApplication = class _CrxApplication2 extends SdkObject { + constructor(crx2, context, transport) { + super(context, "crxApplication"); + __publicField(this, "_crx"); + __publicField(this, "_context"); + __publicField(this, "_transport"); + __publicField(this, "_recorderApp"); + __publicField(this, "_closed", false); + __publicField(this, "onWindowRemoved", async () => { + const windows = await chrome.windows.getAll(); + if (this.isIncognito() && windows.every((w) => !w.incognito)) + await this.close({}); + }); + this.instrumentation.addListener({ + onPageClose: (page) => { + page.hideHighlight(); + } + }, null); + this._crx = crx2; + this._context = context; + this._transport = transport; + context.on(BrowserContext$1.Events.Page, (page) => { + const tabId = this.tabIdForPage(page); + if (!tabId) + return; + page[kTabIdSymbol] = tabId; + page.on(Page$1.Events.Close, () => { + this.emit(_CrxApplication2.Events.Detached, { tabId }); + }); + this.emit(_CrxApplication2.Events.Attached, { page, tabId }); + }); + context.on(BrowserContext$1.Events.Close, () => this.close().catch(() => { + })); + chrome.windows.onRemoved.addListener(this.onWindowRemoved); + } + _browser() { + return this._context._browser; + } + isIncognito() { + return this._context._browser._defaultContext !== this._context; + } + _crPages() { + return [...this._browser()._crPages.values()].filter((p) => this._transport.isIncognito(p._targetId) === this.isIncognito()); + } + _crPageByTargetId(targetId) { + const crPage = this._browser()._crPages.get(targetId); + if (crPage && this._transport.isIncognito(crPage._targetId) === this.isIncognito()) + return crPage; + } + tabIdForPage(page) { + var _a2; + const targetId = (_a2 = this._crPages().find((crPage) => crPage._page === page)) == null ? void 0 : _a2._targetId; + if (!targetId) + return; + return this._transport.getTabId(targetId); + } + async showRecorder(options2) { + if (!this._recorderApp) { + const { mode, ...otherOptions } = options2 ?? {}; + const recorderParams = { + language: (options2 == null ? void 0 : options2.language) ?? "playwright-test", + mode: mode === "none" ? void 0 : mode, + ...otherOptions + }; + Recorder.show(this._context, (recorder) => this._createRecorderApp(recorder), recorderParams); + } + await this._recorderApp.open(options2); + } + async hideRecorder() { + var _a2; + await ((_a2 = this._recorderApp) == null ? void 0 : _a2.close()); + } + setMode(mode) { + var _a2; + (_a2 = this._recorderApp) == null ? void 0 : _a2._recorder.setMode(mode); + } + async attach(tabId) { + const { targetId, browserContextId } = await this._transport.attach(tabId); + const tab = await chrome.tabs.get(tabId); + if (tab.incognito !== this.isIncognito() || this._context._browserContextId && browserContextId !== this._context._browserContextId) { + await this._transport.detach(targetId); + throw new Error("Tab is not in the expected browser context"); + } + const crPage = this._crPageByTargetId(targetId); + assert(crPage); + const pageOrError = await crPage._page.waitForInitializedOrError(); + if (pageOrError instanceof Error) + throw pageOrError; + return pageOrError; + } + async attachAll(params) { + const tabs = await chrome.tabs.query(params); + const pages = await Promise.all(tabs.map(async (tab) => { + var _a2; + const baseUrl = chrome.runtime.getURL(""); + if (tab.incognito === this.isIncognito() && tab.id && !((_a2 = tab.url) == null ? void 0 : _a2.startsWith(baseUrl))) + return await this.attach(tab.id).catch(() => { + }); + })); + return pages.filter(Boolean); + } + async detach(tabIdOrPage) { + const targetId = tabIdOrPage instanceof Page$1 ? tabIdOrPage.delegate._targetId : this._transport.getTargetId(tabIdOrPage); + await this._doDetach(targetId); + } + async detachAll() { + const tabs = await chrome.tabs.query({}); + await Promise.all(tabs.map(async (tab) => { + if (tab.id && tab.incognito === this.isIncognito()) + await this.detach(tab.id).catch(() => { + }); + })); + } + async newPage(params) { + const tab = await createTab({ incognito: this.isIncognito(), ...params }); + if (!(tab == null ? void 0 : tab.id)) + throw new Error(`No ID found for tab`); + return await this.attach(tab.id); + } + async close(options2) { + if (this._closed) + return; + if ((options2 == null ? void 0 : options2.closeWindows) && !this.isIncognito()) + throw new Error("closeWindows is only supported in incognito mode"); + this._closed = true; + chrome.windows.onRemoved.removeListener(this.onWindowRemoved); + if (options2 == null ? void 0 : options2.closeWindows) { + const windows = await chrome.windows.getAll(); + await Promise.all(windows.filter((w) => w.incognito && w.id).map((w) => chrome.windows.remove(w.id))); + } else { + await Promise.all(this._crPages().map((crPage) => (options2 == null ? void 0 : options2.closePages) ? crPage.closePage(false) : this._doDetach(crPage._targetId))); + } + await this._context.close({}); + } + list(code) { + const tests = parse3(code); + return tests.map(({ title, options: options2, location: location2 }) => ({ title, options: options2, location: location2 })); + } + load(code) { + var _a2; + (_a2 = this._recorderApp) == null ? void 0 : _a2.load(code); + } + async run(code, page) { + const [{ actions }] = parse3(code); + await this._crx.player.run(page ?? this._context, actions); + } + async parseForTest(originCode) { + const [{ actions, options: options2 }] = parse3(originCode); + const jsLanguage = [...languageSet()].find((l) => l.id === "playwright-test"); + const code = generateCode(actions, jsLanguage, { browserName: "", launchOptions: {}, contextOptions: {}, ...options2 }).text; + return { actions, options: options2, code }; + } + async _createRecorderApp(recorder) { + if (!this._recorderApp) { + this._recorderApp = new CrxRecorderApp(this._crx, recorder); + this._recorderApp.on("show", () => this.emit(_CrxApplication2.Events.RecorderShow)); + this._recorderApp.on("hide", () => this.emit(_CrxApplication2.Events.RecorderHide)); + this._recorderApp.on("modeChanged", (event) => { + this.emit(_CrxApplication2.Events.ModeChanged, event); + }); + } + return this._recorderApp; + } + _recorder() { + var _a2; + return (_a2 = this._recorderApp) == null ? void 0 : _a2._recorder; + } + async _doDetach(targetId) { + var _a2; + if (!targetId) + return; + if (this._transport.isIncognito(targetId) !== this.isIncognito()) + throw new Error("Tab is not in the expected browser context"); + const crPage = this._crPageByTargetId(targetId); + if (!crPage) + return; + const pageOrError = await crPage._page.waitForInitializedOrError(); + if (pageOrError instanceof Error) + throw pageOrError; + await Promise.all([ + (_a2 = this._recorderApp) == null ? void 0 : _a2.uninstall(pageOrError), + pageOrError.hideHighlight() + ]); + const closed = new Promise((x) => pageOrError.once(Page$1.Events.Close, x)); + await this._transport.detach(targetId); + await closed; + } +}; +__publicField(_CrxApplication, "Events", { + RecorderHide: "hide", + RecorderShow: "show", + Attached: "attached", + Detached: "detached", + ModeChanged: "modeChanged" +}); +let CrxApplication2 = _CrxApplication; +class CrxPlaywright2 extends Playwright$1 { + constructor() { + super({ sdkLanguage: "javascript" }); + __publicField(this, "_crx"); + this._crx = new Crx2(this); + } +} +class CrxDispatcher extends Dispatcher { + constructor(scope, crx2) { + super(scope, crx2, "Crx", {}); + __publicField(this, "_type_Crx", true); + } + async start(params) { + return { crxApplication: new CrxApplicationDispatcher(this, await this._object.start(params)) }; + } +} +class CrxApplicationDispatcher extends Dispatcher { + constructor(scope, crxApplication) { + const context = new BrowserContextDispatcher(scope, crxApplication._context); + super(scope, crxApplication, "CrxApplication", { context }); + __publicField(this, "_type_CrxApplication", true); + __publicField(this, "_context"); + this._context = context; + const dispatchEvent = this._dispatchEvent.bind(this); + this.addObjectListener(CrxApplication2.Events.RecorderHide, () => { + dispatchEvent("hide"); + }); + this.addObjectListener(CrxApplication2.Events.RecorderShow, () => { + dispatchEvent("show"); + }); + this.addObjectListener(CrxApplication2.Events.Attached, ({ tabId, page }) => { + dispatchEvent("attached", { tabId, page: PageDispatcher.from(this._context, page) }); + }); + this.addObjectListener(CrxApplication2.Events.Detached, ({ tabId }) => { + dispatchEvent("detached", { tabId }); + }); + this.addObjectListener(CrxApplication2.Events.ModeChanged, (event) => { + dispatchEvent("modeChanged", event); + }); + } + async attach(params) { + return { page: PageDispatcher.from(this._context, await this._object.attach(params.tabId)) }; + } + async attachAll(params) { + return { pages: (await this._object.attachAll(params)).map((page) => PageDispatcher.from(this._context, page)) }; + } + async detach(params) { + if (params.tabId && params.page) + throw new Error(`Only either tabId or page must be specified, not both`); + if (!params.tabId && !params.page) + throw new Error(`Either tabId or page must be specified, not none`); + await this._object.detach(params.tabId ?? params.page._object); + } + async detachAll() { + await this._object.detachAll(); + } + async newPage(params) { + return { page: PageDispatcher.from(this._context, await this._object.newPage(params)) }; + } + async showRecorder(params) { + await this._object.showRecorder(params); + } + async hideRecorder() { + await this._object.hideRecorder(); + } + async setMode(params) { + this._object.setMode(params.mode); + } + async close() { + await this._object.close(); + this._dispose(); + } + async list(params) { + const tests = this._object.list(params.code); + return { tests }; + } + async load(params) { + this._object.load(params.code); + } + async run(params) { + var _a2; + await this._object.run(params.code, (_a2 = params.page) == null ? void 0 : _a2._object); + } +} +class CrxPlaywrightDispatcher extends Dispatcher { + constructor(scope, playwright2) { + super(scope, playwright2, "Playwright", { + chromium: new BrowserTypeDispatcher(scope, playwright2.chromium), + firefox: new BrowserTypeDispatcher(scope, playwright2.firefox), + webkit: new BrowserTypeDispatcher(scope, playwright2.webkit), + bidiChromium: new BrowserTypeDispatcher(scope, playwright2.bidiChromium), + bidiFirefox: new BrowserTypeDispatcher(scope, playwright2.bidiFirefox), + android: new AndroidDispatcher(scope, playwright2.android), + electron: new ElectronDispatcher(scope, playwright2.electron), + utils: new LocalUtilsDispatcher(scope, playwright2), + _crx: new CrxDispatcher(scope, playwright2._crx) + }); + __publicField(this, "_type_Playwright"); + this._type_Playwright = true; + } + async newRequest(params) { + const request2 = new GlobalAPIRequestContext(this._object, params); + return { request: APIRequestContextDispatcher.from(this.parentScope(), request2) }; + } + async cleanup() { + } +} +const apis = { + accessibility: [Accessibility2.prototype, { snapshot: true }], + // android: [Android.prototype], + // androidDevice: [AndroidDevice.prototype], + // androidWebView: [AndroidWebView.prototype], + // androidInput: [AndroidInput.prototype], + // androidSocket: [AndroidSocket.prototype], + browser: [Browser.prototype, { newContext: true, newPage: true, newBrowserCDPSession: true, startTracing: true, stopTracing: true, close: true }], + browserContext: [BrowserContext.prototype, { + newPage: true, + cookies: true, + addCookies: true, + clearCookies: true, + grantPermissions: true, + clearPermissions: true, + setGeolocation: true, + setExtraHTTPHeaders: true, + setOffline: true, + setHTTPCredentials: true, + addInitScript: true, + exposeBinding: true, + exposeFunction: true, + route: true, + routeWebSocket: true, + routeFromHAR: true, + unrouteAll: true, + unroute: true, + waitForEvent: true, + storageState: true, + newCDPSession: true, + close: true + }], + browserType: [BrowserType2.prototype, { launch: true, launchServer: true, launchPersistentContext: true, connect: true, connectOverCDP: true }], + clock: [Clock2.prototype, { install: true, fastForward: true, pauseAt: true, resume: true, runFor: true, setFixedTime: true, setSystemTime: true }], + consoleMessage: [ConsoleMessage2.prototype, {}], + coverage: [Coverage.prototype, { startCSSCoverage: true, stopCSSCoverage: true, startJSCoverage: true, stopJSCoverage: true }], + dialog: [Dialog2.prototype, { accept: true, dismiss: true }], + download: [Download2.prototype, { cancel: true, createReadStream: true, path: true, failure: true, delete: true, saveAs: true }], + // electron: [Electron.prototype, {}], + // electronApplication: [ElectronApplication.prototype, {}], + locator: [Locator.prototype, { + boundingBox: true, + check: true, + click: true, + dblclick: true, + dispatchEvent: true, + dragTo: true, + evaluate: true, + evaluateAll: true, + evaluateHandle: true, + fill: true, + clear: true, + highlight: true, + elementHandle: true, + elementHandles: true, + focus: true, + blur: true, + count: true, + getAttribute: true, + hover: true, + innerHTML: true, + innerText: true, + inputValue: true, + isChecked: true, + isDisabled: true, + isEditable: true, + isEnabled: true, + isHidden: true, + isVisible: true, + press: true, + screenshot: true, + ariaSnapshot: true, + scrollIntoViewIfNeeded: true, + selectOption: true, + selectText: true, + setChecked: true, + setInputFiles: true, + tap: true, + textContent: true, + type: true, + pressSequentially: true, + uncheck: true, + all: true, + allInnerTexts: true, + allTextContents: true, + waitFor: true + }], + frameLocator: [FrameLocator.prototype, {}], + elementHandle: [ElementHandle2.prototype, { + // from JSHandle + evaluate: true, + evaluateHandle: true, + getProperty: true, + getProperties: true, + jsonValue: true, + dispose: true, + // from ElementHandle + ownerFrame: true, + contentFrame: true, + getAttribute: true, + inputValue: true, + textContent: true, + innerText: true, + innerHTML: true, + isChecked: true, + isDisabled: true, + isEditable: true, + isEnabled: true, + isHidden: true, + isVisible: true, + dispatchEvent: true, + scrollIntoViewIfNeeded: true, + hover: true, + click: true, + dblclick: true, + tap: true, + selectOption: true, + fill: true, + selectText: true, + setInputFiles: true, + focus: true, + type: true, + press: true, + check: true, + uncheck: true, + setChecked: true, + boundingBox: true, + screenshot: true, + $: true, + $$: true, + $eval: true, + $$eval: true, + waitForElementState: true, + waitForSelector: true + }], + fileChooser: [FileChooser2.prototype, { setFiles: true }], + timeoutError: [TimeoutError2.prototype, {}], + frame: [Frame.prototype, { + goto: true, + waitForNavigation: true, + waitForLoadState: true, + waitForURL: true, + frameElement: true, + evaluateHandle: true, + evaluate: true, + $: true, + $$: true, + waitForSelector: true, + dispatchEvent: true, + $eval: true, + $$eval: true, + content: true, + setContent: true, + addScriptTag: true, + addStyleTag: true, + click: true, + dblclick: true, + dragAndDrop: true, + tap: true, + fill: true, + focus: true, + textContent: true, + innerText: true, + innerHTML: true, + getAttribute: true, + inputValue: true, + isChecked: true, + isDisabled: true, + isEditable: true, + isEnabled: true, + isHidden: true, + isVisible: true, + hover: true, + selectOption: true, + setInputFiles: true, + type: true, + press: true, + check: true, + uncheck: true, + setChecked: true, + waitForTimeout: true, + waitForFunction: true, + title: true + }], + keyboard: [Keyboard2.prototype, { down: true, up: true, insertText: true, type: true, press: true }], + mouse: [Mouse2.prototype, { click: true, dblclick: true, down: true, up: true, move: true, wheel: true }], + touchscreen: [Touchscreen2.prototype, { tap: true }], + jSHandle: [JSHandle2.prototype, { evaluate: true, evaluateHandle: true, getProperty: true, jsonValue: true, getProperties: true, dispose: true }], + route: [Route2.prototype, { fallback: true, abort: true, fetch: true, fulfill: true, continue: true }], + webSocket: [WebSocket.prototype, { waitForEvent: true }], + webSocketRoute: [WebSocketRoute.prototype, { close: true }], + // request: [APIRequest.prototype, {}], + // requestContext: [APIRequestContext.prototype, {}], + // response: [APIResponse.prototype, {}], + page: [Page.prototype, { + opener: true, + waitForSelector: true, + dispatchEvent: true, + evaluateHandle: true, + $: true, + $$: true, + $eval: true, + $$eval: true, + addScriptTag: true, + addStyleTag: true, + exposeFunction: true, + exposeBinding: true, + setExtraHTTPHeaders: true, + content: true, + setContent: true, + goto: true, + reload: true, + addLocatorHandler: true, + removeLocatorHandler: true, + waitForLoadState: true, + waitForNavigation: true, + waitForURL: true, + waitForRequest: true, + waitForResponse: true, + waitForEvent: true, + goBack: true, + goForward: true, + requestGC: true, + emulateMedia: true, + setViewportSize: true, + evaluate: true, + addInitScript: true, + route: true, + routeFromHAR: true, + routeWebSocket: true, + unrouteAll: true, + unroute: true, + screenshot: true, + title: true, + bringToFront: true, + close: true, + click: true, + dragAndDrop: true, + dblclick: true, + tap: true, + fill: true, + focus: true, + textContent: true, + innerText: true, + innerHTML: true, + getAttribute: true, + inputValue: true, + isChecked: true, + isDisabled: true, + isEditable: true, + isEnabled: true, + isHidden: true, + isVisible: true, + hover: true, + selectOption: true, + setInputFiles: true, + type: true, + press: true, + check: true, + uncheck: true, + setChecked: true, + waitForTimeout: true, + waitForFunction: true, + pause: true, + pdf: true + }], + selectors: [Selectors2.prototype, { register: true }], + tracing: [Tracing2.prototype, { group: true, groupEnd: true, start: true, startChunk: true, stop: true, stopChunk: true }], + video: [Video.prototype, { delete: true, path: true, saveAs: true }], + worker: [Worker.prototype, { evaluate: true, evaluateHandle: true }], + session: [CDPSession.prototype, { send: true, detach: true }], + playwright: [Playwright2.prototype, { devices: false }], + webError: [WebError.prototype, {}], + // from crx + crx: [Crx$1.prototype, { start: true, get: true }], + crxApplication: [CrxApplication$1.prototype, { attach: true, attachAll: true, close: true, detach: true, detachAll: true, newPage: true }], + crxRecorder: [CrxRecorder.prototype, { hide: true, list: true, load: true, run: true, setMode: true, show: true }] +}; +const kCrxZoneWrapped = Symbol("crxZone"); +function wrapClientApis() { + for (const [typeName, [proto, props]] of Object.entries(apis)) { + for (const [key2, needsWrap] of Object.entries(props)) { + if (!needsWrap) + continue; + const originalFn = proto[key2]; + if (!originalFn || typeof originalFn !== "function") + throw new Error(`Method ${key2} not found in ${typeName}`); + if (originalFn[kCrxZoneWrapped] === true) + continue; + const wrapFn = async function(...args) { + const apiName = currentZone().data("crxZone"); + if (apiName) + return await originalFn.apply(this, args); + return await currentZone().with("crxZone", { apiName: `${typeName}.${key2}` }).run(async () => await originalFn.apply(this, args)); + }; + wrapFn[kCrxZoneWrapped] = true; + proto[key2] = wrapFn; + } + } +} +PageBinding.kBindingName = "__crx__binding__"; +const playwright = new CrxPlaywright2(); +const clientConnection = new CrxConnection(nodePlatform); +const dispatcherConnection = new DispatcherConnection( + true + /* local */ +); +dispatcherConnection.onmessage = (message) => clientConnection.dispatch(message); +clientConnection.onmessage = (message) => dispatcherConnection.dispatch(message); +const rootScope = new RootDispatcher(dispatcherConnection); +new CrxPlaywrightDispatcher(rootScope, playwright); +const playwrightAPI = clientConnection.getObjectWithKnownName("Playwright"); +dispatcherConnection.onmessage = (message) => setImmediate(() => clientConnection.dispatch(message)); +clientConnection.onmessage = (message) => setImmediate(() => dispatcherConnection.dispatch(message)); +clientConnection.toImpl = (x) => x ? dispatcherConnection._dispatcherByGuid.get(x._guid)._object : dispatcherConnection._dispatcherByGuid.get(""); +playwrightAPI._toImpl = clientConnection.toImpl; +const { _crx: crx, selectors, errors } = playwrightAPI; +wrapClientApis(); +const debug = browserExports$2.debug; +const stoppedModes = ["none", "standby", "detached"]; +const recordingModes = ["recording", "assertingText", "assertingVisibility", "assertingValue", "assertingSnapshot"]; +let crxAppPromise; +const attachedTabIds = /* @__PURE__ */ new Set(); +let currentMode; +let settings = defaultSettings; +const settingsInitializing = loadSettings().then((s) => settings = s).catch(() => { +}); +addSettingsChangedListener((newSettings) => { + settings = newSettings; + setTestIdAttributeName(newSettings.testIdAttributeName); +}); +let allowsIncognitoAccess = false; +chrome.extension.isAllowedIncognitoAccess().then((allowed) => { + allowsIncognitoAccess = allowed; +}); +async function changeAction(tabId, mode) { + if (!mode) + mode = attachedTabIds.has(tabId) ? currentMode : "detached"; + else if (mode !== "detached") + currentMode = mode; + if (!mode || stoppedModes.includes(mode)) { + await Promise.all([ + chrome.action.setTitle({ title: mode === "none" ? "Stopped" : "Record", tabId }), + chrome.action.setBadgeText({ text: "", tabId }) + ]).catch(() => { + }); + return; + } + const { text, title, color, bgColor } = recordingModes.includes(mode) ? { text: "REC", title: "Recording", color: "white", bgColor: "darkred" } : { text: "INS", title: "Inspecting", color: "white", bgColor: "dodgerblue" }; + await Promise.all([ + chrome.action.setTitle({ title, tabId }), + chrome.action.setBadgeText({ text, tabId }), + chrome.action.setBadgeTextColor({ color, tabId }), + chrome.action.setBadgeBackgroundColor({ color: bgColor, tabId }) + ]).catch(() => { + }); +} +chrome.tabs.onUpdated.addListener((tabId) => changeAction(tabId)); +async function getCrxApp(incognito) { + if (!crxAppPromise) { + await settingsInitializing; + crxAppPromise = crx.start({ incognito }).then((crxApp) => { + crxApp.recorder.addListener("hide", async () => { + await crxApp.close(); + crxAppPromise = void 0; + }); + crxApp.recorder.addListener("modechanged", async ({ mode }) => { + await Promise.all([...attachedTabIds].map((tabId) => changeAction(tabId, mode))); + }); + crxApp.addListener("attached", async ({ tabId }) => { + attachedTabIds.add(tabId); + await changeAction(tabId, crxApp.recorder.mode()); + }); + crxApp.addListener("detached", async (tabId) => { + attachedTabIds.delete(tabId); + await changeAction(tabId, "detached"); + }); + setTestIdAttributeName(settings.testIdAttributeName); + return crxApp; + }); + } + return await crxAppPromise; +} +async function attach(tab, mode) { + var _a2; + if (!(tab == null ? void 0 : tab.id) || attachedTabIds.has(tab.id) && !mode) + return; + if (tab.incognito && !allowsIncognitoAccess) + throw new Error("Not authorized to launch in Incognito mode."); + const sidepanel = !isUnderTest() && settings.sidepanel; + if (sidepanel) + await chrome.sidePanel.open({ windowId: tab.windowId }); + chrome.action.disable(); + if ((_a2 = tab.url) == null ? void 0 : _a2.startsWith("chrome://")) { + const windowId = tab.windowId; + tab = await new Promise((resolve) => { + chrome.tabs.create({ windowId, url: "about:blank" }).then((tab2) => { + resolve(tab2); + }).catch(() => { + }); + }); + } + const crxApp = await getCrxApp(tab.incognito); + try { + if (crxApp.recorder.isHidden()) { + await crxApp.recorder.show({ + mode: mode ?? "recording", + language: settings.targetLanguage, + window: { type: sidepanel ? "sidepanel" : "popup", url: "index.html" }, + playInIncognito: settings.playInIncognito + }); + } + await crxApp.attach(tab.id); + if (mode) + await crxApp.recorder.setMode(mode); + } finally { + chrome.action.enable(); + } +} +async function setTestIdAttributeName(testIdAttributeName2) { + playwrightAPI.selectors.setTestIdAttribute(testIdAttributeName2); +} +chrome.action.onClicked.addListener(attach); +chrome.contextMenus.create({ + id: "pw-recorder", + title: "Attach to Playwright Recorder", + contexts: ["all"] +}); +chrome.contextMenus.onClicked.addListener(async (_, tab) => { + if (tab) + await attach(tab); +}); +chrome.commands.onCommand.addListener(async (command2, tab) => { + if (!tab.id) + return; + if (command2 === "inspect") + await attach(tab, "inspecting"); + else if (command2 === "record") + await attach(tab, "recording"); +}); +async function getStorageState() { + const crxApp = await crxAppPromise; + if (!crxApp) + return; + return await crxApp.context().storageState(); +} +chrome.runtime.onMessage.addListener((message, _, sendResponse) => { + if (message.event === "storageStateRequested") { + getStorageState().then(sendResponse).catch(() => { + }); + return true; + } +}); +chrome.runtime.onInstalled.addListener((details) => { + if (globalThis.__crxTest) + return; + void details; +}); +Object.assign(self, { attach, setTestIdAttributeName, getCrxApp, _debug: debug, _setUnderTest: setUnderTest }); +import "./edge_share_relay.js"; diff --git a/extension/edge-share-crx/codeMirrorModule.css b/extension/edge-share-crx/codeMirrorModule.css new file mode 100644 index 0000000..f4d5718 --- /dev/null +++ b/extension/edge-share-crx/codeMirrorModule.css @@ -0,0 +1,344 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; + direction: ltr; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre.CodeMirror-line, +.CodeMirror pre.CodeMirror-line-like { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0 !important; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} +.cm-fat-cursor .CodeMirror-line::selection, +.cm-fat-cursor .CodeMirror-line > span::selection, +.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; } +.cm-fat-cursor .CodeMirror-line::-moz-selection, +.cm-fat-cursor .CodeMirror-line > span::-moz-selection, +.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; } +.cm-fat-cursor { caret-color: transparent; } +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-rulers { + position: absolute; + left: 0; right: 0; top: -50px; bottom: 0; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + top: 0; bottom: 0; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 50px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -50px; margin-right: -50px; + padding-bottom: 50px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; + z-index: 0; +} +.CodeMirror-sizer { + position: relative; + border-right: 50px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; + outline: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + min-height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + vertical-align: top; + margin-bottom: -50px; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper ::selection { background-color: transparent } +.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre.CodeMirror-line, +.CodeMirror pre.CodeMirror-line-like { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; +} +.CodeMirror-wrap pre.CodeMirror-line, +.CodeMirror-wrap pre.CodeMirror-line-like { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + padding: 0.1px; /* Force widget margins to stay inside of the container */ +} + +.CodeMirror-widget {} + +.CodeMirror-rtl pre { direction: rtl; } + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { + position: absolute; + pointer-events: none; +} +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background-color: #ffa; + background-color: rgba(255, 255, 0, .4); +} + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/extension/edge-share-crx/codeMirrorModule.js b/extension/edge-share-crx/codeMirrorModule.js new file mode 100644 index 0000000..39e69d5 --- /dev/null +++ b/extension/edge-share-crx/codeMirrorModule.js @@ -0,0 +1,16684 @@ +import { g as getDefaultExportFromCjs } from "./form.js"; +import "./settings.js"; +var codemirror$2 = { exports: {} }; +var codemirror$1 = codemirror$2.exports; +var hasRequiredCodemirror; +function requireCodemirror() { + if (hasRequiredCodemirror) return codemirror$2.exports; + hasRequiredCodemirror = 1; + (function(module, exports) { + (function(global, factory) { + module.exports = factory(); + })(codemirror$1, function() { + var userAgent = navigator.userAgent; + var platform = navigator.platform; + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var edge = /Edge\/(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up || edge; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); + var webkit = !edge && /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent); + var chrome_version = chrome && +chrome[1]; + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); + var android = /Android/.test(userAgent); + var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) { + presto_version = Number(presto_version[1]); + } + if (presto_version && presto_version >= 15) { + presto = false; + webkit = true; + } + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || ie && ie_version >= 9; + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); + } + var rmClass = function(node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) { + e.removeChild(e.firstChild); + } + return e; + } + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) { + e.className = className; + } + if (style) { + e.style.cssText = style; + } + if (typeof content == "string") { + e.appendChild(document.createTextNode(content)); + } else if (content) { + for (var i2 = 0; i2 < content.length; ++i2) { + e.appendChild(content[i2]); + } + } + return e; + } + function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style); + e.setAttribute("role", "presentation"); + return e; + } + var range; + if (document.createRange) { + range = function(node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + } else { + range = function(node, start, end) { + var r = document.body.createTextRange(); + try { + r.moveToElementText(node.parentNode); + } catch (e) { + return r; + } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + } + function contains(parent, child) { + if (child.nodeType == 3) { + child = child.parentNode; + } + if (parent.contains) { + return parent.contains(child); + } + do { + if (child.nodeType == 11) { + child = child.host; + } + if (child == parent) { + return true; + } + } while (child = child.parentNode); + } + function activeElt(rootNode2) { + var doc2 = rootNode2.ownerDocument || rootNode2; + var activeElement; + try { + activeElement = rootNode2.activeElement; + } catch (e) { + activeElement = doc2.body || null; + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { + activeElement = activeElement.shadowRoot.activeElement; + } + return activeElement; + } + function addClass(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) { + node.className += (current ? " " : "") + cls; + } + } + function joinClasses(a, b) { + var as = a.split(" "); + for (var i2 = 0; i2 < as.length; i2++) { + if (as[i2] && !classTest(as[i2]).test(b)) { + b += " " + as[i2]; + } + } + return b; + } + var selectInput = function(node) { + node.select(); + }; + if (ios) { + selectInput = function(node) { + node.selectionStart = 0; + node.selectionEnd = node.value.length; + }; + } else if (ie) { + selectInput = function(node) { + try { + node.select(); + } catch (_e) { + } + }; + } + function doc(cm) { + return cm.display.wrapper.ownerDocument; + } + function root(cm) { + return rootNode(cm.display.wrapper); + } + function rootNode(element) { + return element.getRootNode ? element.getRootNode() : element.ownerDocument; + } + function win(cm) { + return doc(cm).defaultView; + } + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return f.apply(null, args); + }; + } + function copyObj(obj, target, overwrite) { + if (!target) { + target = {}; + } + for (var prop2 in obj) { + if (obj.hasOwnProperty(prop2) && (overwrite !== false || !target.hasOwnProperty(prop2))) { + target[prop2] = obj[prop2]; + } + } + return target; + } + function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) { + end = string.length; + } + } + for (var i2 = startIndex || 0, n = startValue || 0; ; ) { + var nextTab = string.indexOf(" ", i2); + if (nextTab < 0 || nextTab >= end) { + return n + (end - i2); + } + n += nextTab - i2; + n += tabSize - n % tabSize; + i2 = nextTab + 1; + } + } + var Delayed = function() { + this.id = null; + this.f = null; + this.time = 0; + this.handler = bind(this.onTimeout, this); + }; + Delayed.prototype.onTimeout = function(self) { + self.id = 0; + if (self.time <= +/* @__PURE__ */ new Date()) { + self.f(); + } else { + setTimeout(self.handler, self.time - +/* @__PURE__ */ new Date()); + } + }; + Delayed.prototype.set = function(ms, f) { + this.f = f; + var time = +/* @__PURE__ */ new Date() + ms; + if (!this.id || time < this.time) { + clearTimeout(this.id); + this.id = setTimeout(this.handler, ms); + this.time = time; + } + }; + function indexOf(array, elt2) { + for (var i2 = 0; i2 < array.length; ++i2) { + if (array[i2] == elt2) { + return i2; + } + } + return -1; + } + var scrollerGap = 50; + var Pass = { toString: function() { + return "CodeMirror.Pass"; + } }; + var sel_dontScroll = { scroll: false }, sel_mouse = { origin: "*mouse" }, sel_move = { origin: "+move" }; + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0; ; ) { + var nextTab = string.indexOf(" ", pos); + if (nextTab == -1) { + nextTab = string.length; + } + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) { + return pos + Math.min(skipped, goal - col); + } + col += nextTab - pos; + col += tabSize - col % tabSize; + pos = nextTab + 1; + if (col >= goal) { + return pos; + } + } + } + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) { + spaceStrs.push(lst(spaceStrs) + " "); + } + return spaceStrs[n]; + } + function lst(arr) { + return arr[arr.length - 1]; + } + function map(array, f) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = f(array[i2], i2); + } + return out; + } + function insertSorted(array, value, score) { + var pos = 0, priority = score(value); + while (pos < array.length && score(array[pos]) <= priority) { + pos++; + } + array.splice(pos, 0, value); + } + function nothing() { + } + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) { + copyObj(props, inst); + } + return inst; + } + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "€" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + function isWordChar(ch, helper) { + if (!helper) { + return isWordCharBasic(ch); + } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { + return true; + } + return helper.test(ch); + } + function isEmpty(obj) { + for (var n in obj) { + if (obj.hasOwnProperty(n) && obj[n]) { + return false; + } + } + return true; + } + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { + return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); + } + function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { + pos += dir; + } + return pos; + } + function findFirst(pred, from, to) { + var dir = from > to ? -1 : 1; + for (; ; ) { + if (from == to) { + return from; + } + var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); + if (mid == from) { + return pred(mid) ? from : to; + } + if (pred(mid)) { + to = mid; + } else { + from = mid + dir; + } + } + } + function iterateBidiSections(order, from, to, f) { + if (!order) { + return f(from, to, "ltr", 0); + } + var found = false; + for (var i2 = 0; i2 < order.length; ++i2) { + var part = order[i2]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2); + found = true; + } + } + if (!found) { + f(from, to, "ltr"); + } + } + var bidiOther = null; + function getBidiPartAt(order, ch, sticky) { + var found; + bidiOther = null; + for (var i2 = 0; i2 < order.length; ++i2) { + var cur = order[i2]; + if (cur.from < ch && cur.to > ch) { + return i2; + } + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { + found = i2; + } else { + bidiOther = i2; + } + } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { + found = i2; + } else { + bidiOther = i2; + } + } + } + return found != null ? found : bidiOther; + } + var bidiOrdering = /* @__PURE__ */ function() { + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; + function charType(code) { + if (code <= 247) { + return lowTypes.charAt(code); + } else if (1424 <= code && code <= 1524) { + return "R"; + } else if (1536 <= code && code <= 1785) { + return arabicTypes.charAt(code - 1536); + } else if (1774 <= code && code <= 2220) { + return "r"; + } else if (8192 <= code && code <= 8203) { + return "w"; + } else if (code == 8204) { + return "b"; + } else { + return "L"; + } + } + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; + this.to = to; + } + return function(str, direction) { + var outerType = direction == "ltr" ? "L" : "R"; + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { + return false; + } + var len = str.length, types = []; + for (var i2 = 0; i2 < len; ++i2) { + types.push(charType(str.charCodeAt(i2))); + } + for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) { + var type = types[i$12]; + if (type == "m") { + types[i$12] = prev; + } else { + prev = type; + } + } + for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) { + var type$1 = types[i$22]; + if (type$1 == "1" && cur == "r") { + types[i$22] = "n"; + } else if (isStrong.test(type$1)) { + cur = type$1; + if (type$1 == "r") { + types[i$22] = "R"; + } + } + } + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3]; + if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { + types[i$3] = "1"; + } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) { + types[i$3] = prev$1; + } + prev$1 = type$2; + } + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4]; + if (type$3 == ",") { + types[i$4] = "N"; + } else if (type$3 == "%") { + var end = void 0; + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) { + } + var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N"; + for (var j = i$4; j < end; ++j) { + types[j] = replace; + } + i$4 = end - 1; + } + } + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5]; + if (cur$1 == "L" && type$4 == "1") { + types[i$5] = "L"; + } else if (isStrong.test(type$4)) { + cur$1 = type$4; + } + } + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = void 0; + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) { + } + var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; + var after = (end$1 < len ? types[end$1] : outerType) == "L"; + var replace$1 = before == after ? before ? "L" : "R" : outerType; + for (var j$1 = i$6; j$1 < end$1; ++j$1) { + types[j$1] = replace$1; + } + i$6 = end$1 - 1; + } + } + var order = [], m; + for (var i$7 = 0; i$7 < len; ) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7; + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) { + } + order.push(new BidiSpan(0, start, i$7)); + } else { + var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0; + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) { + } + for (var j$2 = pos; j$2 < i$7; ) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { + order.splice(at, 0, new BidiSpan(1, pos, j$2)); + at += isRTL; + } + var nstart = j$2; + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) { + } + order.splice(at, 0, new BidiSpan(2, nstart, j$2)); + at += isRTL; + pos = j$2; + } else { + ++j$2; + } + } + if (pos < i$7) { + order.splice(at, 0, new BidiSpan(1, pos, i$7)); + } + } + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + } + return direction == "rtl" ? order.reverse() : order; + }; + }(); + function getOrder(line, direction) { + var order = line.order; + if (order == null) { + order = line.order = bidiOrdering(line.text, direction); + } + return order; + } + var noHandlers = []; + var on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false); + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f); + } else { + var map2 = emitter._handlers || (emitter._handlers = {}); + map2[type] = (map2[type] || noHandlers).concat(f); + } + }; + function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers; + } + function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false); + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f); + } else { + var map2 = emitter._handlers, arr = map2 && map2[type]; + if (arr) { + var index = indexOf(arr, f); + if (index > -1) { + map2[type] = arr.slice(0, index).concat(arr.slice(index + 1)); + } + } + } + } + function signal(emitter, type) { + var handlers = getHandlers(emitter, type); + if (!handlers.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2); + for (var i2 = 0; i2 < handlers.length; ++i2) { + handlers[i2].apply(null, args); + } + } + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") { + e = { type: e, preventDefault: function() { + this.defaultPrevented = true; + } }; + } + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) { + return; + } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i2 = 0; i2 < arr.length; ++i2) { + if (indexOf(set, arr[i2]) == -1) { + set.push(arr[i2]); + } + } + } + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0; + } + function eventMixin(ctor) { + ctor.prototype.on = function(type, f) { + on(this, type, f); + }; + ctor.prototype.off = function(type, f) { + off(this, type, f); + }; + } + function e_preventDefault(e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + } + function e_stopPropagation(e) { + if (e.stopPropagation) { + e.stopPropagation(); + } else { + e.cancelBubble = true; + } + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + function e_stop(e) { + e_preventDefault(e); + e_stopPropagation(e); + } + function e_target(e) { + return e.target || e.srcElement; + } + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) { + b = 1; + } else if (e.button & 2) { + b = 3; + } else if (e.button & 4) { + b = 2; + } + } + if (mac && e.ctrlKey && b == 1) { + b = 3; + } + return b; + } + var dragAndDrop = function() { + if (ie && ie_version < 9) { + return false; + } + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + }(); + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "​"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) { + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); + } + } + var node = zwspSupported ? elt("span", "​") : elt("span", " ", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) { + return badBidiRects; + } + var txt = removeChildrenAndAdd(measure, document.createTextNode("AخA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + var r1 = range(txt, 1, 2).getBoundingClientRect(); + removeChildren(measure); + if (!r0 || r0.left == r0.right) { + return false; + } + return badBidiRects = r1.right - r0.right < 3; + } + var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function(string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) { + nl = string.length; + } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function(string) { + return string.split(/\r\n?|\n/); + }; + var hasSelection = window.getSelection ? function(te) { + try { + return te.selectionStart != te.selectionEnd; + } catch (e) { + return false; + } + } : function(te) { + var range2; + try { + range2 = te.ownerDocument.selection.createRange(); + } catch (e) { + } + if (!range2 || range2.parentElement() != te) { + return false; + } + return range2.compareEndPoints("StartToEnd", range2) != 0; + }; + var hasCopyEvent = function() { + var e = elt("div"); + if ("oncopy" in e) { + return true; + } + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + }(); + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { + return badZoomedRects; + } + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + var modes = {}, mimeModes = {}; + function defineMode(name, mode) { + if (arguments.length > 2) { + mode.dependencies = Array.prototype.slice.call(arguments, 2); + } + modes[name] = mode; + } + function defineMIME(mime, spec) { + mimeModes[mime] = spec; + } + function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") { + found = { name: found }; + } + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml"); + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json"); + } + if (typeof spec == "string") { + return { name: spec }; + } else { + return spec || { name: "null" }; + } + } + function getMode(options, spec) { + spec = resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) { + return getMode(options, "text/plain"); + } + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop2 in exts) { + if (!exts.hasOwnProperty(prop2)) { + continue; + } + if (modeObj.hasOwnProperty(prop2)) { + modeObj["_" + prop2] = modeObj[prop2]; + } + modeObj[prop2] = exts[prop2]; + } + } + modeObj.name = spec.name; + if (spec.helperType) { + modeObj.helperType = spec.helperType; + } + if (spec.modeProps) { + for (var prop$1 in spec.modeProps) { + modeObj[prop$1] = spec.modeProps[prop$1]; + } + } + return modeObj; + } + var modeExtensions = {}; + function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {}; + copyObj(properties, exts); + } + function copyState(mode, state) { + if (state === true) { + return state; + } + if (mode.copyState) { + return mode.copyState(state); + } + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) { + val = val.concat([]); + } + nstate[n] = val; + } + return nstate; + } + function innerMode(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) { + break; + } + state = info.state; + mode = info.mode; + } + return info || { mode, state }; + } + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + var StringStream = function(string, tabSize, lineOracle) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.lineOracle = lineOracle; + }; + StringStream.prototype.eol = function() { + return this.pos >= this.string.length; + }; + StringStream.prototype.sol = function() { + return this.pos == this.lineStart; + }; + StringStream.prototype.peek = function() { + return this.string.charAt(this.pos) || void 0; + }; + StringStream.prototype.next = function() { + if (this.pos < this.string.length) { + return this.string.charAt(this.pos++); + } + }; + StringStream.prototype.eat = function(match) { + var ch = this.string.charAt(this.pos); + var ok; + if (typeof match == "string") { + ok = ch == match; + } else { + ok = ch && (match.test ? match.test(ch) : match(ch)); + } + if (ok) { + ++this.pos; + return ch; + } + }; + StringStream.prototype.eatWhile = function(match) { + var start = this.pos; + while (this.eat(match)) { + } + return this.pos > start; + }; + StringStream.prototype.eatSpace = function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { + ++this.pos; + } + return this.pos > start; + }; + StringStream.prototype.skipToEnd = function() { + this.pos = this.string.length; + }; + StringStream.prototype.skipTo = function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) { + this.pos = found; + return true; + } + }; + StringStream.prototype.backUp = function(n) { + this.pos -= n; + }; + StringStream.prototype.column = function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }; + StringStream.prototype.indentation = function() { + return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }; + StringStream.prototype.match = function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) { + return caseInsensitive ? str.toLowerCase() : str; + }; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) { + this.pos += pattern.length; + } + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) { + return null; + } + if (match && consume !== false) { + this.pos += match[0].length; + } + return match; + } + }; + StringStream.prototype.current = function() { + return this.string.slice(this.start, this.pos); + }; + StringStream.prototype.hideFirstChars = function(n, inner) { + this.lineStart += n; + try { + return inner(); + } finally { + this.lineStart -= n; + } + }; + StringStream.prototype.lookAhead = function(n) { + var oracle = this.lineOracle; + return oracle && oracle.lookAhead(n); + }; + StringStream.prototype.baseToken = function() { + var oracle = this.lineOracle; + return oracle && oracle.baseToken(this.pos); + }; + function getLine(doc2, n) { + n -= doc2.first; + if (n < 0 || n >= doc2.size) { + throw new Error("There is no line " + (n + doc2.first) + " in the document."); + } + var chunk = doc2; + while (!chunk.lines) { + for (var i2 = 0; ; ++i2) { + var child = chunk.children[i2], sz = child.chunkSize(); + if (n < sz) { + chunk = child; + break; + } + n -= sz; + } + } + return chunk.lines[n]; + } + function getBetween(doc2, start, end) { + var out = [], n = start.line; + doc2.iter(start.line, end.line + 1, function(line) { + var text = line.text; + if (n == end.line) { + text = text.slice(0, end.ch); + } + if (n == start.line) { + text = text.slice(start.ch); + } + out.push(text); + ++n; + }); + return out; + } + function getLines(doc2, from, to) { + var out = []; + doc2.iter(from, to, function(line) { + out.push(line.text); + }); + return out; + } + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) { + for (var n = line; n; n = n.parent) { + n.height += diff; + } + } + } + function lineNo(line) { + if (line.parent == null) { + return null; + } + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i2 = 0; ; ++i2) { + if (chunk.children[i2] == cur) { + break; + } + no += chunk.children[i2].chunkSize(); + } + } + return no + cur.first; + } + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) { + var child = chunk.children[i$12], ch = child.height; + if (h < ch) { + chunk = child; + continue outer; + } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + var i2 = 0; + for (; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2], lh = line.height; + if (h < lh) { + break; + } + h -= lh; + } + return n + i2; + } + function isLine(doc2, l) { + return l >= doc2.first && l < doc2.first + doc2.size; + } + function lineNumberFor(options, i2) { + return String(options.lineNumberFormatter(i2 + options.firstLineNumber)); + } + function Pos(line, ch, sticky) { + if (sticky === void 0) sticky = null; + if (!(this instanceof Pos)) { + return new Pos(line, ch, sticky); + } + this.line = line; + this.ch = ch; + this.sticky = sticky; + } + function cmp(a, b) { + return a.line - b.line || a.ch - b.ch; + } + function equalCursorPos(a, b) { + return a.sticky == b.sticky && cmp(a, b) == 0; + } + function copyPos(x) { + return Pos(x.line, x.ch); + } + function maxPos(a, b) { + return cmp(a, b) < 0 ? b : a; + } + function minPos(a, b) { + return cmp(a, b) < 0 ? a : b; + } + function clipLine(doc2, n) { + return Math.max(doc2.first, Math.min(n, doc2.first + doc2.size - 1)); + } + function clipPos(doc2, pos) { + if (pos.line < doc2.first) { + return Pos(doc2.first, 0); + } + var last = doc2.first + doc2.size - 1; + if (pos.line > last) { + return Pos(last, getLine(doc2, last).text.length); + } + return clipToLen(pos, getLine(doc2, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) { + return Pos(pos.line, linelen); + } else if (ch < 0) { + return Pos(pos.line, 0); + } else { + return pos; + } + } + function clipPosArray(doc2, array) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = clipPos(doc2, array[i2]); + } + return out; + } + var SavedContext = function(state, lookAhead) { + this.state = state; + this.lookAhead = lookAhead; + }; + var Context = function(doc2, state, line, lookAhead) { + this.state = state; + this.doc = doc2; + this.line = line; + this.maxLookAhead = lookAhead || 0; + this.baseTokens = null; + this.baseTokenPos = 1; + }; + Context.prototype.lookAhead = function(n) { + var line = this.doc.getLine(this.line + n); + if (line != null && n > this.maxLookAhead) { + this.maxLookAhead = n; + } + return line; + }; + Context.prototype.baseToken = function(n) { + if (!this.baseTokens) { + return null; + } + while (this.baseTokens[this.baseTokenPos] <= n) { + this.baseTokenPos += 2; + } + var type = this.baseTokens[this.baseTokenPos + 1]; + return { + type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n + }; + }; + Context.prototype.nextLine = function() { + this.line++; + if (this.maxLookAhead > 0) { + this.maxLookAhead--; + } + }; + Context.fromSaved = function(doc2, saved, line) { + if (saved instanceof SavedContext) { + return new Context(doc2, copyState(doc2.mode, saved.state), line, saved.lookAhead); + } else { + return new Context(doc2, copyState(doc2.mode, saved), line); + } + }; + Context.prototype.save = function(copy) { + var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state; + }; + function highlightLine(cm, line, context, forceToEnd) { + var st = [cm.state.modeGen], lineClasses = {}; + runMode( + cm, + line.text, + cm.doc.mode, + context, + function(end, style) { + return st.push(end, style); + }, + lineClasses, + forceToEnd + ); + var state = context.state; + var loop = function(o2) { + context.baseTokens = st; + var overlay = cm.state.overlays[o2], i2 = 1, at = 0; + context.state = true; + runMode(cm, line.text, overlay.mode, context, function(end, style) { + var start = i2; + while (at < end) { + var i_end = st[i2]; + if (i_end > end) { + st.splice(i2, 1, end, st[i2 + 1], i_end); + } + i2 += 2; + at = Math.min(end, i_end); + } + if (!style) { + return; + } + if (overlay.opaque) { + st.splice(start, i2 - start, end, "overlay " + style); + i2 = start + 2; + } else { + for (; start < i2; start += 2) { + var cur = st[start + 1]; + st[start + 1] = (cur ? cur + " " : "") + "overlay " + style; + } + } + }, lineClasses); + context.state = state; + context.baseTokens = null; + context.baseTokenPos = 1; + }; + for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); + return { styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null }; + } + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)); + var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); + var result = highlightLine(cm, line, context); + if (resetState) { + context.state = resetState; + } + line.stateAfter = context.save(!resetState); + line.styles = result.styles; + if (result.classes) { + line.styleClasses = result.classes; + } else if (line.styleClasses) { + line.styleClasses = null; + } + if (updateFrontier === cm.doc.highlightFrontier) { + cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); + } + } + return line.styles; + } + function getContextBefore(cm, n, precise) { + var doc2 = cm.doc, display = cm.display; + if (!doc2.mode.startState) { + return new Context(doc2, true, n); + } + var start = findStartLine(cm, n, precise); + var saved = start > doc2.first && getLine(doc2, start - 1).stateAfter; + var context = saved ? Context.fromSaved(doc2, saved, start) : new Context(doc2, startState(doc2.mode), start); + doc2.iter(start, n, function(line) { + processLine(cm, line.text, context); + var pos = context.line; + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; + context.nextLine(); + }); + if (precise) { + doc2.modeFrontier = context.line; + } + return context; + } + function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize, context); + stream.start = stream.pos = startAt || 0; + if (text == "") { + callBlankLine(mode, context.state); + } + while (!stream.eol()) { + readToken(mode, stream, context.state); + stream.start = stream.pos; + } + } + function callBlankLine(mode, state) { + if (mode.blankLine) { + return mode.blankLine(state); + } + if (!mode.innerMode) { + return; + } + var inner = innerMode(mode, state); + if (inner.mode.blankLine) { + return inner.mode.blankLine(inner.state); + } + } + function readToken(mode, stream, state, inner) { + for (var i2 = 0; i2 < 10; i2++) { + if (inner) { + inner[0] = innerMode(mode, state).mode; + } + var style = mode.token(stream, state); + if (stream.pos > stream.start) { + return style; + } + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + var Token = function(stream, type, state) { + this.start = stream.start; + this.end = stream.pos; + this.string = stream.current(); + this.type = type || null; + this.state = state; + }; + function takeToken(cm, pos, precise, asArray) { + var doc2 = cm.doc, mode = doc2.mode, style; + pos = clipPos(doc2, pos); + var line = getLine(doc2, pos.line), context = getContextBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; + if (asArray) { + tokens = []; + } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, context.state); + if (asArray) { + tokens.push(new Token(stream, style, copyState(doc2.mode, context.state))); + } + } + return asArray ? tokens : new Token(stream, style, context.state); + } + function extractLineClasses(type, output) { + if (type) { + for (; ; ) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) { + break; + } + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop2 = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop2] == null) { + output[prop2] = lineClass[2]; + } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop2])) { + output[prop2] += " " + lineClass[2]; + } + } + } + return type; + } + function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) { + flattenSpans = cm.options.flattenSpans; + } + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize, context), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") { + extractLineClasses(callBlankLine(mode, context.state), lineClasses); + } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) { + processLine(cm, text, context, stream.pos); + } + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) { + style = "m-" + (style ? mName + " " + style : mName); + } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5e3); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + var pos = Math.min(stream.pos, curStart + 5e3); + f(pos, curStyle); + curStart = pos; + } + } + function findStartLine(cm, n, precise) { + var minindent, minline, doc2 = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc2.first) { + return doc2.first; + } + var line = getLine(doc2, search - 1), after = line.stateAfter; + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc2.modeFrontier)) { + return search; + } + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + function retreatFrontier(doc2, n) { + doc2.modeFrontier = Math.min(doc2.modeFrontier, n); + if (doc2.highlightFrontier < n - 10) { + return; + } + var start = doc2.first; + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc2, line).stateAfter; + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1; + break; + } + } + doc2.highlightFrontier = Math.min(doc2.highlightFrontier, start); + } + var sawReadOnlySpans = false, sawCollapsedSpans = false; + function seeReadOnlySpans() { + sawReadOnlySpans = true; + } + function seeCollapsedSpans() { + sawCollapsedSpans = true; + } + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; + this.to = to; + } + function getMarkedSpanFor(spans, marker) { + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.marker == marker) { + return span; + } + } + } + } + function removeMarkedSpan(spans, span) { + var r; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2] != span) { + (r || (r = [])).push(spans[i2]); + } + } + return r; + } + function addMarkedSpan(line, span, op) { + var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = /* @__PURE__ */ new WeakSet())); + if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { + line.markedSpans.push(span); + } else { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + if (inThisOp) { + inThisOp.add(line.markedSpans); + } + } + span.marker.attachLine(line); + } + function markedSpansBefore(old, startCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan( + marker, + startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh + )); + } + } + } + return nw; + } + function stretchSpansOverChange(doc2, change) { + if (change.full) { + return null; + } + var oldFirst = isLine(doc2, change.from.line) && getLine(doc2, change.from.line).markedSpans; + var oldLast = isLine(doc2, change.to.line) && getLine(doc2, change.to.line).markedSpans; + if (!oldFirst && !oldLast) { + return null; + } + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + for (var i2 = 0; i2 < first.length; ++i2) { + var span = first[i2]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) { + span.to = startCh; + } else if (sameLine) { + span.to = found.to == null ? null : found.to + offset; + } + } + } + } + if (last) { + for (var i$12 = 0; i$12 < last.length; ++i$12) { + var span$1 = last[i$12]; + if (span$1.to != null) { + span$1.to += offset; + } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker); + if (!found$1) { + span$1.from = offset; + if (sameLine) { + (first || (first = [])).push(span$1); + } + } + } else { + span$1.from += offset; + if (sameLine) { + (first || (first = [])).push(span$1); + } + } + } + } + if (first) { + first = clearEmptySpans(first); + } + if (last && last != first) { + last = clearEmptySpans(last); + } + var newMarkers = [first]; + if (!sameLine) { + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) { + for (var i$22 = 0; i$22 < first.length; ++i$22) { + if (first[i$22].to == null) { + (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null)); + } + } + } + for (var i$3 = 0; i$3 < gap; ++i$3) { + newMarkers.push(gapMarkers); + } + newMarkers.push(last); + } + return newMarkers; + } + function clearEmptySpans(spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { + spans.splice(i2--, 1); + } + } + if (!spans.length) { + return null; + } + return spans; + } + function removeReadOnlyRanges(doc2, from, to) { + var markers = null; + doc2.iter(from.line, to.line + 1, function(line) { + if (line.markedSpans) { + for (var i3 = 0; i3 < line.markedSpans.length; ++i3) { + var mark = line.markedSpans[i3].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { + (markers || (markers = [])).push(mark); + } + } + } + }); + if (!markers) { + return null; + } + var parts = [{ from, to }]; + for (var i2 = 0; i2 < markers.length; ++i2) { + var mk = markers[i2], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { + continue; + } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { + newParts.push({ from: p.from, to: m.from }); + } + if (dto > 0 || !mk.inclusiveRight && !dto) { + newParts.push({ from: m.to, to: p.to }); + } + parts.splice.apply(parts, newParts); + j += newParts.length - 3; + } + } + return parts; + } + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.detachLine(line); + } + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.attachLine(line); + } + line.markedSpans = spans; + } + function extraLeft(marker) { + return marker.inclusiveLeft ? -1 : 0; + } + function extraRight(marker) { + return marker.inclusiveRight ? 1 : 0; + } + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) { + return lenDiff; + } + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) { + return -fromCmp; + } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) { + return toCmp; + } + return b.id - a.id; + } + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { + found = sp.marker; + } + } + } + return found; + } + function collapsedSpanAtStart(line) { + return collapsedSpanAtSide(line, true); + } + function collapsedSpanAtEnd(line) { + return collapsedSpanAtSide(line, false); + } + function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { + found = sp.marker; + } + } + } + return found; + } + function conflictingCollapsedRange(doc2, lineNo2, from, to, marker) { + var line = getLine(doc2, lineNo2); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; + } + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { + continue; + } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { + return true; + } + } + } + } + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) { + line = merged.find(-1, true).line; + } + return line; + } + function visualLineEnd(line) { + var merged; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + } + return line; + } + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + function visualLineNo(doc2, lineN) { + var line = getLine(doc2, lineN), vis = visualLine(line); + if (line == vis) { + return lineN; + } + return lineNo(vis); + } + function visualLineEndNo(doc2, lineN) { + if (lineN > doc2.lastLine()) { + return lineN; + } + var line = getLine(doc2, lineN), merged; + if (!lineIsHidden(doc2, line)) { + return lineN; + } + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + } + return lineNo(line) + 1; + } + function lineIsHidden(doc2, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; + } + if (sp.from == null) { + return true; + } + if (sp.marker.widgetNode) { + continue; + } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc2, line, sp)) { + return true; + } + } + } + } + function lineIsHiddenInner(doc2, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc2, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) { + return true; + } + for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) { + sp = line.markedSpans[i2]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc2, line, sp)) { + return true; + } + } + } + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + var h = 0, chunk = lineObj.parent; + for (var i2 = 0; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2]; + if (line == lineObj) { + break; + } else { + h += line.height; + } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$12 = 0; i$12 < p.children.length; ++i$12) { + var cur = p.children[i$12]; + if (cur == chunk) { + break; + } else { + h += cur.height; + } + } + } + return h; + } + function lineLength(line) { + if (line.height == 0) { + return 0; + } + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true); + len -= cur.text.length - found$1.from.ch; + cur = found$1.to.line; + len += cur.text.length - found$1.to.ch; + } + return len; + } + function findMaxLine(cm) { + var d = cm.display, doc2 = cm.doc; + d.maxLine = getLine(doc2, doc2.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc2.iter(function(line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + var Line = function(text, markedSpans, estimateHeight2) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight2 ? estimateHeight2(this) : 1; + }; + Line.prototype.lineNo = function() { + return lineNo(this); + }; + eventMixin(Line); + function updateLine(line, text, markedSpans, estimateHeight2) { + line.text = text; + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + if (line.order != null) { + line.order = null; + } + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight2 ? estimateHeight2(line) : 1; + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + } + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { + return null; + } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + function buildLineContent(cm, lineView) { + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = { + pre: eltP("pre", [content], "CodeMirror-line"), + content, + col: 0, + pos: 0, + cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping") + }; + lineView.measure = {}; + for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) { + var line = i2 ? lineView.rest[i2 - 1] : lineView.line, order = void 0; + builder.pos = 0; + builder.addToken = buildToken; + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { + builder.addToken = buildTokenBadBidi(builder.addToken, order); + } + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) { + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); + } + if (line.styleClasses.textClass) { + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); + } + } + if (builder.map.length == 0) { + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); + } + if (i2 == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + if (webkit) { + var last = builder.content.lastChild; + if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) { + builder.content.className = "cm-tab-wrap-hack"; + } + } + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) { + builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); + } + return builder; + } + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "•", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + function buildToken(builder, text, style, startStyle, endStyle, css2, attributes) { + if (!text) { + return; + } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + var content; + if (!special.test(text)) { + builder.col += text.length; + content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) { + mustWrap = true; + } + builder.pos += text.length; + } else { + content = document.createDocumentFragment(); + var pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt])); + } else { + content.appendChild(txt); + } + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) { + break; + } + pos += skipped + 1; + var txt$1 = void 0; + if (m[0] == " ") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt$1.setAttribute("role", "presentation"); + txt$1.setAttribute("cm-text", " "); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar")); + txt$1.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); + txt$1.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt$1])); + } else { + content.appendChild(txt$1); + } + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt$1); + builder.pos++; + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; + if (style || startStyle || endStyle || mustWrap || css2 || attributes) { + var fullStyle = style || ""; + if (startStyle) { + fullStyle += startStyle; + } + if (endStyle) { + fullStyle += endStyle; + } + var token = elt("span", [content], fullStyle, css2); + if (attributes) { + for (var attr in attributes) { + if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { + token.setAttribute(attr, attributes[attr]); + } + } + } + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { + return text; + } + var spaceBefore = trailingBefore, result = ""; + for (var i2 = 0; i2 < text.length; i2++) { + var ch = text.charAt(i2); + if (ch == " " && spaceBefore && (i2 == text.length - 1 || text.charCodeAt(i2 + 1) == 32)) { + ch = " "; + } + result += ch; + spaceBefore = ch == " "; + } + return result; + } + function buildTokenBadBidi(inner, order) { + return function(builder, text, style, startStyle, endStyle, css2, attributes) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (; ; ) { + var part = void 0; + for (var i2 = 0; i2 < order.length; i2++) { + part = order[i2]; + if (part.to > start && part.from <= start) { + break; + } + } + if (part.to >= end) { + return inner(builder, text, style, startStyle, endStyle, css2, attributes); + } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, css2, attributes); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) { + builder.map.push(builder.pos, builder.pos + size, widget); + } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) { + widget = builder.content.appendChild(document.createElement("span")); + } + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + builder.trailingSpace = false; + } + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i$12 = 1; i$12 < styles.length; i$12 += 2) { + builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options)); + } + return; + } + var len = allText.length, pos = 0, i2 = 1, text = "", style, css2; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; + for (; ; ) { + if (nextChange == pos) { + spanStyle = spanEndStyle = spanStartStyle = css2 = ""; + attributes = null; + collapsed = null; + nextChange = Infinity; + var foundBookmarks = [], endStyles = void 0; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) { + spanStyle += " " + m.className; + } + if (m.css) { + css2 = (css2 ? css2 + ";" : "") + m.css; + } + if (m.startStyle && sp.from == pos) { + spanStartStyle += " " + m.startStyle; + } + if (m.endStyle && sp.to == nextChange) { + (endStyles || (endStyles = [])).push(m.endStyle, sp.to); + } + if (m.title) { + (attributes || (attributes = {})).title = m.title; + } + if (m.attributes) { + for (var attr in m.attributes) { + (attributes || (attributes = {}))[attr] = m.attributes[attr]; + } + } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { + collapsed = sp; + } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (endStyles) { + for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { + if (endStyles[j$1 + 1] == nextChange) { + spanEndStyle += " " + endStyles[j$1]; + } + } + } + if (!collapsed || collapsed.from == pos) { + for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { + buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan( + builder, + (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, + collapsed.from == null + ); + if (collapsed.to == null) { + return; + } + if (collapsed.to == pos) { + collapsed = false; + } + } + } + if (pos >= len) { + break; + } + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken( + builder, + tokenText, + style ? style + spanStyle : spanStyle, + spanStartStyle, + pos + tokenText.length == nextChange ? spanEndStyle : "", + css2, + attributes + ); + } + if (end >= upto) { + text = text.slice(upto - pos); + pos = upto; + break; + } + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i2++]); + style = interpretTokenStyle(styles[i2++], builder.cm.options); + } + } + } + function LineView(doc2, line, lineN) { + this.line = line; + this.rest = visualLineContinued(line); + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc2, line); + } + function buildViewArray(cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + var operationGroup = null; + function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op); + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + }; + } + } + function fireCallbacksForOps(group) { + var callbacks = group.delayedCallbacks, i2 = 0; + do { + for (; i2 < callbacks.length; i2++) { + callbacks[i2].call(null); + } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); + } + } + } + } while (i2 < callbacks.length); + } + function finishOperation(op, endCb) { + var group = op.ownsGroup; + if (!group) { + return; + } + try { + fireCallbacksForOps(group); + } finally { + operationGroup = null; + endCb(group); + } + } + var orphanDelayedCallbacks = null; + function signalLater(emitter, type) { + var arr = getHandlers(emitter, type); + if (!arr.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + var loop = function(i3) { + list.push(function() { + return arr[i3].apply(null, args); + }); + }; + for (var i2 = 0; i2 < arr.length; ++i2) + loop(i2); + } + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i2 = 0; i2 < delayed.length; ++i2) { + delayed[i2](); + } + } + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") { + updateLineText(cm, lineView); + } else if (type == "gutter") { + updateLineGutter(cm, lineView, lineN, dims); + } else if (type == "class") { + updateLineClasses(cm, lineView); + } else if (type == "widget") { + updateLineWidgets(cm, lineView, dims); + } + } + lineView.changes = null; + } + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) { + lineView.text.parentNode.replaceChild(lineView.node, lineView.text); + } + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) { + lineView.node.style.zIndex = 2; + } + } + return lineView.node; + } + function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) { + cls += " CodeMirror-linebackground"; + } + if (lineView.background) { + if (cls) { + lineView.background.className = cls; + } else { + lineView.background.parentNode.removeChild(lineView.background); + lineView.background = null; + } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + cm.display.input.setUneditable(lineView.background); + } + } + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) { + lineView.node = built.pre; + } + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(cm, lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView); + if (lineView.line.wrapClass) { + ensureLineWrapped(lineView).className = lineView.line.wrapClass; + } else if (lineView.node != lineView.text) { + lineView.node.className = ""; + } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt( + "div", + null, + "CodeMirror-gutter-background " + lineView.line.gutterClass, + "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px" + ); + cm.display.input.setUneditable(lineView.gutterBackground); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); + gutterWrap.setAttribute("aria-hidden", "true"); + cm.display.input.setUneditable(gutterWrap); + wrap$1.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) { + gutterWrap.className += " " + lineView.line.gutterClass; + } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { + lineView.lineNumber = gutterWrap.appendChild( + elt( + "div", + lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px" + ) + ); + } + if (markers) { + for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { + var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild(elt( + "div", + [found], + "CodeMirror-gutter-elt", + "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px" + )); + } + } + } + } + } + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { + lineView.alignable = null; + } + var isWidget = classTest("CodeMirror-linewidget"); + for (var node = lineView.node.firstChild, next = void 0; node; node = next) { + next = node.nextSibling; + if (isWidget.test(node.className)) { + lineView.node.removeChild(node); + } + } + insertLineWidgets(cm, lineView, dims); + } + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) { + lineView.bgClass = built.bgClass; + } + if (built.textClass) { + lineView.textClass = built.textClass; + } + updateLineClasses(cm, lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false); + } + } + } + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { + return; + } + var wrap = ensureLineWrapped(lineView); + for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) { + var widget = ws[i2], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); + if (!widget.handleMouseEvents) { + node.setAttribute("cm-ignore-events", "true"); + } + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) { + wrap.insertBefore(node, lineView.gutter || lineView.text); + } else { + wrap.appendChild(node); + } + signalLater(widget, "redraw"); + } + } + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) { + node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + } + function widgetHeight(widget) { + if (widget.height != null) { + return widget.height; + } + var cm = widget.doc.cm; + if (!cm) { + return 0; + } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) { + parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; + } + if (widget.noHScroll) { + parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.parentNode.offsetHeight; + } + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) { + return true; + } + } + } + function paddingTop(display) { + return display.lineSpace.offsetTop; + } + function paddingVert(display) { + return display.mover.offsetHeight - display.lineSpace.offsetHeight; + } + function paddingH(display) { + if (display.cachedPaddingH) { + return display.cachedPaddingH; + } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = { left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight) }; + if (!isNaN(data.left) && !isNaN(data.right)) { + display.cachedPaddingH = data; + } + return data; + } + function scrollGap(cm) { + return scrollerGap - cm.display.nativeBarWidth; + } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i2 = 0; i2 < rects.length - 1; i2++) { + var cur = rects[i2], next = rects[i2 + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) { + heights.push((cur.bottom + next.top) / 2 - rect.top); + } + } + } + heights.push(rect.bottom - rect.top); + } + } + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) { + return { map: lineView.measure.map, cache: lineView.measure.cache }; + } + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + if (lineView.rest[i2] == line) { + return { map: lineView.measure.maps[i2], cache: lineView.measure.caches[i2] }; + } + } + for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) { + if (lineNo(lineView.rest[i$12]) > lineN) { + return { map: lineView.measure.maps[i$12], cache: lineView.measure.caches[i$12], before: true }; + } + } + } + } + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { + return cm.display.view[findViewIndex(cm, lineN)]; + } + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { + return ext; + } + } + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) { + view = updateExternalMeasurement(cm, line); + } + var info = mapFromLineView(view, line, lineN); + return { + line, + view, + rect: null, + map: info.map, + cache: info.cache, + before: info.before, + hasHeights: false + }; + } + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { + ch = -1; + } + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) { + prepared.rect = prepared.view.text.getBoundingClientRect(); + } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) { + prepared.cache[key] = found; + } + } + return { + left: found.left, + right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom + }; + } + var nullRect = { left: 0, right: 0, top: 0, bottom: 0 }; + function nodeAndOffsetInLineMap(map2, ch, bias) { + var node, start, end, collapse, mStart, mEnd; + for (var i2 = 0; i2 < map2.length; i2 += 3) { + mStart = map2[i2]; + mEnd = map2[i2 + 1]; + if (ch < mStart) { + start = 0; + end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i2 == map2.length - 3 || ch == mEnd && map2[i2 + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) { + collapse = "right"; + } + } + if (start != null) { + node = map2[i2 + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { + collapse = bias; + } + if (bias == "left" && start == 0) { + while (i2 && map2[i2 - 2] == map2[i2 - 3] && map2[i2 - 1].insertLeft) { + node = map2[(i2 -= 3) + 2]; + collapse = "left"; + } + } + if (bias == "right" && start == mEnd - mStart) { + while (i2 < map2.length - 3 && map2[i2 + 3] == map2[i2 + 4] && !map2[i2 + 5].insertLeft) { + node = map2[(i2 += 3) + 2]; + collapse = "right"; + } + } + break; + } + } + return { node, start, end, collapse, coverStart: mStart, coverEnd: mEnd }; + } + function getUsefulRect(rects, bias) { + var rect = nullRect; + if (bias == "left") { + for (var i2 = 0; i2 < rects.length; i2++) { + if ((rect = rects[i2]).left != rect.right) { + break; + } + } + } else { + for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) { + if ((rect = rects[i$12]).left != rect.right) { + break; + } + } + } + return rect; + } + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + var rect; + if (node.nodeType == 3) { + for (var i$12 = 0; i$12 < 4; i$12++) { + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { + --start; + } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { + ++end; + } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else { + rect = getUsefulRect(range(node, start, end).getClientRects(), bias); + } + if (rect.left || rect.right || start == 0) { + break; + } + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) { + rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } + } else { + if (start > 0) { + collapse = bias = "right"; + } + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { + rect = rects[bias == "right" ? rects.length - 1 : 0]; + } else { + rect = node.getBoundingClientRect(); + } + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) { + rect = { left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom }; + } else { + rect = nullRect; + } + } + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + var i2 = 0; + for (; i2 < heights.length - 1; i2++) { + if (mid < heights[i2]) { + break; + } + } + var top = i2 ? heights[i2 - 1] : 0, bot = heights[i2]; + var result = { + left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top, + bottom: bot + }; + if (!rect.left && !rect.right) { + result.bogus = true; + } + if (!cm.options.singleCursorHeightPerLine) { + result.rtop = rtop; + result.rbottom = rbot; + } + return result; + } + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { + return rect; + } + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return { + left: rect.left * scaleX, + right: rect.right * scaleX, + top: rect.top * scaleY, + bottom: rect.bottom * scaleY + }; + } + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + lineView.measure.caches[i2] = {}; + } + } + } + } + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + clearLineMeasurementCacheFor(cm.display.view[i2]); + } + } + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) { + cm.display.maxLineChanged = true; + } + cm.display.lineNumChars = null; + } + function pageScrollX(doc2) { + if (chrome && android) { + return -(doc2.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc2.body).marginLeft)); + } + return doc2.defaultView.pageXOffset || (doc2.documentElement || doc2.body).scrollLeft; + } + function pageScrollY(doc2) { + if (chrome && android) { + return -(doc2.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc2.body).marginTop)); + } + return doc2.defaultView.pageYOffset || (doc2.documentElement || doc2.body).scrollTop; + } + function widgetTopHeight(lineObj) { + var ref = visualLine(lineObj); + var widgets = ref.widgets; + var height = 0; + if (widgets) { + for (var i2 = 0; i2 < widgets.length; ++i2) { + if (widgets[i2].above) { + height += widgetHeight(widgets[i2]); + } + } + } + return height; + } + function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj); + rect.top += height; + rect.bottom += height; + } + if (context == "line") { + return rect; + } + if (!context) { + context = "local"; + } + var yOff = heightAtLine(lineObj); + if (context == "local") { + yOff += paddingTop(cm.display); + } else { + yOff -= cm.display.viewOffset; + } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm))); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm))); + rect.left += xOff; + rect.right += xOff; + } + rect.top += yOff; + rect.bottom += yOff; + return rect; + } + function fromCoordSystem(cm, coords, context) { + if (context == "div") { + return coords; + } + var left = coords.left, top = coords.top; + if (context == "page") { + left -= pageScrollX(doc(cm)); + top -= pageScrollY(doc(cm)); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return { left: left - lineSpaceBox.left, top: top - lineSpaceBox.top }; + } + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { + lineObj = getLine(cm.doc, pos.line); + } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + function get(ch2, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch2, right ? "right" : "left", varHeight); + if (right) { + m.left = m.right; + } else { + m.right = m.left; + } + return intoCoordSystem(cm, lineObj, m, context); + } + var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; + if (ch >= lineObj.text.length) { + ch = lineObj.text.length; + sticky = "before"; + } else if (ch <= 0) { + ch = 0; + sticky = "after"; + } + if (!order) { + return get(sticky == "before" ? ch - 1 : ch, sticky == "before"); + } + function getBidi(ch2, partPos2, invert) { + var part = order[partPos2], right = part.level == 1; + return get(invert ? ch2 - 1 : ch2, right != invert); + } + var partPos = getBidiPartAt(order, ch, sticky); + var other = bidiOther; + var val = getBidi(ch, partPos, sticky == "before"); + if (other != null) { + val.other = getBidi(ch, other, sticky != "before"); + } + return val; + } + function estimateCoords(cm, pos) { + var left = 0; + pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) { + left = charWidth(cm.display) * pos.ch; + } + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return { left, right: left, top, bottom: top + lineObj.height }; + } + function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky); + pos.xRel = xRel; + if (outside) { + pos.outside = outside; + } + return pos; + } + function coordsChar(cm, x, y) { + var doc2 = cm.doc; + y += cm.display.viewOffset; + if (y < 0) { + return PosWithInfo(doc2.first, 0, null, -1, -1); + } + var lineN = lineAtHeight(doc2, y), last = doc2.first + doc2.size - 1; + if (lineN > last) { + return PosWithInfo(doc2.first + doc2.size - 1, getLine(doc2, last).text.length, null, 1, 1); + } + if (x < 0) { + x = 0; + } + var lineObj = getLine(doc2, lineN); + for (; ; ) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); + if (!collapsed) { + return found; + } + var rangeEnd = collapsed.find(1); + if (rangeEnd.line == lineN) { + return rangeEnd; + } + lineObj = getLine(doc2, lineN = rangeEnd.line); + } + } + function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj); + var end = lineObj.text.length; + var begin = findFirst(function(ch) { + return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; + }, end, 0); + end = findFirst(function(ch) { + return measureCharPrepared(cm, preparedMeasure, ch).top > y; + }, begin, end); + return { begin, end }; + } + function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop); + } + function boxIsAfter(box, x, y, left) { + return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x; + } + function coordsCharInner(cm, lineObj, lineNo2, x, y) { + y -= heightAtLine(lineObj); + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + var widgetHeight2 = widgetTopHeight(lineObj); + var begin = 0, end = lineObj.text.length, ltr = true; + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x, y); + ltr = part.level != 1; + begin = ltr ? part.from : part.to - 1; + end = ltr ? part.to : part.from - 1; + } + var chAround = null, boxAround = null; + var ch = findFirst(function(ch2) { + var box = measureCharPrepared(cm, preparedMeasure, ch2); + box.top += widgetHeight2; + box.bottom += widgetHeight2; + if (!boxIsAfter(box, x, y, false)) { + return false; + } + if (box.top <= y && box.left <= x) { + chAround = ch2; + boxAround = box; + } + return true; + }, begin, end); + var baseX, sticky, outside = false; + if (boxAround) { + var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; + ch = chAround + (atStart ? 0 : 1); + sticky = atStart ? "after" : "before"; + baseX = atLeft ? boxAround.left : boxAround.right; + } else { + if (!ltr && (ch == end || ch == begin)) { + ch++; + } + sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y == ltr ? "after" : "before"; + var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure); + baseX = coords.left; + outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + } + ch = skipExtendingChars(lineObj.text, ch, 1); + return PosWithInfo(lineNo2, ch, sticky, outside, x - baseX); + } + function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x, y) { + var index = findFirst(function(i2) { + var part2 = order[i2], ltr2 = part2.level != 1; + return boxIsAfter(cursorCoords( + cm, + Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"), + "line", + lineObj, + preparedMeasure + ), x, y, true); + }, 0, order.length - 1); + var part = order[index]; + if (index > 0) { + var ltr = part.level != 1; + var start = cursorCoords( + cm, + Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"), + "line", + lineObj, + preparedMeasure + ); + if (boxIsAfter(start, x, y, true) && start.top > y) { + part = order[index - 1]; + } + } + return part; + } + function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { + end--; + } + var part = null, closestDist = null; + for (var i2 = 0; i2 < order.length; i2++) { + var p = order[i2]; + if (p.from >= end || p.to <= begin) { + continue; + } + var ltr = p.level != 1; + var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; + var dist = endX < x ? x - endX + 1e9 : endX - x; + if (!part || closestDist > dist) { + part = p; + closestDist = dist; + } + } + if (!part) { + part = order[order.length - 1]; + } + if (part.from < begin) { + part = { from: begin, to: part.to, level: part.level }; + } + if (part.to > end) { + part = { from: part.from, to: end, level: part.level }; + } + return part; + } + var measureText; + function textHeight(display) { + if (display.cachedTextHeight != null) { + return display.cachedTextHeight; + } + if (measureText == null) { + measureText = elt("pre", null, "CodeMirror-line-like"); + for (var i2 = 0; i2 < 49; ++i2) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) { + display.cachedTextHeight = height; + } + removeChildren(display.measure); + return height || 1; + } + function charWidth(display) { + if (display.cachedCharWidth != null) { + return display.cachedCharWidth; + } + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor], "CodeMirror-line-like"); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) { + display.cachedCharWidth = width; + } + return width || 10; + } + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) { + var id = cm.display.gutterSpecs[i2].className; + left[id] = n.offsetLeft + n.clientLeft + gutterLeft; + width[id] = n.clientWidth; + } + return { + fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth + }; + } + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function(line) { + if (lineIsHidden(cm.doc, line)) { + return 0; + } + var widgetsHeight = 0; + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].height) { + widgetsHeight += line.widgets[i2].height; + } + } + } + if (wrapping) { + return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + } else { + return widgetsHeight + th; + } + }; + } + function estimateLineHeights(cm) { + var doc2 = cm.doc, est = estimateHeight(cm); + doc2.iter(function(line) { + var estHeight = est(line); + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + }); + } + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { + return null; + } + var x, y, space = display.lineSpace.getBoundingClientRect(); + try { + x = e.clientX - space.left; + y = e.clientY - space.top; + } catch (e$1) { + return null; + } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { + return null; + } + n -= cm.display.viewFrom; + if (n < 0) { + return null; + } + var view = cm.display.view; + for (var i2 = 0; i2 < view.length; i2++) { + n -= view[i2].size; + if (n < 0) { + return i2; + } + } + } + function regChange(cm, from, to, lendiff) { + if (from == null) { + from = cm.doc.first; + } + if (to == null) { + to = cm.doc.first + cm.doc.size; + } + if (!lendiff) { + lendiff = 0; + } + var display = cm.display; + if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { + display.updateLineNumbers = from; + } + cm.curOp.viewChanged = true; + if (from >= display.viewTo) { + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { + resetView(cm); + } + } else if (to <= display.viewFrom) { + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { + resetView(cm); + } else if (from <= display.viewFrom) { + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { + var cut$1 = viewCuttingPoint(cm, from, from, -1); + if (cut$1) { + display.view = display.view.slice(0, cut$1.index); + display.viewTo = cut$1.lineN; + } else { + resetView(cm); + } + } else { + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) { + ext.lineN += lendiff; + } else if (from < ext.lineN + ext.size) { + display.externalMeasured = null; + } + } + } + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { + display.externalMeasured = null; + } + if (line < display.viewFrom || line >= display.viewTo) { + return; + } + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) { + return; + } + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) { + arr.push(type); + } + } + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { + return { index, lineN: newN }; + } + var n = cm.display.viewFrom; + for (var i2 = 0; i2 < index; i2++) { + n += view[i2].size; + } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { + return null; + } + diff = n + view[index].size - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; + newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { + return null; + } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return { index, lineN: newN }; + } + function adjustView(cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) { + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); + } else if (display.viewFrom < from) { + display.view = display.view.slice(findViewIndex(cm, from)); + } + display.viewFrom = from; + if (display.viewTo < to) { + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); + } else if (display.viewTo > to) { + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + } + display.viewTo = to; + } + function countDirtyView(cm) { + var view = cm.display.view, dirty = 0; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) { + ++dirty; + } + } + return dirty; + } + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + function prepareSelection(cm, primary) { + if (primary === void 0) primary = true; + var doc2 = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + var customCursor = cm.options.$customCursor; + if (customCursor) { + primary = true; + } + for (var i2 = 0; i2 < doc2.sel.ranges.length; i2++) { + if (!primary && i2 == doc2.sel.primIndex) { + continue; + } + var range2 = doc2.sel.ranges[i2]; + if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) { + continue; + } + var collapsed = range2.empty(); + if (customCursor) { + var head = customCursor(cm, range2); + if (head) { + drawSelectionCursor(cm, head, curFragment); + } + } else if (collapsed || cm.options.showCursorWhenSelecting) { + drawSelectionCursor(cm, range2.head, curFragment); + } + if (!collapsed) { + drawSelectionRange(cm, range2, selFragment); + } + } + return result; + } + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + var cursor = output.appendChild(elt("div", " ", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { + var charPos = charCoords(cm, head, "div", null, null); + var width = charPos.right - charPos.left; + cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; + } + if (pos.other) { + var otherCursor = output.appendChild(elt("div", " ", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px"; + } + } + function cmpCoords(a, b) { + return a.top - b.top || a.left - b.left; + } + function drawSelectionRange(cm, range2, output) { + var display = cm.display, doc2 = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + var docLTR = doc2.direction == "ltr"; + function add(left, top, width, bottom) { + if (top < 0) { + top = 0; + } + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")); + } + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc2, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos); + var prop2 = dir == "ltr" == (side == "after") ? "left" : "right"; + var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); + return coords(ch, prop2)[prop2]; + } + var order = getOrder(lineObj, doc2.direction); + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir, i2) { + var ltr = dir == "ltr"; + var fromPos = coords(from, ltr ? "left" : "right"); + var toPos = coords(to - 1, ltr ? "right" : "left"); + var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; + var first = i2 == 0, last = !order || i2 == order.length - 1; + if (toPos.top - fromPos.top <= 3) { + var openLeft = (docLTR ? openStart : openEnd) && first; + var openRight = (docLTR ? openEnd : openStart) && last; + var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; + var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; + add(left, fromPos.top, right - left, fromPos.bottom); + } else { + var topLeft, topRight, botLeft, botRight; + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left; + topRight = docLTR ? rightSide : wrapX(from, dir, "before"); + botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); + botRight = docLTR && openEnd && last ? rightSide : toPos.right; + } else { + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); + topRight = !docLTR && openStart && first ? rightSide : fromPos.right; + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; + botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); + } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); + if (fromPos.bottom < toPos.top) { + add(leftSide, fromPos.bottom, null, toPos.top); + } + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); + } + if (!start || cmpCoords(fromPos, start) < 0) { + start = fromPos; + } + if (cmpCoords(toPos, start) < 0) { + start = toPos; + } + if (!end || cmpCoords(fromPos, end) < 0) { + end = fromPos; + } + if (cmpCoords(toPos, end) < 0) { + end = toPos; + } + }); + return { start, end }; + } + var sFrom = range2.from(), sTo = range2.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc2, sFrom.line), toLine = getLine(doc2, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) { + add(leftSide, leftEnd.bottom, null, rightStart.top); + } + } + output.appendChild(fragment); + } + function restartBlink(cm) { + if (!cm.state.focused) { + return; + } + var display = cm.display; + clearInterval(display.blinker); + var on2 = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function() { + if (!cm.hasFocus()) { + onBlur(cm); + } + display.cursorDiv.style.visibility = (on2 = !on2) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) { + display.cursorDiv.style.visibility = "hidden"; + } + } + function ensureFocus(cm) { + if (!cm.hasFocus()) { + cm.display.input.focus(); + if (!cm.state.focused) { + onFocus(cm); + } + } + } + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function() { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + if (cm.state.focused) { + onBlur(cm); + } + } + }, 100); + } + function onFocus(cm, e) { + if (cm.state.delayingBlurEvent && !cm.state.draggingText) { + cm.state.delayingBlurEvent = false; + } + if (cm.options.readOnly == "nocursor") { + return; + } + if (!cm.state.focused) { + signal(cm, "focus", cm, e); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) { + setTimeout(function() { + return cm.display.input.reset(true); + }, 20); + } + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { + return; + } + if (cm.state.focused) { + signal(cm, "blur", cm, e); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function() { + if (!cm.state.focused) { + cm.display.shift = false; + } + }, 150); + } + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); + var oldHeight = display.lineDiv.getBoundingClientRect().top; + var mustScroll = 0; + for (var i2 = 0; i2 < display.view.length; i2++) { + var cur = display.view[i2], wrapping = cm.options.lineWrapping; + var height = void 0, width = 0; + if (cur.hidden) { + continue; + } + oldHeight += cur.line.height; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + if (!wrapping && cur.text.firstChild) { + width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; + } + } + var diff = cur.line.height - height; + if (diff > 5e-3 || diff < -5e-3) { + if (oldHeight < viewTop) { + mustScroll -= diff; + } + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) { + updateWidgetHeight(cur.rest[j]); + } + } + } + if (width > cm.display.sizerWidth) { + var chWidth = Math.ceil(width / charWidth(cm.display)); + if (chWidth > cm.display.maxLineLength) { + cm.display.maxLineLength = chWidth; + cm.display.maxLine = cur.line; + cm.display.maxLineChanged = true; + } + } + } + if (Math.abs(mustScroll) > 2) { + display.scroller.scrollTop += mustScroll; + } + } + function updateWidgetHeight(line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; ++i2) { + var w = line.widgets[i2], parent = w.node.parentNode; + if (parent) { + w.height = parent.offsetHeight; + } + } + } + } + function visibleLines(display, doc2, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + var from = lineAtHeight(doc2, top), to = lineAtHeight(doc2, bottom); + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc2, heightAtLine(getLine(doc2, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc2.lastLine()) >= to) { + from = lineAtHeight(doc2, heightAtLine(getLine(doc2, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return { from, to: Math.max(to, from + 1) }; + } + function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { + return; + } + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + var doc2 = display.wrapper.ownerDocument; + if (rect.top + box.top < 0) { + doScroll = true; + } else if (rect.bottom + box.top > (doc2.defaultView.innerHeight || doc2.documentElement.clientHeight)) { + doScroll = false; + } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "​", null, "position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { + margin = 0; + } + var rect; + if (!cm.options.lineWrapping && pos == end) { + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; + } + for (var limit = 0; limit < 5; limit++) { + var changed = false; + var coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + rect = { + left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin + }; + var scrollPos = calculateScrollPos(cm, rect); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { + changed = true; + } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { + changed = true; + } + } + if (!changed) { + break; + } + } + return rect; + } + function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect); + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + } + } + function calculateScrollPos(cm, rect) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (rect.top < 0) { + rect.top = 0; + } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen2 = displayHeight(cm), result = {}; + if (rect.bottom - rect.top > screen2) { + rect.bottom = rect.top + screen2; + } + var docBottom = cm.doc.height + paddingVert(display); + var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top; + } else if (rect.bottom > screentop + screen2) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2); + if (newTop != screentop) { + result.scrollTop = newTop; + } + } + var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; + var screenw = displayWidth(cm) - display.gutters.offsetWidth; + var tooWide = rect.right - rect.left > screenw; + if (tooWide) { + rect.right = rect.left + screenw; + } + if (rect.left < 10) { + result.scrollLeft = 0; + } else if (rect.left < screenleft) { + result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); + } else if (rect.right > screenw + screenleft - 3) { + result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; + } + return result; + } + function addToScrollTop(cm, top) { + if (top == null) { + return; + } + resolveScrollToPos(cm); + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(); + cm.curOp.scrollToPos = { from: cur, to: cur, margin: cm.options.cursorScrollMargin }; + } + function scrollToCoords(cm, x, y) { + if (x != null || y != null) { + resolveScrollToPos(cm); + } + if (x != null) { + cm.curOp.scrollLeft = x; + } + if (y != null) { + cm.curOp.scrollTop = y; + } + } + function scrollToRange(cm, range2) { + resolveScrollToPos(cm); + cm.curOp.scrollToPos = range2; + } + function resolveScrollToPos(cm) { + var range2 = cm.curOp.scrollToPos; + if (range2) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range2.from), to = estimateCoords(cm, range2.to); + scrollToCoordsRange(cm, from, to, range2.margin); + } + } + function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin + }); + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); + } + function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { + return; + } + if (!gecko) { + updateDisplaySimple(cm, { top: val }); + } + setScrollTop(cm, val, true); + if (gecko) { + updateDisplaySimple(cm); + } + startWorker(cm, 100); + } + function setScrollTop(cm, val, forceScroll) { + val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); + if (cm.display.scroller.scrollTop == val && !forceScroll) { + return; + } + cm.doc.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (cm.display.scroller.scrollTop != val) { + cm.display.scroller.scrollTop = val; + } + } + function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { + return; + } + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) { + cm.display.scroller.scrollLeft = val; + } + cm.display.scrollbars.setScrollLeft(val); + } + function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, + clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + }; + } + var NativeScrollbars = function(place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + vert.tabIndex = horiz.tabIndex = -1; + place(vert); + place(horiz); + on(vert, "scroll", function() { + if (vert.clientHeight) { + scroll(vert.scrollTop, "vertical"); + } + }); + on(horiz, "scroll", function() { + if (horiz.clientWidth) { + scroll(horiz.scrollLeft, "horizontal"); + } + }); + this.checkedZeroWidth = false; + if (ie && ie_version < 8) { + this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } + }; + NativeScrollbars.prototype.update = function(measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.scrollTop = 0; + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { + this.zeroWidthHack(); + } + this.checkedZeroWidth = true; + } + return { right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0 }; + }; + NativeScrollbars.prototype.setScrollLeft = function(pos) { + if (this.horiz.scrollLeft != pos) { + this.horiz.scrollLeft = pos; + } + if (this.disableHoriz) { + this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); + } + }; + NativeScrollbars.prototype.setScrollTop = function(pos) { + if (this.vert.scrollTop != pos) { + this.vert.scrollTop = pos; + } + if (this.disableVert) { + this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); + } + }; + NativeScrollbars.prototype.zeroWidthHack = function() { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.visibility = this.vert.style.visibility = "hidden"; + this.disableHoriz = new Delayed(); + this.disableVert = new Delayed(); + }; + NativeScrollbars.prototype.enableZeroWidthBar = function(bar, delay, type) { + bar.style.visibility = ""; + function maybeDisable() { + var box = bar.getBoundingClientRect(); + var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); + if (elt2 != bar) { + bar.style.visibility = "hidden"; + } else { + delay.set(1e3, maybeDisable); + } + } + delay.set(1e3, maybeDisable); + }; + NativeScrollbars.prototype.clear = function() { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + }; + var NullScrollbars = function() { + }; + NullScrollbars.prototype.update = function() { + return { bottom: 0, right: 0 }; + }; + NullScrollbars.prototype.setScrollLeft = function() { + }; + NullScrollbars.prototype.setScrollTop = function() { + }; + NullScrollbars.prototype.clear = function() { + }; + function updateScrollbars(cm, measure) { + if (!measure) { + measure = measureForScrollbars(cm); + } + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { + updateHeightsInViewport(cm); + } + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; + startHeight = cm.display.barHeight; + } + } + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else { + d.scrollbarFiller.style.display = ""; + } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else { + d.gutterFiller.style.display = ""; + } + } + var scrollbarModel = { "native": NativeScrollbars, "null": NullScrollbars }; + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) { + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function(node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + on(node, "mousedown", function() { + if (cm.state.focused) { + setTimeout(function() { + return cm.display.input.focus(); + }, 0); + } + }); + node.setAttribute("cm-not-content", "true"); + }, function(pos, axis) { + if (axis == "horizontal") { + setScrollLeft(cm, pos); + } else { + updateScrollTop(cm, pos); + } + }, cm); + if (cm.display.scrollbars.addClass) { + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + var nextOpId = 0; + function startOperation(cm) { + cm.curOp = { + cm, + viewChanged: false, + // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, + // Used to detect need to update scrollbar + forceUpdate: false, + // Used to force a redraw + updateInput: 0, + // Whether to reset the input textarea + typing: false, + // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, + // Accumulated changes, for firing change events + cursorActivityHandlers: null, + // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, + // Tracks which cursorActivity handlers have been called already + selectionChanged: false, + // Whether the selection needs to be redrawn + updateMaxLine: false, + // Set when the widest line needs to be determined anew + scrollLeft: null, + scrollTop: null, + // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, + // Used to scroll to a specific position + focus: false, + id: ++nextOpId, + // Unique ID + markArrays: null + // Used by addMarkedSpan + }; + pushOperation(cm.curOp); + } + function endOperation(cm) { + var op = cm.curOp; + if (op) { + finishOperation(op, function(group) { + for (var i2 = 0; i2 < group.ops.length; i2++) { + group.ops[i2].cm.curOp = null; + } + endOperations(group); + }); + } + } + function endOperations(group) { + var ops = group.ops; + for (var i2 = 0; i2 < ops.length; i2++) { + endOperation_R1(ops[i2]); + } + for (var i$12 = 0; i$12 < ops.length; i$12++) { + endOperation_W1(ops[i$12]); + } + for (var i$22 = 0; i$22 < ops.length; i$22++) { + endOperation_R2(ops[i$22]); + } + for (var i$3 = 0; i$3 < ops.length; i$3++) { + endOperation_W2(ops[i$3]); + } + for (var i$4 = 0; i$4 < ops.length; i$4++) { + endOperation_finish(ops[i$4]); + } + } + function endOperation_R1(op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) { + findMaxLine(cm); + } + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { top: op.scrollTop, ensure: op.scrollToPos }, op.forceUpdate); + } + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + function endOperation_R2(op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) { + updateHeightsInViewport(cm); + } + op.barMeasure = measureForScrollbars(cm); + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + if (op.updatedDisplay || op.selectionChanged) { + op.preparedSelection = display.input.prepareSelection(); + } + } + function endOperation_W2(op) { + var cm = op.cm; + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) { + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); + } + cm.display.maxLineChanged = false; + } + var takeFocus = op.focus && op.focus == activeElt(root(cm)); + if (op.preparedSelection) { + cm.display.input.showSelection(op.preparedSelection, takeFocus); + } + if (op.updatedDisplay || op.startHeight != cm.doc.height) { + updateScrollbars(cm, op.barMeasure); + } + if (op.updatedDisplay) { + setDocumentHeight(cm, op.barMeasure); + } + if (op.selectionChanged) { + restartBlink(cm); + } + if (cm.state.focused && op.updateInput) { + cm.display.input.reset(op.typing); + } + if (takeFocus) { + ensureFocus(op.cm); + } + } + function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc2 = cm.doc; + if (op.updatedDisplay) { + postUpdateDisplay(cm, op.update); + } + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { + display.wheelStartX = display.wheelStartY = null; + } + if (op.scrollTop != null) { + setScrollTop(cm, op.scrollTop, op.forceScroll); + } + if (op.scrollLeft != null) { + setScrollLeft(cm, op.scrollLeft, true, true); + } + if (op.scrollToPos) { + var rect = scrollPosIntoView( + cm, + clipPos(doc2, op.scrollToPos.from), + clipPos(doc2, op.scrollToPos.to), + op.scrollToPos.margin + ); + maybeScrollWindow(cm, rect); + } + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i2 = 0; i2 < hidden.length; ++i2) { + if (!hidden[i2].lines.length) { + signal(hidden[i2], "hide"); + } + } + } + if (unhidden) { + for (var i$12 = 0; i$12 < unhidden.length; ++i$12) { + if (unhidden[i$12].lines.length) { + signal(unhidden[i$12], "unhide"); + } + } + } + if (display.wrapper.offsetHeight) { + doc2.scrollTop = cm.display.scroller.scrollTop; + } + if (op.changeObjs) { + signal(cm, "changes", cm, op.changeObjs); + } + if (op.update) { + op.update.finish(); + } + } + function runInOp(cm, f) { + if (cm.curOp) { + return f(); + } + startOperation(cm); + try { + return f(); + } finally { + endOperation(cm); + } + } + function operation(cm, f) { + return function() { + if (cm.curOp) { + return f.apply(cm, arguments); + } + startOperation(cm); + try { + return f.apply(cm, arguments); + } finally { + endOperation(cm); + } + }; + } + function methodOp(f) { + return function() { + if (this.curOp) { + return f.apply(this, arguments); + } + startOperation(this); + try { + return f.apply(this, arguments); + } finally { + endOperation(this); + } + }; + } + function docMethodOp(f) { + return function() { + var cm = this.cm; + if (!cm || cm.curOp) { + return f.apply(this, arguments); + } + startOperation(cm); + try { + return f.apply(this, arguments); + } finally { + endOperation(cm); + } + }; + } + function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) { + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } + } + function highlightWorker(cm) { + var doc2 = cm.doc; + if (doc2.highlightFrontier >= cm.display.viewTo) { + return; + } + var end = +/* @__PURE__ */ new Date() + cm.options.workTime; + var context = getContextBefore(cm, doc2.highlightFrontier); + var changedLines = []; + doc2.iter(context.line, Math.min(doc2.first + doc2.size, cm.display.viewTo + 500), function(line) { + if (context.line >= cm.display.viewFrom) { + var oldStyles = line.styles; + var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc2.mode, context.state) : null; + var highlighted = highlightLine(cm, line, context, true); + if (resetState) { + context.state = resetState; + } + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) { + line.styleClasses = newCls; + } else if (oldCls) { + line.styleClasses = null; + } + var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) { + ischange = oldStyles[i2] != line.styles[i2]; + } + if (ischange) { + changedLines.push(context.line); + } + line.stateAfter = context.save(); + context.nextLine(); + } else { + if (line.text.length <= cm.options.maxHighlightLength) { + processLine(cm, line.text, context); + } + line.stateAfter = context.line % 5 == 0 ? context.save() : null; + context.nextLine(); + } + if (+/* @__PURE__ */ new Date() > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + doc2.highlightFrontier = context.line; + doc2.modeFrontier = Math.max(doc2.modeFrontier, context.line); + if (changedLines.length) { + runInOp(cm, function() { + for (var i2 = 0; i2 < changedLines.length; i2++) { + regLineChange(cm, changedLines[i2], "text"); + } + }); + } + } + var DisplayUpdate = function(cm, viewport, force) { + var display = cm.display; + this.viewport = viewport; + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + }; + DisplayUpdate.prototype.signal = function(emitter, type) { + if (hasHandler(emitter, type)) { + this.events.push(arguments); + } + }; + DisplayUpdate.prototype.finish = function() { + for (var i2 = 0; i2 < this.events.length; i2++) { + signal.apply(null, this.events[i2]); + } + }; + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + function selectionSnapshot(cm) { + if (cm.hasFocus()) { + return null; + } + var active = activeElt(root(cm)); + if (!active || !contains(cm.display.lineDiv, active)) { + return null; + } + var result = { activeElt: active }; + if (window.getSelection) { + var sel = win(cm).getSelection(); + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode; + result.anchorOffset = sel.anchorOffset; + result.focusNode = sel.focusNode; + result.focusOffset = sel.focusOffset; + } + } + return result; + } + function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(rootNode(snapshot.activeElt))) { + return; + } + snapshot.activeElt.focus(); + if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + var doc2 = snapshot.activeElt.ownerDocument; + var sel = doc2.defaultView.getSelection(), range2 = doc2.createRange(); + range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset); + range2.collapse(false); + sel.removeAllRanges(); + sel.addRange(range2); + sel.extend(snapshot.focusNode, snapshot.focusOffset); + } + } + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc2 = cm.doc; + if (update.editorIsHidden) { + resetView(cm); + return false; + } + if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { + return false; + } + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + var end = doc2.first + doc2.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc2.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) { + from = Math.max(doc2.first, display.viewFrom); + } + if (display.viewTo > to && display.viewTo - to < 20) { + to = Math.min(end, display.viewTo); + } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + cm.display.mover.style.top = display.viewOffset + "px"; + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { + return false; + } + var selSnapshot = selectionSnapshot(cm); + if (toUpdate > 4) { + display.lineDiv.style.display = "none"; + } + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) { + display.lineDiv.style.display = ""; + } + display.renderedView = display.view; + restoreSelection(selSnapshot); + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + display.updateLineNumbers = null; + return true; + } + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + for (var first = true; ; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + if (viewport && viewport.top != null) { + viewport = { top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) }; + } + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { + break; + } + } else if (first) { + update.visible = visibleLines(cm.display, cm.doc, viewport); + } + if (!updateDisplayIfNeeded(cm, update)) { + break; + } + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.force = false; + } + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; + cm.display.reportedViewTo = cm.display.viewTo; + } + } + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + function rm(node2) { + var next = node2.nextSibling; + if (webkit && mac && cm.display.currentWheelTarget == node2) { + node2.style.display = "none"; + } else { + node2.parentNode.removeChild(node2); + } + return next; + } + var view = display.view, lineN = display.viewFrom; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (lineView.hidden) ; + else if (!lineView.node || lineView.node.parentNode != container) { + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { + while (cur != lineView.node) { + cur = rm(cur); + } + var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { + updateNumber = false; + } + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) { + cur = rm(cur); + } + } + function updateGutterSpace(display) { + var width = display.gutters.offsetWidth; + display.sizer.style.marginLeft = width + "px"; + signalLater(display, "gutterChanged", display); + } + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px"; + } + function alignHorizontally(cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { + return; + } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i2 = 0; i2 < view.length; i2++) { + if (!view[i2].hidden) { + if (cm.options.fixedGutter) { + if (view[i2].gutter) { + view[i2].gutter.style.left = left; + } + if (view[i2].gutterBackground) { + view[i2].gutterBackground.style.left = left; + } + } + var align = view[i2].alignable; + if (align) { + for (var j = 0; j < align.length; j++) { + align[j].style.left = left; + } + } + } + } + if (cm.options.fixedGutter) { + display.gutters.style.left = comp + gutterW + "px"; + } + } + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { + return false; + } + var doc2 = cm.doc, last = lineNumberFor(cm.options, doc2.first + doc2.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt( + "div", + [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt" + )); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm.display); + return true; + } + return false; + } + function getGutters(gutters, lineNumbers) { + var result = [], sawLineNumbers = false; + for (var i2 = 0; i2 < gutters.length; i2++) { + var name = gutters[i2], style = null; + if (typeof name != "string") { + style = name.style; + name = name.className; + } + if (name == "CodeMirror-linenumbers") { + if (!lineNumbers) { + continue; + } else { + sawLineNumbers = true; + } + } + result.push({ className: name, style }); + } + if (lineNumbers && !sawLineNumbers) { + result.push({ className: "CodeMirror-linenumbers", style: null }); + } + return result; + } + function renderGutters(display) { + var gutters = display.gutters, specs = display.gutterSpecs; + removeChildren(gutters); + display.lineGutter = null; + for (var i2 = 0; i2 < specs.length; ++i2) { + var ref = specs[i2]; + var className = ref.className; + var style = ref.style; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); + if (style) { + gElt.style.cssText = style; + } + if (className == "CodeMirror-linenumbers") { + display.lineGutter = gElt; + gElt.style.width = (display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = specs.length ? "" : "none"; + updateGutterSpace(display); + } + function updateGutters(cm) { + renderGutters(cm.display); + regChange(cm); + alignHorizontally(cm); + } + function Display(place, doc2, input, options) { + var d = this; + this.input = input; + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + d.lineDiv = eltP("div", null, "CodeMirror-code"); + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + d.measure = elt("div", null, "CodeMirror-measure"); + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + d.lineSpace = eltP( + "div", + [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, + "position: relative; outline: none" + ); + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); + d.mover = elt("div", [lines], null, "position: relative"); + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + if (chrome && chrome_version >= 105) { + d.wrapper.style.clipPath = "inset(0px)"; + } + d.wrapper.setAttribute("translate", "no"); + if (ie && ie_version < 8) { + d.gutters.style.zIndex = -1; + d.scroller.style.paddingRight = 0; + } + if (!webkit && !(gecko && mobile)) { + d.scroller.draggable = true; + } + if (place) { + if (place.appendChild) { + place.appendChild(d.wrapper); + } else { + place(d.wrapper); + } + } + d.viewFrom = d.viewTo = doc2.first; + d.reportedViewFrom = d.reportedViewTo = doc2.first; + d.view = []; + d.renderedView = null; + d.externalMeasured = null; + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + d.alignWidgets = false; + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + d.shift = false; + d.selForContextMenu = null; + d.activeTouch = null; + d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); + renderGutters(d); + input.init(d); + } + var wheelSamples = 0, wheelPixelsPerUnit = null; + if (ie) { + wheelPixelsPerUnit = -0.53; + } else if (gecko) { + wheelPixelsPerUnit = 15; + } else if (chrome) { + wheelPixelsPerUnit = -0.7; + } else if (safari) { + wheelPixelsPerUnit = -1 / 3; + } + function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { + dx = e.detail; + } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { + dy = e.detail; + } else if (dy == null) { + dy = e.wheelDelta; + } + return { x: dx, y: dy }; + } + function wheelEventPixels(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + } + function onScrollWheel(cm, e) { + if (chrome && chrome_version == 102) { + if (cm.display.chromeScrollHack == null) { + cm.display.sizer.style.pointerEvents = "none"; + } else { + clearTimeout(cm.display.chromeScrollHack); + } + cm.display.chromeScrollHack = setTimeout(function() { + cm.display.chromeScrollHack = null; + cm.display.sizer.style.pointerEvents = ""; + }, 100); + } + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + var pixelsPerUnit = wheelPixelsPerUnit; + if (e.deltaMode === 0) { + dx = e.deltaX; + dy = e.deltaY; + pixelsPerUnit = 1; + } + var display = cm.display, scroll = display.scroller; + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) { + return; + } + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i2 = 0; i2 < view.length; i2++) { + if (view[i2].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + if (dx && !gecko && !presto && pixelsPerUnit != null) { + if (dy && canScrollY) { + updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); + } + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); + if (!dy || dy && canScrollY) { + e_preventDefault(e); + } + display.wheelStartX = null; + return; + } + if (dy && pixelsPerUnit != null) { + var pixels = dy * pixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) { + top = Math.max(0, top + pixels - 50); + } else { + bot = Math.min(cm.doc.height, bot + pixels + 50); + } + updateDisplaySimple(cm, { top, bottom: bot }); + } + if (wheelSamples < 20 && e.deltaMode !== 0) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; + display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; + display.wheelDY = dy; + setTimeout(function() { + if (display.wheelStartX == null) { + return; + } + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX; + display.wheelStartX = display.wheelStartY = null; + if (!sample) { + return; + } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; + display.wheelDY += dy; + } + } + } + var Selection = function(ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + }; + Selection.prototype.primary = function() { + return this.ranges[this.primIndex]; + }; + Selection.prototype.equals = function(other) { + if (other == this) { + return true; + } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { + return false; + } + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var here = this.ranges[i2], there = other.ranges[i2]; + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { + return false; + } + } + return true; + }; + Selection.prototype.deepCopy = function() { + var out = []; + for (var i2 = 0; i2 < this.ranges.length; i2++) { + out[i2] = new Range(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head)); + } + return new Selection(out, this.primIndex); + }; + Selection.prototype.somethingSelected = function() { + for (var i2 = 0; i2 < this.ranges.length; i2++) { + if (!this.ranges[i2].empty()) { + return true; + } + } + return false; + }; + Selection.prototype.contains = function(pos, end) { + if (!end) { + end = pos; + } + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var range2 = this.ranges[i2]; + if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) { + return i2; + } + } + return -1; + }; + var Range = function(anchor, head) { + this.anchor = anchor; + this.head = head; + }; + Range.prototype.from = function() { + return minPos(this.anchor, this.head); + }; + Range.prototype.to = function() { + return maxPos(this.anchor, this.head); + }; + Range.prototype.empty = function() { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + }; + function normalizeSelection(cm, ranges, primIndex) { + var mayTouch = cm && cm.options.selectionsMayTouch; + var prim = ranges[primIndex]; + ranges.sort(function(a, b) { + return cmp(a.from(), b.from()); + }); + primIndex = indexOf(ranges, prim); + for (var i2 = 1; i2 < ranges.length; i2++) { + var cur = ranges[i2], prev = ranges[i2 - 1]; + var diff = cmp(prev.to(), cur.from()); + if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i2 <= primIndex) { + --primIndex; + } + ranges.splice(--i2, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + function changeEnd(change) { + if (!change.text) { + return change.to; + } + return Pos( + change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + ); + } + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { + return pos; + } + if (cmp(pos, change.to) <= 0) { + return changeEnd(change); + } + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) { + ch += changeEnd(change).ch - change.to.ch; + } + return Pos(line, ch); + } + function computeSelAfterChange(doc2, change) { + var out = []; + for (var i2 = 0; i2 < doc2.sel.ranges.length; i2++) { + var range2 = doc2.sel.ranges[i2]; + out.push(new Range( + adjustForChange(range2.anchor, change), + adjustForChange(range2.head, change) + )); + } + return normalizeSelection(doc2.cm, out, doc2.sel.primIndex); + } + function offsetPos(pos, old, nw) { + if (pos.line == old.line) { + return Pos(nw.line, pos.ch - old.ch + nw.ch); + } else { + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + } + function computeReplacedSel(doc2, changes, hint) { + var out = []; + var oldPrev = Pos(doc2.first, 0), newPrev = oldPrev; + for (var i2 = 0; i2 < changes.length; i2++) { + var change = changes[i2]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range2 = doc2.sel.ranges[i2], inv = cmp(range2.head, range2.anchor) < 0; + out[i2] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i2] = new Range(from, from); + } + } + return new Selection(out, doc2.sel.primIndex); + } + function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + function resetModeState(cm) { + cm.doc.iter(function(line) { + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + }); + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) { + regChange(cm); + } + } + function isWholeLineUpdate(doc2, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc2.cm || doc2.cm.options.wholeLineUpdateBefore); + } + function updateDoc(doc2, change, markedSpans, estimateHeight2) { + function spansFor(n) { + return markedSpans ? markedSpans[n] : null; + } + function update(line, text2, spans) { + updateLine(line, text2, spans, estimateHeight2); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + var result = []; + for (var i2 = start; i2 < end; ++i2) { + result.push(new Line(text[i2], spansFor(i2), estimateHeight2)); + } + return result; + } + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc2, from.line), lastLine = getLine(doc2, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + if (change.full) { + doc2.insert(0, linesFor(0, text.length)); + doc2.remove(text.length, doc2.size - text.length); + } else if (isWholeLineUpdate(doc2, change)) { + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) { + doc2.remove(from.line, nlines); + } + if (added.length) { + doc2.insert(from.line, added); + } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added$1 = linesFor(1, text.length - 1); + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc2.insert(from.line + 1, added$1); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc2.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added$2 = linesFor(1, text.length - 1); + if (nlines > 1) { + doc2.remove(from.line + 1, nlines - 1); + } + doc2.insert(from.line + 1, added$2); + } + signalLater(doc2, "change", doc2, change); + } + function linkedDocs(doc2, f, sharedHistOnly) { + function propagate(doc3, skip, sharedHist) { + if (doc3.linked) { + for (var i2 = 0; i2 < doc3.linked.length; ++i2) { + var rel = doc3.linked[i2]; + if (rel.doc == skip) { + continue; + } + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) { + continue; + } + f(rel.doc, shared); + propagate(rel.doc, doc3, shared); + } + } + } + propagate(doc2, null, true); + } + function attachDoc(cm, doc2) { + if (doc2.cm) { + throw new Error("This document is already in use."); + } + cm.doc = doc2; + doc2.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + setDirectionClass(cm); + cm.options.direction = doc2.direction; + if (!cm.options.lineWrapping) { + findMaxLine(cm); + } + cm.options.mode = doc2.modeOption; + regChange(cm); + } + function setDirectionClass(cm) { + (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); + } + function directionChanged(cm) { + runInOp(cm, function() { + setDirectionClass(cm); + regChange(cm); + }); + } + function History(prev) { + this.done = []; + this.undone = []; + this.undoDepth = prev ? prev.undoDepth : Infinity; + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; + } + function historyChangeFromChange(doc2, change) { + var histChange = { from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc2, change.from, change.to) }; + attachLocalSpans(doc2, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc2, function(doc3) { + return attachLocalSpans(doc3, histChange, change.from.line, change.to.line + 1); + }, true); + return histChange; + } + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) { + array.pop(); + } else { + break; + } + } + } + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + function addChangeToHistory(doc2, change, selAfter, opId) { + var hist = doc2.history; + hist.undone.length = 0; + var time = +/* @__PURE__ */ new Date(), cur; + var last; + if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc2.cm ? doc2.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + last.to = changeEnd(change); + } else { + cur.changes.push(historyChangeFromChange(doc2, change)); + } + } else { + var before = lst(hist.done); + if (!before || !before.ranges) { + pushSelectionToHistory(doc2.sel, hist.done); + } + cur = { + changes: [historyChangeFromChange(doc2, change)], + generation: hist.generation + }; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) { + hist.done.shift(); + } + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + if (!last) { + signal(doc2, "historyAdded"); + } + } + function selectionEventCanBeMerged(doc2, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && /* @__PURE__ */ new Date() - doc2.history.lastSelTime <= (doc2.cm ? doc2.cm.options.historyEventDelay : 500); + } + function addSelectionToHistory(doc2, sel, opId, options) { + var hist = doc2.history, origin = options && options.origin; + if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc2, origin, lst(hist.done), sel))) { + hist.done[hist.done.length - 1] = sel; + } else { + pushSelectionToHistory(sel, hist.done); + } + hist.lastSelTime = +/* @__PURE__ */ new Date(); + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) { + clearSelectionEvents(hist.undone); + } + } + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) { + dest.push(sel); + } + } + function attachLocalSpans(doc2, change, from, to) { + var existing = change["spans_" + doc2.id], n = 0; + doc2.iter(Math.max(doc2.first, from), Math.min(doc2.first + doc2.size, to), function(line) { + if (line.markedSpans) { + (existing || (existing = change["spans_" + doc2.id] = {}))[n] = line.markedSpans; + } + ++n; + }); + } + function removeClearedSpans(spans) { + if (!spans) { + return null; + } + var out; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2].marker.explicitlyCleared) { + if (!out) { + out = spans.slice(0, i2); + } + } else if (out) { + out.push(spans[i2]); + } + } + return !out ? spans : out.length ? out : null; + } + function getOldSpans(doc2, change) { + var found = change["spans_" + doc2.id]; + if (!found) { + return null; + } + var nw = []; + for (var i2 = 0; i2 < change.text.length; ++i2) { + nw.push(removeClearedSpans(found[i2])); + } + return nw; + } + function mergeOldSpans(doc2, change) { + var old = getOldSpans(doc2, change); + var stretched = stretchSpansOverChange(doc2, change); + if (!old) { + return stretched; + } + if (!stretched) { + return old; + } + for (var i2 = 0; i2 < old.length; ++i2) { + var oldCur = old[i2], stretchCur = stretched[i2]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) { + if (oldCur[k].marker == span.marker) { + continue spans; + } + } + oldCur.push(span); + } + } else if (stretchCur) { + old[i2] = stretchCur; + } + } + return old; + } + function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = []; + for (var i2 = 0; i2 < events.length; ++i2) { + var event = events[i2]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({ changes: newChanges }); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = void 0; + newChanges.push({ from: change.from, to: change.to, text: change.text }); + if (newGroup) { + for (var prop2 in change) { + if (m = prop2.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop2] = change[prop2]; + delete change[prop2]; + } + } + } + } + } + } + return copy; + } + function extendRange(range2, head, other, extend) { + if (extend) { + var anchor = range2.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != cmp(other, anchor) < 0) { + anchor = head; + head = other; + } else if (posBefore != cmp(head, other) < 0) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); + } + } + function extendSelection(doc2, head, other, options, extend) { + if (extend == null) { + extend = doc2.cm && (doc2.cm.display.shift || doc2.extend); + } + setSelection(doc2, new Selection([extendRange(doc2.sel.primary(), head, other, extend)], 0), options); + } + function extendSelections(doc2, heads, options) { + var out = []; + var extend = doc2.cm && (doc2.cm.display.shift || doc2.extend); + for (var i2 = 0; i2 < doc2.sel.ranges.length; i2++) { + out[i2] = extendRange(doc2.sel.ranges[i2], heads[i2], null, extend); + } + var newSel = normalizeSelection(doc2.cm, out, doc2.sel.primIndex); + setSelection(doc2, newSel, options); + } + function replaceOneSelection(doc2, i2, range2, options) { + var ranges = doc2.sel.ranges.slice(0); + ranges[i2] = range2; + setSelection(doc2, normalizeSelection(doc2.cm, ranges, doc2.sel.primIndex), options); + } + function setSimpleSelection(doc2, anchor, head, options) { + setSelection(doc2, simpleSelection(anchor, head), options); + } + function filterSelectionChange(doc2, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + this.ranges = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + this.ranges[i2] = new Range( + clipPos(doc2, ranges[i2].anchor), + clipPos(doc2, ranges[i2].head) + ); + } + }, + origin: options && options.origin + }; + signal(doc2, "beforeSelectionChange", doc2, obj); + if (doc2.cm) { + signal(doc2.cm, "beforeSelectionChange", doc2.cm, obj); + } + if (obj.ranges != sel.ranges) { + return normalizeSelection(doc2.cm, obj.ranges, obj.ranges.length - 1); + } else { + return sel; + } + } + function setSelectionReplaceHistory(doc2, sel, options) { + var done = doc2.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc2, sel, options); + } else { + setSelection(doc2, sel, options); + } + } + function setSelection(doc2, sel, options) { + setSelectionNoUndo(doc2, sel, options); + addSelectionToHistory(doc2, doc2.sel, doc2.cm ? doc2.cm.curOp.id : NaN, options); + } + function setSelectionNoUndo(doc2, sel, options) { + if (hasHandler(doc2, "beforeSelectionChange") || doc2.cm && hasHandler(doc2.cm, "beforeSelectionChange")) { + sel = filterSelectionChange(doc2, sel, options); + } + var bias = options && options.bias || (cmp(sel.primary().head, doc2.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc2, skipAtomicInSelection(doc2, sel, bias, true)); + if (!(options && options.scroll === false) && doc2.cm && doc2.cm.getOption("readOnly") != "nocursor") { + ensureCursorVisible(doc2.cm); + } + } + function setSelectionInner(doc2, sel) { + if (sel.equals(doc2.sel)) { + return; + } + doc2.sel = sel; + if (doc2.cm) { + doc2.cm.curOp.updateInput = 1; + doc2.cm.curOp.selectionChanged = true; + signalCursorActivity(doc2.cm); + } + signalLater(doc2, "cursorActivity", doc2); + } + function reCheckSelection(doc2) { + setSelectionInner(doc2, skipAtomicInSelection(doc2, doc2.sel, null, false)); + } + function skipAtomicInSelection(doc2, sel, bias, mayClear) { + var out; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + var old = sel.ranges.length == doc2.sel.ranges.length && doc2.sel.ranges[i2]; + var newAnchor = skipAtomic(doc2, range2.anchor, old && old.anchor, bias, mayClear); + var newHead = range2.head == range2.anchor ? newAnchor : skipAtomic(doc2, range2.head, old && old.head, bias, mayClear); + if (out || newAnchor != range2.anchor || newHead != range2.head) { + if (!out) { + out = sel.ranges.slice(0, i2); + } + out[i2] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(doc2.cm, out, sel.primIndex) : sel; + } + function skipAtomicInner(doc2, pos, oldPos, dir, mayClear) { + var line = getLine(doc2, pos.line); + if (line.markedSpans) { + for (var i2 = 0; i2 < line.markedSpans.length; ++i2) { + var sp = line.markedSpans[i2], m = sp.marker; + var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; + var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight; + if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) { + break; + } else { + --i2; + continue; + } + } + } + if (!m.atomic) { + continue; + } + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = void 0; + if (dir < 0 ? preventCursorRight : preventCursorLeft) { + near = movePos(doc2, near, -dir, near && near.line == pos.line ? line : null); + } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { + return skipAtomicInner(doc2, near, pos, dir, mayClear); + } + } + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? preventCursorLeft : preventCursorRight) { + far = movePos(doc2, far, dir, far.line == pos.line ? line : null); + } + return far ? skipAtomicInner(doc2, far, pos, dir, mayClear) : null; + } + } + } + return pos; + } + function skipAtomic(doc2, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = skipAtomicInner(doc2, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc2, pos, oldPos, dir, true) || skipAtomicInner(doc2, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc2, pos, oldPos, -dir, true); + if (!found) { + doc2.cantEdit = true; + return Pos(doc2.first, 0); + } + return found; + } + function movePos(doc2, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc2.first) { + return clipPos(doc2, Pos(pos.line - 1)); + } else { + return null; + } + } else if (dir > 0 && pos.ch == (line || getLine(doc2, pos.line)).text.length) { + if (pos.line < doc2.first + doc2.size - 1) { + return Pos(pos.line + 1, 0); + } else { + return null; + } + } else { + return new Pos(pos.line, pos.ch + dir); + } + } + function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); + } + function filterChange(doc2, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function() { + return obj.canceled = true; + } + }; + if (update) { + obj.update = function(from, to, text, origin) { + if (from) { + obj.from = clipPos(doc2, from); + } + if (to) { + obj.to = clipPos(doc2, to); + } + if (text) { + obj.text = text; + } + if (origin !== void 0) { + obj.origin = origin; + } + }; + } + signal(doc2, "beforeChange", doc2, obj); + if (doc2.cm) { + signal(doc2.cm, "beforeChange", doc2.cm, obj); + } + if (obj.canceled) { + if (doc2.cm) { + doc2.cm.curOp.updateInput = 2; + } + return null; + } + return { from: obj.from, to: obj.to, text: obj.text, origin: obj.origin }; + } + function makeChange(doc2, change, ignoreReadOnly) { + if (doc2.cm) { + if (!doc2.cm.curOp) { + return operation(doc2.cm, makeChange)(doc2, change, ignoreReadOnly); + } + if (doc2.cm.state.suppressEdits) { + return; + } + } + if (hasHandler(doc2, "beforeChange") || doc2.cm && hasHandler(doc2.cm, "beforeChange")) { + change = filterChange(doc2, change, true); + if (!change) { + return; + } + } + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc2, change.from, change.to); + if (split) { + for (var i2 = split.length - 1; i2 >= 0; --i2) { + makeChangeInner(doc2, { from: split[i2].from, to: split[i2].to, text: i2 ? [""] : change.text, origin: change.origin }); + } + } else { + makeChangeInner(doc2, change); + } + } + function makeChangeInner(doc2, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { + return; + } + var selAfter = computeSelAfterChange(doc2, change); + addChangeToHistory(doc2, change, selAfter, doc2.cm ? doc2.cm.curOp.id : NaN); + makeChangeSingleDoc(doc2, change, selAfter, stretchSpansOverChange(doc2, change)); + var rebased = []; + linkedDocs(doc2, function(doc3, sharedHist) { + if (!sharedHist && indexOf(rebased, doc3.history) == -1) { + rebaseHist(doc3.history, change); + rebased.push(doc3.history); + } + makeChangeSingleDoc(doc3, change, null, stretchSpansOverChange(doc3, change)); + }); + } + function makeChangeFromHistory(doc2, type, allowSelectionOnly) { + var suppress = doc2.cm && doc2.cm.state.suppressEdits; + if (suppress && !allowSelectionOnly) { + return; + } + var hist = doc2.history, event, selAfter = doc2.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + var i2 = 0; + for (; i2 < source.length; i2++) { + event = source[i2]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc2.sel) : !event.ranges) { + break; + } + } + if (i2 == source.length) { + return; + } + hist.lastOrigin = hist.lastSelOrigin = null; + for (; ; ) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc2.sel)) { + setSelection(doc2, event, { clearRedo: false }); + return; + } + selAfter = event; + } else if (suppress) { + source.push(event); + return; + } else { + break; + } + } + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({ changes: antiChanges, generation: hist.generation }); + hist.generation = event.generation || ++hist.maxGeneration; + var filter = hasHandler(doc2, "beforeChange") || doc2.cm && hasHandler(doc2.cm, "beforeChange"); + var loop = function(i3) { + var change = event.changes[i3]; + change.origin = type; + if (filter && !filterChange(doc2, change, false)) { + source.length = 0; + return {}; + } + antiChanges.push(historyChangeFromChange(doc2, change)); + var after = i3 ? computeSelAfterChange(doc2, change) : lst(source); + makeChangeSingleDoc(doc2, change, after, mergeOldSpans(doc2, change)); + if (!i3 && doc2.cm) { + doc2.cm.scrollIntoView({ from: change.from, to: changeEnd(change) }); + } + var rebased = []; + linkedDocs(doc2, function(doc3, sharedHist) { + if (!sharedHist && indexOf(rebased, doc3.history) == -1) { + rebaseHist(doc3.history, change); + rebased.push(doc3.history); + } + makeChangeSingleDoc(doc3, change, null, mergeOldSpans(doc3, change)); + }); + }; + for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) { + var returned = loop(i$12); + if (returned) return returned.v; + } + } + function shiftDoc(doc2, distance) { + if (distance == 0) { + return; + } + doc2.first += distance; + doc2.sel = new Selection(map(doc2.sel.ranges, function(range2) { + return new Range( + Pos(range2.anchor.line + distance, range2.anchor.ch), + Pos(range2.head.line + distance, range2.head.ch) + ); + }), doc2.sel.primIndex); + if (doc2.cm) { + regChange(doc2.cm, doc2.first, doc2.first - distance, distance); + for (var d = doc2.cm.display, l = d.viewFrom; l < d.viewTo; l++) { + regLineChange(doc2.cm, l, "gutter"); + } + } + } + function makeChangeSingleDoc(doc2, change, selAfter, spans) { + if (doc2.cm && !doc2.cm.curOp) { + return operation(doc2.cm, makeChangeSingleDoc)(doc2, change, selAfter, spans); + } + if (change.to.line < doc2.first) { + shiftDoc(doc2, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc2.lastLine()) { + return; + } + if (change.from.line < doc2.first) { + var shift = change.text.length - 1 - (doc2.first - change.from.line); + shiftDoc(doc2, shift); + change = { + from: Pos(doc2.first, 0), + to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], + origin: change.origin + }; + } + var last = doc2.lastLine(); + if (change.to.line > last) { + change = { + from: change.from, + to: Pos(last, getLine(doc2, last).text.length), + text: [change.text[0]], + origin: change.origin + }; + } + change.removed = getBetween(doc2, change.from, change.to); + if (!selAfter) { + selAfter = computeSelAfterChange(doc2, change); + } + if (doc2.cm) { + makeChangeSingleDocInEditor(doc2.cm, change, spans); + } else { + updateDoc(doc2, change, spans); + } + setSelectionNoUndo(doc2, selAfter, sel_dontScroll); + if (doc2.cantEdit && skipAtomic(doc2, Pos(doc2.firstLine(), 0))) { + doc2.cantEdit = false; + } + } + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc2 = cm.doc, display = cm.display, from = change.from, to = change.to; + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc2, from.line))); + doc2.iter(checkWidthStart, to.line + 1, function(line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + if (doc2.sel.contains(change.from, change.to) > -1) { + signalCursorActivity(cm); + } + updateDoc(doc2, change, spans, estimateHeight(cm)); + if (!cm.options.lineWrapping) { + doc2.iter(checkWidthStart, from.line + change.text.length, function(line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) { + cm.curOp.updateMaxLine = true; + } + } + retreatFrontier(doc2, from.line); + startWorker(cm, 400); + var lendiff = change.text.length - (to.line - from.line) - 1; + if (change.full) { + regChange(cm); + } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { + regLineChange(cm, from.line, "text"); + } else { + regChange(cm, from.line, to.line + 1, lendiff); + } + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from, + to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) { + signalLater(cm, "change", cm, obj); + } + if (changesHandler) { + (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + } + cm.display.selForContextMenu = null; + } + function replaceRange(doc2, code, from, to, origin) { + var assign; + if (!to) { + to = from; + } + if (cmp(to, from) < 0) { + assign = [to, from], from = assign[0], to = assign[1]; + } + if (typeof code == "string") { + code = doc2.splitLines(code); + } + makeChange(doc2, { from, to, text: code, origin }); + } + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + function rebaseHistArray(array, from, to, diff) { + for (var i2 = 0; i2 < array.length; ++i2) { + var sub = array[i2], ok = true; + if (sub.ranges) { + if (!sub.copied) { + sub = array[i2] = sub.deepCopy(); + sub.copied = true; + } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i2 + 1); + i2 = 0; + } + } + } + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + function changeLine(doc2, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle == "number") { + line = getLine(doc2, clipLine(doc2, handle)); + } else { + no = lineNo(handle); + } + if (no == null) { + return null; + } + if (op(line, no) && doc2.cm) { + regLineChange(doc2.cm, no, changeType); + } + return line; + } + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; + height += lines[i2].height; + } + this.height = height; + } + LeafChunk.prototype = { + chunkSize: function() { + return this.lines.length; + }, + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + for (var i2 = at, e = at + n; i2 < e; ++i2) { + var line = this.lines[i2]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; + } + }, + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) { + if (op(this.lines[at])) { + return true; + } + } + } + }; + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i2 = 0; i2 < children.length; ++i2) { + var ch = children[i2]; + size += ch.chunkSize(); + height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + BranchChunk.prototype = { + chunkSize: function() { + return this.size; + }, + removeInner: function(at, n) { + this.size -= n; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { + this.children.splice(i2--, 1); + child.parent = null; + } + if ((n -= rm) == 0) { + break; + } + at = 0; + } else { + at -= sz; + } + } + if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + this.children[i2].collapse(lines); + } + }, + insertInner: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + var remaining = child.lines.length % 25 + 25; + for (var pos = remaining; pos < child.lines.length; ) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); + child.height -= leaf.height; + this.children.splice(++i2, 0, leaf); + leaf.parent = this; + } + child.lines = child.lines.slice(0, remaining); + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) { + return; + } + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function(at, n, op) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) { + return true; + } + if ((n -= used) == 0) { + break; + } + at = 0; + } else { + at -= sz; + } + } + } + }; + var LineWidget = function(doc2, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) { + this[opt] = options[opt]; + } + } + } + this.doc = doc2; + this.node = node; + }; + LineWidget.prototype.clear = function() { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) { + return; + } + for (var i2 = 0; i2 < ws.length; ++i2) { + if (ws[i2] == this) { + ws.splice(i2--, 1); + } + } + if (!ws.length) { + line.widgets = null; + } + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function() { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + signalLater(cm, "lineWidgetCleared", cm, this, no); + } + }; + LineWidget.prototype.changed = function() { + var this$1$1 = this; + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) { + return; + } + if (!lineIsHidden(this.doc, line)) { + updateLineHeight(line, line.height + diff); + } + if (cm) { + runInOp(cm, function() { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line)); + }); + } + }; + eventMixin(LineWidget); + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) { + addToScrollTop(cm, diff); + } + } + function addLineWidget(doc2, handle, node, options) { + var widget = new LineWidget(doc2, node, options); + var cm = doc2.cm; + if (cm && widget.noHScroll) { + cm.display.alignWidgets = true; + } + changeLine(doc2, handle, "widget", function(line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) { + widgets.push(widget); + } else { + widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); + } + widget.line = line; + if (cm && !lineIsHidden(doc2, line)) { + var aboveVisible = heightAtLine(line) < doc2.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) { + addToScrollTop(cm, widget.height); + } + cm.curOp.forceUpdate = true; + } + return true; + }); + if (cm) { + signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); + } + return widget; + } + var nextMarkerId = 0; + var TextMarker = function(doc2, type) { + this.lines = []; + this.type = type; + this.doc = doc2; + this.id = ++nextMarkerId; + }; + TextMarker.prototype.clear = function() { + if (this.explicitlyCleared) { + return; + } + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) { + startOperation(cm); + } + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) { + signalLater(this, "clear", found.from, found.to); + } + } + var min = null, max = null; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) { + regLineChange(cm, lineNo(line), "text"); + } else if (cm) { + if (span.to != null) { + max = lineNo(line); + } + if (span.from != null) { + min = lineNo(line); + } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { + updateLineHeight(line, textHeight(cm.display)); + } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i$12 = 0; i$12 < this.lines.length; ++i$12) { + var visual = visualLine(this.lines[i$12]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + } + if (min != null && cm && this.collapsed) { + regChange(cm, min, max + 1); + } + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) { + reCheckSelection(cm.doc); + } + } + if (cm) { + signalLater(cm, "markerCleared", cm, this, min, max); + } + if (withOp) { + endOperation(cm); + } + if (this.parent) { + this.parent.clear(); + } + }; + TextMarker.prototype.find = function(side, lineObj) { + if (side == null && this.type == "bookmark") { + side = 1; + } + var from, to; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) { + return from; + } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) { + return to; + } + } + } + return from && { from, to }; + }; + TextMarker.prototype.changed = function() { + var this$1$1 = this; + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) { + return; + } + runInOp(cm, function() { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) { + updateLineHeight(line, line.height + dHeight); + } + } + signalLater(cm, "markerChanged", cm, this$1$1); + }); + }; + TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); + } + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + eventMixin(TextMarker); + function markText(doc2, from, to, options, type) { + if (options && options.shared) { + return markTextShared(doc2, from, to, options, type); + } + if (doc2.cm && !doc2.cm.curOp) { + return operation(doc2.cm, markText)(doc2, from, to, options, type); + } + var marker = new TextMarker(doc2, type), diff = cmp(from, to); + if (options) { + copyObj(options, marker, false); + } + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { + return marker; + } + if (marker.replacedWith) { + marker.collapsed = true; + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) { + marker.widgetNode.setAttribute("cm-ignore-events", "true"); + } + if (options.insertLeft) { + marker.widgetNode.insertLeft = true; + } + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc2, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc2, to.line, from, to, marker)) { + throw new Error("Inserting collapsed marker partially overlapping an existing one"); + } + seeCollapsedSpans(); + } + if (marker.addToHistory) { + addChangeToHistory(doc2, { from, to, origin: "markText" }, doc2.sel, NaN); + } + var curLine = from.line, cm = doc2.cm, updateMaxLine; + doc2.iter(curLine, to.line + 1, function(line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { + updateMaxLine = true; + } + if (marker.collapsed && curLine != from.line) { + updateLineHeight(line, 0); + } + addMarkedSpan(line, new MarkedSpan( + marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null + ), doc2.cm && doc2.cm.curOp); + ++curLine; + }); + if (marker.collapsed) { + doc2.iter(from.line, to.line + 1, function(line) { + if (lineIsHidden(doc2, line)) { + updateLineHeight(line, 0); + } + }); + } + if (marker.clearOnEnter) { + on(marker, "beforeCursorEnter", function() { + return marker.clear(); + }); + } + if (marker.readOnly) { + seeReadOnlySpans(); + if (doc2.history.done.length || doc2.history.undone.length) { + doc2.clearHistory(); + } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + if (updateMaxLine) { + cm.curOp.updateMaxLine = true; + } + if (marker.collapsed) { + regChange(cm, from.line, to.line + 1); + } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { + for (var i2 = from.line; i2 <= to.line; i2++) { + regLineChange(cm, i2, "text"); + } + } + if (marker.atomic) { + reCheckSelection(cm.doc); + } + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + var SharedTextMarker = function(markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i2 = 0; i2 < markers.length; ++i2) { + markers[i2].parent = this; + } + }; + SharedTextMarker.prototype.clear = function() { + if (this.explicitlyCleared) { + return; + } + this.explicitlyCleared = true; + for (var i2 = 0; i2 < this.markers.length; ++i2) { + this.markers[i2].clear(); + } + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function(side, lineObj) { + return this.primary.find(side, lineObj); + }; + eventMixin(SharedTextMarker); + function markTextShared(doc2, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc2, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc2, function(doc3) { + if (widget) { + options.widgetNode = widget.cloneNode(true); + } + markers.push(markText(doc3, clipPos(doc3, from), clipPos(doc3, to), options, type)); + for (var i2 = 0; i2 < doc3.linked.length; ++i2) { + if (doc3.linked[i2].isParent) { + return; + } + } + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + function findSharedMarkers(doc2) { + return doc2.findMarks(Pos(doc2.first, 0), doc2.clipPos(Pos(doc2.lastLine())), function(m) { + return m.parent; + }); + } + function copySharedMarkers(doc2, markers) { + for (var i2 = 0; i2 < markers.length; i2++) { + var marker = markers[i2], pos = marker.find(); + var mFrom = doc2.clipPos(pos.from), mTo = doc2.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc2, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + function detachSharedMarkers(markers) { + var loop = function(i3) { + var marker = markers[i3], linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function(d) { + return linked.push(d); + }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + }; + for (var i2 = 0; i2 < markers.length; i2++) loop(i2); + } + var nextDocId = 0; + var Doc = function(text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { + return new Doc(text, mode, firstLine, lineSep, direction); + } + if (firstLine == null) { + firstLine = 0; + } + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.modeFrontier = this.highlightFrontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.direction = direction == "rtl" ? "rtl" : "ltr"; + this.extend = false; + if (typeof text == "string") { + text = this.splitLines(text); + } + updateDoc(this, { from: start, to: start, text }); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { + this.iterN(from - this.first, to - from, op); + } else { + this.iterN(this.first, this.first + this.size, from); + } + }, + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + height += lines[i2].height; + } + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { + this.removeInner(at - this.first, n); + }, + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) { + return lines; + } + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, { + from: top, + to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), + origin: "setValue", + full: true + }, true); + if (this.cm) { + scrollToCoords(this.cm, 0, 0); + } + setSelection(this, simpleSelection(top), sel_dontScroll); + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) { + return lines; + } + if (lineSep === "") { + return lines.join(""); + } + return lines.join(lineSep || this.lineSeparator()); + }, + getLine: function(line) { + var l = this.getLineHandle(line); + return l && l.text; + }, + getLineHandle: function(line) { + if (isLine(this, line)) { + return getLine(this, line); + } + }, + getLineNumber: function(line) { + return lineNo(line); + }, + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { + line = getLine(this, line); + } + return visualLine(line); + }, + lineCount: function() { + return this.size; + }, + firstLine: function() { + return this.first; + }, + lastLine: function() { + return this.first + this.size - 1; + }, + clipPos: function(pos) { + return clipPos(this, pos); + }, + getCursor: function(start) { + var range2 = this.sel.primary(), pos; + if (start == null || start == "head") { + pos = range2.head; + } else if (start == "anchor") { + pos = range2.anchor; + } else if (start == "end" || start == "to" || start === false) { + pos = range2.to(); + } else { + pos = range2.from(); + } + return pos; + }, + listSelections: function() { + return this.sel.ranges; + }, + somethingSelected: function() { + return this.sel.somethingSelected(); + }, + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function(ranges, primary, options) { + if (!ranges.length) { + return; + } + var out = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + out[i2] = new Range( + clipPos(this, ranges[i2].anchor), + clipPos(this, ranges[i2].head || ranges[i2].anchor) + ); + } + if (primary == null) { + primary = Math.min(ranges.length - 1, this.sel.primIndex); + } + setSelection(this, normalizeSelection(this.cm, out, primary), options); + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); + }), + getSelection: function(lineSep) { + var ranges = this.sel.ranges, lines; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) { + return lines; + } else { + return lines.join(lineSep || this.lineSeparator()); + } + }, + getSelections: function(lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); + if (lineSep !== false) { + sel = sel.join(lineSep || this.lineSeparator()); + } + parts[i2] = sel; + } + return parts; + }, + replaceSelection: function(code, collapse, origin) { + var dup = []; + for (var i2 = 0; i2 < this.sel.ranges.length; i2++) { + dup[i2] = code; + } + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + changes[i2] = { from: range2.from(), to: range2.to(), text: this.splitLines(code[i2]), origin }; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) { + makeChange(this, changes[i$12]); + } + if (newSel) { + setSelectionReplaceHistory(this, newSel); + } else if (this.cm) { + ensureCursorVisible(this.cm); + } + }), + undo: docMethodOp(function() { + makeChangeFromHistory(this, "undo"); + }), + redo: docMethodOp(function() { + makeChangeFromHistory(this, "redo"); + }), + undoSelection: docMethodOp(function() { + makeChangeFromHistory(this, "undo", true); + }), + redoSelection: docMethodOp(function() { + makeChangeFromHistory(this, "redo", true); + }), + setExtending: function(val) { + this.extend = val; + }, + getExtending: function() { + return this.extend; + }, + historySize: function() { + var hist = this.history, done = 0, undone = 0; + for (var i2 = 0; i2 < hist.done.length; i2++) { + if (!hist.done[i2].ranges) { + ++done; + } + } + for (var i$12 = 0; i$12 < hist.undone.length; i$12++) { + if (!hist.undone[i$12].ranges) { + ++undone; + } + } + return { undo: done, redo: undone }; + }, + clearHistory: function() { + var this$1$1 = this; + this.history = new History(this.history); + linkedDocs(this, function(doc2) { + return doc2.history = this$1$1.history; + }, true); + }, + markClean: function() { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function(forceSplit) { + if (forceSplit) { + this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; + } + return this.history.generation; + }, + isClean: function(gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + getHistory: function() { + return { + done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone) + }; + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + setGutterMarker: docMethodOp(function(line, gutterID, value) { + return changeLine(this, line, "gutter", function(line2) { + var markers = line2.gutterMarkers || (line2.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) { + line2.gutterMarkers = null; + } + return true; + }); + }), + clearGutter: docMethodOp(function(gutterID) { + var this$1$1 = this; + this.iter(function(line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1$1, line, "gutter", function() { + line.gutterMarkers[gutterID] = null; + if (isEmpty(line.gutterMarkers)) { + line.gutterMarkers = null; + } + return true; + }); + } + }); + }), + lineInfo: function(line) { + var n; + if (typeof line == "number") { + if (!isLine(this, line)) { + return null; + } + n = line; + line = getLine(this, line); + if (!line) { + return null; + } + } else { + n = lineNo(line); + if (n == null) { + return null; + } + } + return { + line: n, + handle: line, + text: line.text, + gutterMarkers: line.gutterMarkers, + textClass: line.textClass, + bgClass: line.bgClass, + wrapClass: line.wrapClass, + widgets: line.widgets + }; + }, + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop2]) { + line[prop2] = cls; + } else if (classTest(cls).test(line[prop2])) { + return false; + } else { + line[prop2] += " " + cls; + } + return true; + }); + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop2]; + if (!cur) { + return false; + } else if (cls == null) { + line[prop2] = null; + } else { + var found = cur.match(classTest(cls)); + if (!found) { + return false; + } + var end = found.index + found[0].length; + line[prop2] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function(widget) { + widget.clear(); + }, + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); + }, + setBookmark: function(pos, options) { + var realOpts = { + replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, + shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents + }; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { + markers.push(span.marker.parent || span.marker); + } + } + } + return markers; + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); + to = clipPos(this, to); + var found = [], lineNo2 = from.line; + this.iter(from.line, to.line + 1, function(line) { + var spans = line.markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; i2++) { + var span = spans[i2]; + if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { + found.push(span.marker.parent || span.marker); + } + } + } + ++lineNo2; + }); + return found; + }, + getAllMarks: function() { + var markers = []; + this.iter(function(line) { + var sps = line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + if (sps[i2].from != null) { + markers.push(sps[i2].marker); + } + } + } + }); + return markers; + }, + posFromIndex: function(off2) { + var ch, lineNo2 = this.first, sepSize = this.lineSeparator().length; + this.iter(function(line) { + var sz = line.text.length + sepSize; + if (sz > off2) { + ch = off2; + return true; + } + off2 -= sz; + ++lineNo2; + }); + return clipPos(this, Pos(lineNo2, ch)); + }, + indexFromPos: function(coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) { + return 0; + } + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function(line) { + index += line.text.length + sepSize; + }); + return index; + }, + copy: function(copyHistory) { + var doc2 = new Doc( + getLines(this, this.first, this.first + this.size), + this.modeOption, + this.first, + this.lineSep, + this.direction + ); + doc2.scrollTop = this.scrollTop; + doc2.scrollLeft = this.scrollLeft; + doc2.sel = this.sel; + doc2.extend = false; + if (copyHistory) { + doc2.history.undoDepth = this.history.undoDepth; + doc2.setHistory(this.getHistory()); + } + return doc2; + }, + linkedDoc: function(options) { + if (!options) { + options = {}; + } + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) { + from = options.from; + } + if (options.to != null && options.to < to) { + to = options.to; + } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); + if (options.sharedHist) { + copy.history = this.history; + } + (this.linked || (this.linked = [])).push({ doc: copy, sharedHist: options.sharedHist }); + copy.linked = [{ doc: this, isParent: true, sharedHist: options.sharedHist }]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function(other) { + if (other instanceof CodeMirror) { + other = other.doc; + } + if (this.linked) { + for (var i2 = 0; i2 < this.linked.length; ++i2) { + var link = this.linked[i2]; + if (link.doc != other) { + continue; + } + this.linked.splice(i2, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + } + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function(doc2) { + return splitIds.push(doc2.id); + }, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) { + linkedDocs(this, f); + }, + getMode: function() { + return this.mode; + }, + getEditor: function() { + return this.cm; + }, + splitLines: function(str) { + if (this.lineSep) { + return str.split(this.lineSep); + } + return splitLinesAuto(str); + }, + lineSeparator: function() { + return this.lineSep || "\n"; + }, + setDirection: docMethodOp(function(dir) { + if (dir != "rtl") { + dir = "ltr"; + } + if (dir == this.direction) { + return; + } + this.direction = dir; + this.iter(function(line) { + return line.order = null; + }); + if (this.cm) { + directionChanged(this.cm); + } + }) + }); + Doc.prototype.eachLine = Doc.prototype.iter; + var lastDrop = 0; + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e_preventDefault(e); + if (ie) { + lastDrop = +/* @__PURE__ */ new Date(); + } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) { + return; + } + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var markAsReadAndPasteIfAllFilesAreRead = function() { + if (++read == n) { + operation(cm, function() { + pos = clipPos(cm.doc, pos); + var change = { + from: pos, + to: pos, + text: cm.doc.splitLines( + text.filter(function(t) { + return t != null; + }).join(cm.doc.lineSeparator()) + ), + origin: "paste" + }; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); + })(); + } + }; + var readTextFromFile = function(file, i3) { + if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + var reader = new FileReader(); + reader.onerror = function() { + return markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.onload = function() { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + text[i3] = content; + markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.readAsText(file); + }; + for (var i2 = 0; i2 < files.length; i2++) { + readTextFromFile(files[i2], i2); + } + } else { + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + setTimeout(function() { + return cm.display.input.focus(); + }, 20); + return; + } + try { + var text$1 = e.dataTransfer.getData("Text"); + if (text$1) { + var selected; + if (cm.state.draggingText && !cm.state.draggingText.copy) { + selected = cm.listSelections(); + } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i$12 = 0; i$12 < selected.length; ++i$12) { + replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag"); + } + } + cm.replaceSelection(text$1, "around", "paste"); + cm.display.input.focus(); + } + } catch (e$1) { + } + } + } + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +/* @__PURE__ */ new Date() - lastDrop < 100)) { + e_stop(e); + return; + } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove"; + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) { + img.parentNode.removeChild(img); + } + } + } + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) { + return; + } + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { + return; + } + var byClass = document.getElementsByClassName("CodeMirror"), editors = []; + for (var i2 = 0; i2 < byClass.length; i2++) { + var cm = byClass[i2].CodeMirror; + if (cm) { + editors.push(cm); + } + } + if (editors.length) { + editors[0].operation(function() { + for (var i3 = 0; i3 < editors.length; i3++) { + f(editors[i3]); + } + }); + } + } + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) { + return; + } + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + var resizeTimer; + on(window, "resize", function() { + if (resizeTimer == null) { + resizeTimer = setTimeout(function() { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + } + }); + on(window, "blur", function() { + return forEachCodeMirror(onBlur); + }); + } + function onResize(cm) { + var d = cm.display; + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + var keyNames = { + 3: "Pause", + 8: "Backspace", + 9: "Tab", + 13: "Enter", + 16: "Shift", + 17: "Ctrl", + 18: "Alt", + 19: "Pause", + 20: "CapsLock", + 27: "Esc", + 32: "Space", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "Left", + 38: "Up", + 39: "Right", + 40: "Down", + 44: "PrintScrn", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Mod", + 92: "Mod", + 93: "Mod", + 106: "*", + 107: "=", + 109: "-", + 110: ".", + 111: "/", + 145: "ScrollLock", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'", + 224: "Mod", + 63232: "Up", + 63233: "Down", + 63234: "Left", + 63235: "Right", + 63272: "Delete", + 63273: "Home", + 63275: "End", + 63276: "PageUp", + 63277: "PageDown", + 63302: "Insert" + }; + for (var i = 0; i < 10; i++) { + keyNames[i + 48] = keyNames[i + 96] = String(i); + } + for (var i$1 = 65; i$1 <= 90; i$1++) { + keyNames[i$1] = String.fromCharCode(i$1); + } + for (var i$2 = 1; i$2 <= 12; i$2++) { + keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; + } + var keyMap = {}; + keyMap.basic = { + "Left": "goCharLeft", + "Right": "goCharRight", + "Up": "goLineUp", + "Down": "goLineDown", + "End": "goLineEnd", + "Home": "goLineStartSmart", + "PageUp": "goPageUp", + "PageDown": "goPageDown", + "Delete": "delCharAfter", + "Backspace": "delCharBefore", + "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", + "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", + "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + keyMap.pcDefault = { + "Ctrl-A": "selectAll", + "Ctrl-D": "deleteLine", + "Ctrl-Z": "undo", + "Shift-Ctrl-Z": "redo", + "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", + "Ctrl-End": "goDocEnd", + "Ctrl-Up": "goLineUp", + "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", + "Ctrl-Right": "goGroupRight", + "Alt-Left": "goLineStart", + "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", + "Ctrl-Delete": "delGroupAfter", + "Ctrl-S": "save", + "Ctrl-F": "find", + "Ctrl-G": "findNext", + "Shift-Ctrl-G": "findPrev", + "Shift-Ctrl-F": "replace", + "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", + "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", + "Shift-Ctrl-U": "redoSelection", + "Alt-U": "redoSelection", + "fallthrough": "basic" + }; + keyMap.emacsy = { + "Ctrl-F": "goCharRight", + "Ctrl-B": "goCharLeft", + "Ctrl-P": "goLineUp", + "Ctrl-N": "goLineDown", + "Ctrl-A": "goLineStart", + "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", + "Shift-Ctrl-V": "goPageUp", + "Ctrl-D": "delCharAfter", + "Ctrl-H": "delCharBefore", + "Alt-Backspace": "delWordBefore", + "Ctrl-K": "killLine", + "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", + "Cmd-D": "deleteLine", + "Cmd-Z": "undo", + "Shift-Cmd-Z": "redo", + "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", + "Cmd-Up": "goDocStart", + "Cmd-End": "goDocEnd", + "Cmd-Down": "goDocEnd", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", + "Cmd-Left": "goLineLeft", + "Cmd-Right": "goLineRight", + "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", + "Alt-Delete": "delGroupAfter", + "Cmd-S": "save", + "Cmd-F": "find", + "Cmd-G": "findNext", + "Shift-Cmd-G": "findPrev", + "Cmd-Alt-F": "replace", + "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", + "Cmd-]": "indentMore", + "Cmd-Backspace": "delWrappedLineLeft", + "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", + "Shift-Cmd-U": "redoSelection", + "Ctrl-Up": "goDocStart", + "Ctrl-Down": "goDocEnd", + "fallthrough": ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/); + name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i2 = 0; i2 < parts.length - 1; i2++) { + var mod = parts[i2]; + if (/^(cmd|meta|m)$/i.test(mod)) { + cmd = true; + } else if (/^a(lt)?$/i.test(mod)) { + alt = true; + } else if (/^(c|ctrl|control)$/i.test(mod)) { + ctrl = true; + } else if (/^s(hift)?$/i.test(mod)) { + shift = true; + } else { + throw new Error("Unrecognized modifier name: " + mod); + } + } + if (alt) { + name = "Alt-" + name; + } + if (ctrl) { + name = "Ctrl-" + name; + } + if (cmd) { + name = "Cmd-" + name; + } + if (shift) { + name = "Shift-" + name; + } + return name; + } + function normalizeKeyMap(keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { + continue; + } + if (value == "...") { + delete keymap[keyname]; + continue; + } + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i2 = 0; i2 < keys.length; i2++) { + var val = void 0, name = void 0; + if (i2 == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i2 + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) { + copy[name] = val; + } else if (prev != val) { + throw new Error("Inconsistent bindings for " + name); + } + } + delete keymap[keyname]; + } + } + for (var prop2 in copy) { + keymap[prop2] = copy[prop2]; + } + return keymap; + } + function lookupKey(key, map2, handle, context) { + map2 = getKeyMap(map2); + var found = map2.call ? map2.call(key, context) : map2[key]; + if (found === false) { + return "nothing"; + } + if (found === "...") { + return "multi"; + } + if (found != null && handle(found)) { + return "handled"; + } + if (map2.fallthrough) { + if (Object.prototype.toString.call(map2.fallthrough) != "[object Array]") { + return lookupKey(key, map2.fallthrough, handle, context); + } + for (var i2 = 0; i2 < map2.fallthrough.length; i2++) { + var result = lookupKey(key, map2.fallthrough[i2], handle, context); + if (result) { + return result; + } + } + } + } + function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + function addModifierNames(name, event, noShift) { + var base = name; + if (event.altKey && base != "Alt") { + name = "Alt-" + name; + } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { + name = "Ctrl-" + name; + } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { + name = "Cmd-" + name; + } + if (!noShift && event.shiftKey && base != "Shift") { + name = "Shift-" + name; + } + return name; + } + function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { + return false; + } + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) { + return false; + } + if (event.keyCode == 3 && event.code) { + name = event.code; + } + return addModifierNames(name, event, noShift); + } + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + var toKill = compute(ranges[i2]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + runInOp(cm, function() { + for (var i3 = kill.length - 1; i3 >= 0; i3--) { + replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete"); + } + ensureCursorVisible(cm); + }); + } + function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir); + return target < 0 || target > line.text.length ? null : target; + } + function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir); + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before"); + } + function endOfLine(visually, cm, lineObj, lineNo2, dir) { + if (visually) { + if (cm.doc.direction == "rtl") { + dir = -dir; + } + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = dir < 0 ? lst(order) : order[0]; + var moveInStorageOrder = dir < 0 == (part.level == 1); + var sticky = moveInStorageOrder ? "after" : "before"; + var ch; + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj); + ch = dir < 0 ? lineObj.text.length - 1 : 0; + var targetTop = measureCharPrepared(cm, prep, ch).top; + ch = findFirst(function(ch2) { + return measureCharPrepared(cm, prep, ch2).top == targetTop; + }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch); + if (sticky == "before") { + ch = moveCharLogically(lineObj, ch, 1); + } + } else { + ch = dir < 0 ? part.to : part.from; + } + return new Pos(lineNo2, ch, sticky); + } + } + return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after"); + } + function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction); + if (!bidi) { + return moveLogically(line, start, dir); + } + if (start.ch >= line.text.length) { + start.ch = line.text.length; + start.sticky = "before"; + } else if (start.ch <= 0) { + start.ch = 0; + start.sticky = "after"; + } + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + return moveLogically(line, start, dir); + } + var mv = function(pos, dir2) { + return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2); + }; + var prep; + var getWrappedLineExtent = function(ch2) { + if (!cm.options.lineWrapping) { + return { begin: 0, end: line.text.length }; + } + prep = prep || prepareMeasureForLine(cm, line); + return wrappedLineExtentChar(cm, line, prep, ch2); + }; + var wrappedLineExtent2 = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = part.level == 1 == dir < 0; + var ch = mv(start, moveInStorageOrder ? 1 : -1); + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) { + var sticky = moveInStorageOrder ? "before" : "after"; + return new Pos(start.line, ch, sticky); + } + } + var searchInVisualLine = function(partPos2, dir2, wrappedLineExtent3) { + var getRes = function(ch3, moveInStorageOrder3) { + return moveInStorageOrder3 ? new Pos(start.line, mv(ch3, 1), "before") : new Pos(start.line, ch3, "after"); + }; + for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) { + var part2 = bidi[partPos2]; + var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1); + var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1); + if (part2.from <= ch2 && ch2 < part2.to) { + return getRes(ch2, moveInStorageOrder2); + } + ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1); + if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) { + return getRes(ch2, moveInStorageOrder2); + } + } + }; + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2); + if (res) { + return res; + } + var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1); + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); + if (res) { + return res; + } + } + return null; + } + var commands = { + selectAll, + singleSelection: function(cm) { + return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function(cm) { + return deleteNearSelection(cm, function(range2) { + if (range2.empty()) { + var len = getLine(cm.doc, range2.head.line).text.length; + if (range2.head.ch == len && range2.head.line < cm.lastLine()) { + return { from: range2.head, to: Pos(range2.head.line + 1, 0) }; + } else { + return { from: range2.head, to: Pos(range2.head.line, len) }; + } + } else { + return { from: range2.from(), to: range2.to() }; + } + }); + }, + deleteLine: function(cm) { + return deleteNearSelection(cm, function(range2) { + return { + from: Pos(range2.from().line, 0), + to: clipPos(cm.doc, Pos(range2.to().line + 1, 0)) + }; + }); + }, + delLineLeft: function(cm) { + return deleteNearSelection(cm, function(range2) { + return { + from: Pos(range2.from().line, 0), + to: range2.from() + }; + }); + }, + delWrappedLineLeft: function(cm) { + return deleteNearSelection(cm, function(range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var leftPos = cm.coordsChar({ left: 0, top }, "div"); + return { from: leftPos, to: range2.from() }; + }); + }, + delWrappedLineRight: function(cm) { + return deleteNearSelection(cm, function(range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var rightPos = cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top }, "div"); + return { from: range2.from(), to: rightPos }; + }); + }, + undo: function(cm) { + return cm.undo(); + }, + redo: function(cm) { + return cm.redo(); + }, + undoSelection: function(cm) { + return cm.undoSelection(); + }, + redoSelection: function(cm) { + return cm.redoSelection(); + }, + goDocStart: function(cm) { + return cm.extendSelection(Pos(cm.firstLine(), 0)); + }, + goDocEnd: function(cm) { + return cm.extendSelection(Pos(cm.lastLine())); + }, + goLineStart: function(cm) { + return cm.extendSelectionsBy( + function(range2) { + return lineStart(cm, range2.head.line); + }, + { origin: "+move", bias: 1 } + ); + }, + goLineStartSmart: function(cm) { + return cm.extendSelectionsBy( + function(range2) { + return lineStartSmart(cm, range2.head); + }, + { origin: "+move", bias: 1 } + ); + }, + goLineEnd: function(cm) { + return cm.extendSelectionsBy( + function(range2) { + return lineEnd(cm, range2.head.line); + }, + { origin: "+move", bias: -1 } + ); + }, + goLineRight: function(cm) { + return cm.extendSelectionsBy(function(range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top }, "div"); + }, sel_move); + }, + goLineLeft: function(cm) { + return cm.extendSelectionsBy(function(range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar({ left: 0, top }, "div"); + }, sel_move); + }, + goLineLeftSmart: function(cm) { + return cm.extendSelectionsBy(function(range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + var pos = cm.coordsChar({ left: 0, top }, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { + return lineStartSmart(cm, range2.head); + } + return pos; + }, sel_move); + }, + goLineUp: function(cm) { + return cm.moveV(-1, "line"); + }, + goLineDown: function(cm) { + return cm.moveV(1, "line"); + }, + goPageUp: function(cm) { + return cm.moveV(-1, "page"); + }, + goPageDown: function(cm) { + return cm.moveV(1, "page"); + }, + goCharLeft: function(cm) { + return cm.moveH(-1, "char"); + }, + goCharRight: function(cm) { + return cm.moveH(1, "char"); + }, + goColumnLeft: function(cm) { + return cm.moveH(-1, "column"); + }, + goColumnRight: function(cm) { + return cm.moveH(1, "column"); + }, + goWordLeft: function(cm) { + return cm.moveH(-1, "word"); + }, + goGroupRight: function(cm) { + return cm.moveH(1, "group"); + }, + goGroupLeft: function(cm) { + return cm.moveH(-1, "group"); + }, + goWordRight: function(cm) { + return cm.moveH(1, "word"); + }, + delCharBefore: function(cm) { + return cm.deleteH(-1, "codepoint"); + }, + delCharAfter: function(cm) { + return cm.deleteH(1, "char"); + }, + delWordBefore: function(cm) { + return cm.deleteH(-1, "word"); + }, + delWordAfter: function(cm) { + return cm.deleteH(1, "word"); + }, + delGroupBefore: function(cm) { + return cm.deleteH(-1, "group"); + }, + delGroupAfter: function(cm) { + return cm.deleteH(1, "group"); + }, + indentAuto: function(cm) { + return cm.indentSelection("smart"); + }, + indentMore: function(cm) { + return cm.indentSelection("add"); + }, + indentLess: function(cm) { + return cm.indentSelection("subtract"); + }, + insertTab: function(cm) { + return cm.replaceSelection(" "); + }, + insertSoftTab: function(cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i2 = 0; i2 < ranges.length; i2++) { + var pos = ranges[i2].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(spaceStr(tabSize - col % tabSize)); + } + cm.replaceSelections(spaces); + }, + defaultTab: function(cm) { + if (cm.somethingSelected()) { + cm.indentSelection("add"); + } else { + cm.execCommand("insertTab"); + } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function(cm) { + return runInOp(cm, function() { + var ranges = cm.listSelections(), newSel = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + if (!ranges[i2].empty()) { + continue; + } + var cur = ranges[i2].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) { + cur = new Pos(cur.line, cur.ch - 1); + } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange( + line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), + cur, + "+transpose" + ); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cur = new Pos(cur.line, 1); + cm.replaceRange( + line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), + cur, + "+transpose" + ); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function(cm) { + return runInOp(cm, function() { + var sels = cm.listSelections(); + for (var i2 = sels.length - 1; i2 >= 0; i2--) { + cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input"); + } + sels = cm.listSelections(); + for (var i$12 = 0; i$12 < sels.length; i$12++) { + cm.indentLine(sels[i$12].from().line, null, true); + } + ensureCursorVisible(cm); + }); + }, + openLine: function(cm) { + return cm.replaceSelection("\n", "start"); + }, + toggleOverwrite: function(cm) { + return cm.toggleOverwrite(); + } + }; + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, visual, lineN, 1); + } + function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLineEnd(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, line, lineN, -1); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line, cm.doc.direction); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); + } + return start; + } + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) { + return false; + } + } + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; + } + if (dropShift) { + cm.display.shift = false; + } + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + function lookupKeyForEditor(cm, name, handle) { + for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) { + var result = lookupKey(name, cm.state.keyMaps[i2], handle, cm); + if (result) { + return result; + } + } + return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm); + } + var stopSeq = new Delayed(); + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) { + return "handled"; + } + if (/\'$/.test(name)) { + cm.state.keySeq = null; + } else { + stopSeq.set(50, function() { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + } + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { + return true; + } + } + return dispatchKeyInner(cm, name, e, handle); + } + function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle); + if (result == "multi") { + cm.state.keySeq = name; + } + if (result == "handled") { + signalLater(cm, "keyHandled", cm, name, e); + } + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + return !!result; + } + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) { + return false; + } + if (e.shiftKey && !cm.state.keySeq) { + return dispatchKey(cm, "Shift-" + name, e, function(b) { + return doHandleBinding(cm, b, true); + }) || dispatchKey(cm, name, e, function(b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { + return doHandleBinding(cm, b); + } + }); + } else { + return dispatchKey(cm, name, e, function(b) { + return doHandleBinding(cm, b); + }); + } + } + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function(b) { + return doHandleBinding(cm, b, true); + }); + } + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; + } + cm.curOp.focus = activeElt(root(cm)); + if (signalDOMEvent(cm, e)) { + return; + } + if (ie && ie_version < 11 && e.keyCode == 27) { + e.returnValue = false; + } + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { + cm.replaceSelection("", null, "cut"); + } + } + if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { + document.execCommand("cut"); + } + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { + showCrossHair(cm); + } + } + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + function onKeyUp(e) { + if (e.keyCode == 16) { + this.doc.sel.shift = false; + } + signalDOMEvent(this, e); + } + function onKeyPress(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; + } + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { + return; + } + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) { + lastStoppedKey = null; + e_preventDefault(e); + return; + } + if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) { + return; + } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (ch == "\b") { + return; + } + if (handleCharBinding(cm, e, ch)) { + return; + } + cm.display.input.onKeyPress(e); + } + var DOUBLECLICK_DELAY = 400; + var PastClick = function(time, pos, button) { + this.time = time; + this.pos = pos; + this.button = button; + }; + PastClick.prototype.compare = function(time, pos, button) { + return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button; + }; + var lastClick, lastDoubleClick; + function clickRepeat(pos, button) { + var now = +/* @__PURE__ */ new Date(); + if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { + lastClick = lastDoubleClick = null; + return "triple"; + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button); + lastClick = null; + return "double"; + } else { + lastClick = new PastClick(now, pos, button); + lastDoubleClick = null; + return "single"; + } + } + function onMouseDown(e) { + var cm = this, display = cm.display; + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { + return; + } + display.input.ensurePolled(); + display.shift = e.shiftKey; + if (eventInWidget(display, e)) { + if (!webkit) { + display.scroller.draggable = false; + setTimeout(function() { + return display.scroller.draggable = true; + }, 100); + } + return; + } + if (clickInGutter(cm, e)) { + return; + } + var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; + win(cm).focus(); + if (button == 1 && cm.state.selectingText) { + cm.state.selectingText(e); + } + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { + return; + } + if (button == 1) { + if (pos) { + leftButtonDown(cm, pos, repeat, e); + } else if (e_target(e) == display.scroller) { + e_preventDefault(e); + } + } else if (button == 2) { + if (pos) { + extendSelection(cm.doc, pos); + } + setTimeout(function() { + return display.input.focus(); + }, 20); + } else if (button == 3) { + if (captureRightClick) { + cm.display.input.onContextMenu(e); + } else { + delayBlurEvent(cm); + } + } + } + function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click"; + if (repeat == "double") { + name = "Double" + name; + } else if (repeat == "triple") { + name = "Triple" + name; + } + name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; + return dispatchKey(cm, addModifierNames(name, event), event, function(bound) { + if (typeof bound == "string") { + bound = commands[bound]; + } + if (!bound) { + return false; + } + var done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; + } + done = bound(cm, pos) != Pass; + } finally { + cm.state.suppressEdits = false; + } + return done; + }); + } + function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse"); + var value = option ? option(cm, repeat, event) : {}; + if (value.unit == null) { + var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; + value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; + } + if (value.extend == null || cm.doc.extend) { + value.extend = cm.doc.extend || event.shiftKey; + } + if (value.addNew == null) { + value.addNew = mac ? event.metaKey : event.ctrlKey; + } + if (value.moveOnDrag == null) { + value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); + } + return value; + } + function leftButtonDown(cm, pos, repeat, event) { + if (ie) { + setTimeout(bind(ensureFocus, cm), 0); + } else { + cm.curOp.focus = activeElt(root(cm)); + } + var behavior = configureMouse(cm, repeat, event); + var sel = cm.doc.sel, contained; + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { + leftButtonStartDrag(cm, event, pos, behavior); + } else { + leftButtonSelect(cm, event, pos, behavior); + } + } + function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, moved = false; + var dragEnd = operation(cm, function(e) { + if (webkit) { + display.scroller.draggable = false; + } + cm.state.draggingText = false; + if (cm.state.delayingBlurEvent) { + if (cm.hasFocus()) { + cm.state.delayingBlurEvent = false; + } else { + delayBlurEvent(cm); + } + } + off(display.wrapper.ownerDocument, "mouseup", dragEnd); + off(display.wrapper.ownerDocument, "mousemove", mouseMove); + off(display.scroller, "dragstart", dragStart); + off(display.scroller, "drop", dragEnd); + if (!moved) { + e_preventDefault(e); + if (!behavior.addNew) { + extendSelection(cm.doc, pos, null, null, behavior.extend); + } + if (webkit && !safari || ie && ie_version == 9) { + setTimeout(function() { + display.wrapper.ownerDocument.body.focus({ preventScroll: true }); + display.input.focus(); + }, 20); + } else { + display.input.focus(); + } + } + }); + var mouseMove = function(e2) { + moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; + }; + var dragStart = function() { + return moved = true; + }; + if (webkit) { + display.scroller.draggable = true; + } + cm.state.draggingText = dragEnd; + dragEnd.copy = !behavior.moveOnDrag; + on(display.wrapper.ownerDocument, "mouseup", dragEnd); + on(display.wrapper.ownerDocument, "mousemove", mouseMove); + on(display.scroller, "dragstart", dragStart); + on(display.scroller, "drop", dragEnd); + cm.state.delayingBlurEvent = true; + setTimeout(function() { + return display.input.focus(); + }, 20); + if (display.scroller.dragDrop) { + display.scroller.dragDrop(); + } + } + function rangeForUnit(cm, pos, unit) { + if (unit == "char") { + return new Range(pos, pos); + } + if (unit == "word") { + return cm.findWordAt(pos); + } + if (unit == "line") { + return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + } + var result = unit(cm, pos); + return new Range(result.from, result.to); + } + function leftButtonSelect(cm, event, start, behavior) { + if (ie) { + delayBlurEvent(cm); + } + var display = cm.display, doc2 = cm.doc; + e_preventDefault(event); + var ourRange, ourIndex, startSel = doc2.sel, ranges = startSel.ranges; + if (behavior.addNew && !behavior.extend) { + ourIndex = doc2.sel.contains(start); + if (ourIndex > -1) { + ourRange = ranges[ourIndex]; + } else { + ourRange = new Range(start, start); + } + } else { + ourRange = doc2.sel.primary(); + ourIndex = doc2.sel.primIndex; + } + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { + ourRange = new Range(start, start); + } + start = posFromMouse(cm, event, true, true); + ourIndex = -1; + } else { + var range2 = rangeForUnit(cm, start, behavior.unit); + if (behavior.extend) { + ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend); + } else { + ourRange = range2; + } + } + if (!behavior.addNew) { + ourIndex = 0; + setSelection(doc2, new Selection([ourRange], 0), sel_mouse); + startSel = doc2.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection( + doc2, + normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), + { scroll: false, origin: "*mouse" } + ); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection( + doc2, + normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + { scroll: false, origin: "*mouse" } + ); + startSel = doc2.sel; + } else { + replaceOneSelection(doc2, ourIndex, ourRange, sel_mouse); + } + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { + return; + } + lastPos = pos; + if (behavior.unit == "rectangle") { + var ranges2 = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc2, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc2, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { + var text = getLine(doc2, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) { + ranges2.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); + } else if (text.length > leftPos) { + ranges2.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); + } + } + if (!ranges2.length) { + ranges2.push(new Range(start, start)); + } + setSelection( + doc2, + normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex), + { origin: "*mouse", scroll: false } + ); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var range3 = rangeForUnit(cm, pos, behavior.unit); + var anchor = oldRange.anchor, head; + if (cmp(range3.anchor, anchor) > 0) { + head = range3.head; + anchor = minPos(oldRange.from(), range3.anchor); + } else { + head = range3.anchor; + anchor = maxPos(oldRange.to(), range3.head); + } + var ranges$1 = startSel.ranges.slice(0); + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc2, anchor), head)); + setSelection(doc2, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); + } + } + var editorSize = display.wrapper.getBoundingClientRect(); + var counter = 0; + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); + if (!cur) { + return; + } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(root(cm)); + extendTo(cur); + var visible = visibleLines(display, doc2); + if (cur.line >= visible.to || cur.line < visible.from) { + setTimeout(operation(cm, function() { + if (counter == curCount) { + extend(e); + } + }), 150); + } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { + setTimeout(operation(cm, function() { + if (counter != curCount) { + return; + } + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + } + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + if (e) { + e_preventDefault(e); + display.input.focus(); + } + off(display.wrapper.ownerDocument, "mousemove", move); + off(display.wrapper.ownerDocument, "mouseup", up); + doc2.history.lastSelOrigin = null; + } + var move = operation(cm, function(e) { + if (e.buttons === 0 || !e_button(e)) { + done(e); + } else { + extend(e); + } + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(display.wrapper.ownerDocument, "mousemove", move); + on(display.wrapper.ownerDocument, "mouseup", up); + } + function bidiSimplify(cm, range2) { + var anchor = range2.anchor; + var head = range2.head; + var anchorLine = getLine(cm.doc, anchor.line); + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { + return range2; + } + var order = getOrder(anchorLine); + if (!order) { + return range2; + } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; + if (part.from != anchor.ch && part.to != anchor.ch) { + return range2; + } + var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1); + if (boundary == 0 || boundary == order.length) { + return range2; + } + var leftSide; + if (head.line != anchor.line) { + leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky); + var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); + if (headIndex == boundary - 1 || headIndex == boundary) { + leftSide = dir < 0; + } else { + leftSide = dir > 0; + } + } + var usePart = order[boundary + (leftSide ? -1 : 0)]; + var from = leftSide == (usePart.level == 1); + var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; + return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range(new Pos(anchor.line, ch, sticky), head); + } + function gutterEvent(cm, e, type, prevent) { + var mX, mY; + if (e.touches) { + mX = e.touches[0].clientX; + mY = e.touches[0].clientY; + } else { + try { + mX = e.clientX; + mY = e.clientY; + } catch (e$1) { + return false; + } + } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { + return false; + } + if (prevent) { + e_preventDefault(e); + } + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + if (mY > lineBox.bottom || !hasHandler(cm, type)) { + return e_defaultPrevented(e); + } + mY -= lineBox.top - display.viewOffset; + for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) { + var g = display.gutters.childNodes[i2]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.display.gutterSpecs[i2]; + signal(cm, type, cm, line, gutter.className, e); + return e_defaultPrevented(e); + } + } + } + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true); + } + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { + return; + } + if (signalDOMEvent(cm, e, "contextmenu")) { + return; + } + if (!captureRightClick) { + cm.display.input.onContextMenu(e); + } + } + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { + return false; + } + return gutterEvent(cm, e, "gutterContextMenu", false); + } + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + var Init = { toString: function() { + return "CodeMirror.Init"; + } }; + var defaults = {}; + var optionHandlers = {}; + function defineOptions(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + function option(name, deflt, handle, notOnInit) { + CodeMirror2.defaults[name] = deflt; + if (handle) { + optionHandlers2[name] = notOnInit ? function(cm, val, old) { + if (old != Init) { + handle(cm, val, old); + } + } : handle; + } + } + CodeMirror2.defineOption = option; + CodeMirror2.Init = Init; + option("value", "", function(cm, val) { + return cm.setValue(val); + }, true); + option("mode", null, function(cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function(cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("lineSeparator", null, function(cm, val) { + cm.doc.lineSep = val; + if (!val) { + return; + } + var newBreaks = [], lineNo2 = cm.doc.first; + cm.doc.iter(function(line) { + for (var pos = 0; ; ) { + var found = line.text.indexOf(val, pos); + if (found == -1) { + break; + } + pos = found + val.length; + newBreaks.push(Pos(lineNo2, found)); + } + lineNo2++; + }); + for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) { + replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length)); + } + }); + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function(cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test(" ") ? "" : "| "), "g"); + if (old != Init) { + cm.refresh(); + } + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) { + return cm.refresh(); + }, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function() { + throw new Error("inputStyle can not (yet) be changed in a running editor"); + }, true); + option("spellcheck", false, function(cm, val) { + return cm.getInputField().spellcheck = val; + }, true); + option("autocorrect", false, function(cm, val) { + return cm.getInputField().autocorrect = val; + }, true); + option("autocapitalize", false, function(cm, val) { + return cm.getInputField().autocapitalize = val; + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + option("theme", "default", function(cm) { + themeChanged(cm); + updateGutters(cm); + }, true); + option("keyMap", "default", function(cm, val, old) { + var next = getKeyMap(val); + var prev = old != Init && getKeyMap(old); + if (prev && prev.detach) { + prev.detach(cm, next); + } + if (next.attach) { + next.attach(cm, prev || null); + } + }); + option("extraKeys", null); + option("configureMouse", null); + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function(cm, val) { + cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); + updateGutters(cm); + }, true); + option("fixedGutter", true, function(cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function(cm) { + return updateScrollbars(cm); + }, true); + option("scrollbarStyle", "native", function(cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function(cm, val) { + cm.display.gutterSpecs = getGutters(cm.options.gutters, val); + updateGutters(cm); + }, true); + option("firstLineNumber", 1, updateGutters, true); + option("lineNumberFormatter", function(integer) { + return integer; + }, updateGutters, true); + option("showCursorWhenSelecting", false, updateSelection, true); + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + option("selectionsMayTouch", false); + option("readOnly", false, function(cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + } + cm.display.input.readOnlyChanged(val); + }); + option("screenReaderLabel", null, function(cm, val) { + val = val === "" ? null : val; + cm.display.input.screenReaderLabelChanged(val); + }); + option("disableInput", false, function(cm, val) { + if (!val) { + cm.display.input.reset(); + } + }, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function(cm, val) { + return cm.doc.history.undoDepth = val; + }); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function(cm) { + return cm.refresh(); + }, true); + option("maxHighlightLength", 1e4, resetModeState, true); + option("moveInputWithCursor", true, function(cm, val) { + if (!val) { + cm.display.input.resetPosition(); + } + }); + option("tabindex", null, function(cm, val) { + return cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + option("direction", "ltr", function(cm, val) { + return cm.doc.setDirection(val); + }, true); + option("phrases", null); + } + function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function() { + return updateScrollbars(cm); + }, 100); + } + function CodeMirror(place, options) { + var this$1$1 = this; + if (!(this instanceof CodeMirror)) { + return new CodeMirror(place, options); + } + this.options = options = options ? copyObj(options) : {}; + copyObj(defaults, options, false); + var doc2 = options.value; + if (typeof doc2 == "string") { + doc2 = new Doc(doc2, options.mode, null, options.lineSeparator, options.direction); + } else if (options.mode) { + doc2.modeOption = options.mode; + } + this.doc = doc2; + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc2, input, options); + display.wrapper.CodeMirror = this; + themeChanged(this); + if (options.lineWrapping) { + this.display.wrapper.className += " CodeMirror-wrap"; + } + initScrollbars(this); + this.state = { + keyMaps: [], + // stores maps added by addKeyMap + overlays: [], + // highlighting overlays, as added by addOverlay + modeGen: 0, + // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, + // used to disable editing during key handlers when in readOnly mode + pasteIncoming: -1, + cutIncoming: -1, + // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), + // stores highlight worker timeout + keySeq: null, + // Unfinished key sequence + specialChars: null + }; + if (options.autofocus && !mobile) { + display.input.focus(); + } + if (ie && ie_version < 11) { + setTimeout(function() { + return this$1$1.display.input.reset(true); + }, 20); + } + registerEventHandlers(this); + ensureGlobalHandlers(); + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc2); + if (options.autofocus && !mobile || this.hasFocus()) { + setTimeout(function() { + if (this$1$1.hasFocus() && !this$1$1.state.focused) { + onFocus(this$1$1); + } + }, 20); + } else { + onBlur(this); + } + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) { + optionHandlers[opt](this, options[opt], Init); + } + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) { + options.finishInit(this); + } + for (var i2 = 0; i2 < initHooks.length; ++i2) { + initHooks[i2](this); + } + endOperation(this); + if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { + display.lineDiv.style.textRendering = "auto"; + } + } + CodeMirror.defaults = defaults; + CodeMirror.optionHandlers = optionHandlers; + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + if (ie && ie_version < 11) { + on(d.scroller, "dblclick", operation(cm, function(e) { + if (signalDOMEvent(cm, e)) { + return; + } + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + } else { + on(d.scroller, "dblclick", function(e) { + return signalDOMEvent(cm, e) || e_preventDefault(e); + }); + } + on(d.scroller, "contextmenu", function(e) { + return onContextMenu(cm, e); + }); + on(d.input.getField(), "contextmenu", function(e) { + if (!d.scroller.contains(e.target)) { + onContextMenu(cm, e); + } + }); + var touchFinished, prevTouch = { end: 0 }; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function() { + return d.activeTouch = null; + }, 1e3); + prevTouch = d.activeTouch; + prevTouch.end = +/* @__PURE__ */ new Date(); + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { + return false; + } + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway(touch, other) { + if (other.left == null) { + return true; + } + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function(e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { + d.input.ensurePolled(); + clearTimeout(touchFinished); + var now = +/* @__PURE__ */ new Date(); + d.activeTouch = { + start: now, + moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null + }; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function() { + if (d.activeTouch) { + d.activeTouch.moved = true; + } + }); + on(d.scroller, "touchend", function(e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && /* @__PURE__ */ new Date() - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range2; + if (!touch.prev || farAway(touch, touch.prev)) { + range2 = new Range(pos, pos); + } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) { + range2 = cm.findWordAt(pos); + } else { + range2 = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + } + cm.setSelection(range2.anchor, range2.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + on(d.scroller, "scroll", function() { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + on(d.scroller, "mousewheel", function(e) { + return onScrollWheel(cm, e); + }); + on(d.scroller, "DOMMouseScroll", function(e) { + return onScrollWheel(cm, e); + }); + on(d.wrapper, "scroll", function() { + return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; + }); + d.dragFunctions = { + enter: function(e) { + if (!signalDOMEvent(cm, e)) { + e_stop(e); + } + }, + over: function(e) { + if (!signalDOMEvent(cm, e)) { + onDragOver(cm, e); + e_stop(e); + } + }, + start: function(e) { + return onDragStart(cm, e); + }, + drop: operation(cm, onDrop), + leave: function(e) { + if (!signalDOMEvent(cm, e)) { + clearDragCursor(cm); + } + } + }; + var inp = d.input.getField(); + on(inp, "keyup", function(e) { + return onKeyUp.call(cm, e); + }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", function(e) { + return onFocus(cm, e); + }); + on(inp, "blur", function(e) { + return onBlur(cm, e); + }); + } + var initHooks = []; + CodeMirror.defineInitHook = function(f) { + return initHooks.push(f); + }; + function indentLine(cm, n, how, aggressive) { + var doc2 = cm.doc, state; + if (how == null) { + how = "add"; + } + if (how == "smart") { + if (!doc2.mode.indent) { + how = "prev"; + } else { + state = getContextBefore(cm, n).state; + } + } + var tabSize = cm.options.tabSize; + var line = getLine(doc2, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) { + line.stateAfter = null; + } + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc2.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) { + return; + } + how = "prev"; + } + } + if (how == "prev") { + if (n > doc2.first) { + indentation = countColumn(getLine(doc2, n - 1).text, null, tabSize); + } else { + indentation = 0; + } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) { + for (var i2 = Math.floor(indentation / tabSize); i2; --i2) { + pos += tabSize; + indentString += " "; + } + } + if (pos < indentation) { + indentString += spaceStr(indentation - pos); + } + if (indentString != curSpaceString) { + replaceRange(doc2, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } else { + for (var i$12 = 0; i$12 < doc2.sel.ranges.length; i$12++) { + var range2 = doc2.sel.ranges[i$12]; + if (range2.head.line == n && range2.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length); + replaceOneSelection(doc2, i$12, new Range(pos$1, pos$1)); + break; + } + } + } + } + var lastCopied = null; + function setLastCopied(newLastCopied) { + lastCopied = newLastCopied; + } + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc2 = cm.doc; + cm.display.shift = false; + if (!sel) { + sel = doc2.sel; + } + var recent = +/* @__PURE__ */ new Date() - 200; + var paste = origin == "paste" || cm.state.pasteIncoming > recent; + var textLines = splitLinesAuto(inserted), multiPaste = null; + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i2 = 0; i2 < lastCopied.text.length; i2++) { + multiPaste.push(doc2.splitLines(lastCopied.text[i2])); + } + } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, function(l) { + return [l]; + }); + } + } + var updateInput = cm.curOp.updateInput; + for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) { + var range2 = sel.ranges[i$12]; + var from = range2.from(), to = range2.to(); + if (range2.empty()) { + if (deleted && deleted > 0) { + from = Pos(from.line, from.ch - deleted); + } else if (cm.state.overwrite && !paste) { + to = Pos(to.line, Math.min(getLine(doc2, to.line).text.length, to.ch + lst(textLines).length)); + } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { + from = to = Pos(from.line, 0); + } + } + var changeEvent = { + from, + to, + text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input") + }; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) { + triggerElectric(cm, inserted); + } + ensureCursorVisible(cm); + if (cm.curOp.updateInput < 2) { + cm.curOp.updateInput = updateInput; + } + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = -1; + } + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus()) { + runInOp(cm, function() { + return applyTextInput(cm, pasted, 0, null, "paste"); + }); + } + return true; + } + } + function triggerElectric(cm, inserted) { + if (!cm.options.electricChars || !cm.options.smartIndent) { + return; + } + var sel = cm.doc.sel; + for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { + var range2 = sel.ranges[i2]; + if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) { + continue; + } + var mode = cm.getModeAt(range2.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range2.head.line, "smart"); + break; + } + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) { + indented = indentLine(cm, range2.head.line, "smart"); + } + } + if (indented) { + signalLater(cm, "electricInput", cm, range2.head.line); + } + } + } + function copyableRanges(cm) { + var text = [], ranges = []; + for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { + var line = cm.doc.sel.ranges[i2].head.line; + var lineRange = { anchor: Pos(line, 0), head: Pos(line + 1, 0) }; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return { text, ranges }; + } + function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { + field.setAttribute("autocorrect", autocorrect ? "on" : "off"); + field.setAttribute("autocapitalize", autocapitalize ? "on" : "off"); + field.setAttribute("spellcheck", !!spellcheck); + } + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + if (webkit) { + te.style.width = "1000px"; + } else { + te.setAttribute("wrap", "off"); + } + if (ios) { + te.style.border = "1px solid black"; + } + return div; + } + function addEditorMethods(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + var helpers = CodeMirror2.helpers = {}; + CodeMirror2.prototype = { + constructor: CodeMirror2, + focus: function() { + win(this).focus(); + this.display.input.focus(); + }, + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") { + return; + } + options[option] = value; + if (optionHandlers2.hasOwnProperty(option)) { + operation(this, optionHandlers2[option])(this, value, old); + } + signal(this, "optionChange", this, option); + }, + getOption: function(option) { + return this.options[option]; + }, + getDoc: function() { + return this.doc; + }, + addKeyMap: function(map2, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map2)); + }, + removeKeyMap: function(map2) { + var maps = this.state.keyMaps; + for (var i2 = 0; i2 < maps.length; ++i2) { + if (maps[i2] == map2 || maps[i2].name == map2) { + maps.splice(i2, 1); + return true; + } + } + }, + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror2.getMode(this.options, spec); + if (mode.startState) { + throw new Error("Overlays may not be stateful."); + } + insertSorted( + this.state.overlays, + { + mode, + modeSpec: spec, + opaque: options && options.opaque, + priority: options && options.priority || 0 + }, + function(overlay) { + return overlay.priority; + } + ); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function(spec) { + var overlays = this.state.overlays; + for (var i2 = 0; i2 < overlays.length; ++i2) { + var cur = overlays[i2].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i2, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { + dir = this.options.smartIndent ? "smart" : "prev"; + } else { + dir = dir ? "add" : "subtract"; + } + } + if (isLine(this.doc, n)) { + indentLine(this, n, dir, aggressive); + } + }), + indentSelection: methodOp(function(how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i2 = 0; i2 < ranges.length; i2++) { + var range2 = ranges[i2]; + if (!range2.empty()) { + var from = range2.from(), to = range2.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) { + indentLine(this, j, how); + } + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) { + replaceOneSelection(this.doc, i2, new Range(from, newRanges[i2].to()), sel_dontScroll); + } + } else if (range2.head.line > end) { + indentLine(this, range2.head.line, how, true); + end = range2.head.line; + if (i2 == this.doc.sel.primIndex) { + ensureCursorVisible(this); + } + } + } + }), + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise); + }, + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) { + type = styles[2]; + } else { + for (; ; ) { + var mid = before + after >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { + after = mid; + } else if (styles[mid * 2 + 1] < ch) { + before = mid + 1; + } else { + type = styles[mid * 2 + 2]; + break; + } + } + } + var cut = type ? type.indexOf("overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + getModeAt: function(pos) { + var mode = this.doc.mode; + if (!mode.innerMode) { + return mode; + } + return CodeMirror2.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0]; + }, + getHelpers: function(pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) { + return found; + } + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) { + found.push(help[mode[type]]); + } + } else if (mode[type]) { + for (var i2 = 0; i2 < mode[type].length; i2++) { + var val = help[mode[type][i2]]; + if (val) { + found.push(val); + } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i$12 = 0; i$12 < help._global.length; i$12++) { + var cur = help._global[i$12]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { + found.push(cur.val); + } + } + return found; + }, + getStateAfter: function(line, precise) { + var doc2 = this.doc; + line = clipLine(doc2, line == null ? doc2.first + doc2.size - 1 : line); + return getContextBefore(this, line + 1, precise).state; + }, + cursorCoords: function(start, mode) { + var pos, range2 = this.doc.sel.primary(); + if (start == null) { + pos = range2.head; + } else if (typeof start == "object") { + pos = clipPos(this.doc, start); + } else { + pos = start ? range2.from() : range2.to(); + } + return cursorCoords(this, pos, mode || "page"); + }, + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, { top: height, left: 0 }, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function(line, mode, includeWidgets) { + var end = false, lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) { + line = this.doc.first; + } else if (line > last) { + line = last; + end = true; + } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, { top: 0, left: 0 }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + defaultTextHeight: function() { + return textHeight(this.display); + }, + defaultCharWidth: function() { + return charWidth(this.display); + }, + getViewport: function() { + return { from: this.display.viewFrom, to: this.display.viewTo }; + }, + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { + top = pos.top - node.offsetHeight; + } else if (pos.bottom + node.offsetHeight <= vspace) { + top = pos.bottom; + } + if (left + node.offsetWidth > hspace) { + left = hspace - node.offsetWidth; + } + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") { + left = 0; + } else if (horiz == "middle") { + left = (display.sizer.clientWidth - node.offsetWidth) / 2; + } + node.style.left = left + "px"; + } + if (scroll) { + scrollIntoView(this, { left, top, right: left + node.offsetWidth, bottom: top + node.offsetHeight }); + } + }, + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) { + return commands[cmd].call(null, this); + } + }, + triggerElectric: methodOp(function(text) { + triggerElectric(this, text); + }), + findPosH: function(from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveH: methodOp(function(dir, unit) { + var this$1$1 = this; + this.extendSelectionsBy(function(range2) { + if (this$1$1.display.shift || this$1$1.doc.extend || range2.empty()) { + return findPosH(this$1$1.doc, range2.head, dir, unit, this$1$1.options.rtlMoveVisually); + } else { + return dir < 0 ? range2.from() : range2.to(); + } + }, sel_move); + }), + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc2 = this.doc; + if (sel.somethingSelected()) { + doc2.replaceSelection("", null, "+delete"); + } else { + deleteNearSelection(this, function(range2) { + var other = findPosH(doc2, range2.head, dir, unit, false); + return dir < 0 ? { from: other, to: range2.head } : { from: range2.head, to: other }; + }); + } + }), + findPosV: function(from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) { + x = coords.left; + } else { + coords.left = x; + } + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveV: methodOp(function(dir, unit) { + var this$1$1 = this; + var doc2 = this.doc, goals = []; + var collapse = !this.display.shift && !doc2.extend && doc2.sel.somethingSelected(); + doc2.extendSelectionsBy(function(range2) { + if (collapse) { + return dir < 0 ? range2.from() : range2.to(); + } + var headPos = cursorCoords(this$1$1, range2.head, "div"); + if (range2.goalColumn != null) { + headPos.left = range2.goalColumn; + } + goals.push(headPos.left); + var pos = findPosV(this$1$1, headPos, dir, unit); + if (unit == "page" && range2 == doc2.sel.primary()) { + addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top); + } + return pos; + }, sel_move); + if (goals.length) { + for (var i2 = 0; i2 < doc2.sel.ranges.length; i2++) { + doc2.sel.ranges[i2].goalColumn = goals[i2]; + } + } + }), + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc2 = this.doc, line = getLine(doc2, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.sticky == "before" || end == line.length) && start) { + --start; + } else { + ++end; + } + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) ? function(ch) { + return isWordChar(ch, helper); + } : /\s/.test(startChar) ? function(ch) { + return /\s/.test(ch); + } : function(ch) { + return !/\s/.test(ch) && !isWordChar(ch); + }; + while (start > 0 && check(line.charAt(start - 1))) { + --start; + } + while (end < line.length && check(line.charAt(end))) { + ++end; + } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) { + return; + } + if (this.state.overwrite = !this.state.overwrite) { + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); + } else { + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); + } + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function() { + return this.display.input.getField() == activeElt(root(this)); + }, + isReadOnly: function() { + return !!(this.options.readOnly || this.doc.cantEdit); + }, + scrollTo: methodOp(function(x, y) { + scrollToCoords(this, x, y); + }), + getScrollInfo: function() { + var scroller = this.display.scroller; + return { + left: scroller.scrollLeft, + top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), + clientWidth: displayWidth(this) + }; + }, + scrollIntoView: methodOp(function(range2, margin) { + if (range2 == null) { + range2 = { from: this.doc.sel.primary().head, to: null }; + if (margin == null) { + margin = this.options.cursorScrollMargin; + } + } else if (typeof range2 == "number") { + range2 = { from: Pos(range2, 0), to: null }; + } else if (range2.from == null) { + range2 = { from: range2, to: null }; + } + if (!range2.to) { + range2.to = range2.from; + } + range2.margin = margin || 0; + if (range2.from.line != null) { + scrollToRange(this, range2); + } else { + scrollToCoordsRange(this, range2.from, range2.to, range2.margin); + } + }), + setSize: methodOp(function(width, height) { + var this$1$1 = this; + var interpret = function(val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + }; + if (width != null) { + this.display.wrapper.style.width = interpret(width); + } + if (height != null) { + this.display.wrapper.style.height = interpret(height); + } + if (this.options.lineWrapping) { + clearLineMeasurementCache(this); + } + var lineNo2 = this.display.viewFrom; + this.doc.iter(lineNo2, this.display.viewTo, function(line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].noHScroll) { + regLineChange(this$1$1, lineNo2, "widget"); + break; + } + } + } + ++lineNo2; + }); + this.curOp.forceUpdate = true; + signal(this, "refresh", this); + }), + operation: function(f) { + return runInOp(this, f); + }, + startOperation: function() { + return startOperation(this); + }, + endOperation: function() { + return endOperation(this); + }, + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this.display); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) { + estimateLineHeights(this); + } + signal(this, "refresh", this); + }), + swapDoc: methodOp(function(doc2) { + var old = this.doc; + old.cm = null; + if (this.state.selectingText) { + this.state.selectingText(); + } + attachDoc(this, doc2); + clearCaches(this); + this.display.input.reset(); + scrollToCoords(this, doc2.scrollLeft, doc2.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + phrase: function(phraseText) { + var phrases = this.options.phrases; + return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText; + }, + getInputField: function() { + return this.display.input.getField(); + }, + getWrapperElement: function() { + return this.display.wrapper; + }, + getScrollerElement: function() { + return this.display.scroller; + }, + getGutterElement: function() { + return this.display.gutters; + } + }; + eventMixin(CodeMirror2); + CodeMirror2.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { + helpers[type] = CodeMirror2[type] = { _global: [] }; + } + helpers[type][name] = value; + }; + CodeMirror2.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror2.registerHelper(type, name, value); + helpers[type]._global.push({ pred: predicate, val: value }); + }; + } + function findPosH(doc2, pos, dir, unit, visually) { + var oldPos = pos; + var origDir = dir; + var lineObj = getLine(doc2, pos.line); + var lineDir = visually && doc2.direction == "rtl" ? -dir : dir; + function findNextLine() { + var l = pos.line + lineDir; + if (l < doc2.first || l >= doc2.first + doc2.size) { + return false; + } + pos = new Pos(l, pos.ch, pos.sticky); + return lineObj = getLine(doc2, l); + } + function moveOnce(boundToLine) { + var next; + if (unit == "codepoint") { + var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); + if (isNaN(ch)) { + next = null; + } else { + var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343; + next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); + } + } else if (visually) { + next = moveVisually(doc2.cm, lineObj, pos, dir); + } else { + next = moveLogically(lineObj, pos, dir); + } + if (next == null) { + if (!boundToLine && findNextLine()) { + pos = endOfLine(visually, doc2.cm, lineObj, pos.line, lineDir); + } else { + return false; + } + } else { + pos = next; + } + return true; + } + if (unit == "char" || unit == "codepoint") { + moveOnce(); + } else if (unit == "column") { + moveOnce(true); + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc2.cm && doc2.cm.getHelper(pos, "wordChars"); + for (var first = true; ; first = false) { + if (dir < 0 && !moveOnce(!first)) { + break; + } + var cur = lineObj.text.charAt(pos.ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; + if (group && !first && !type) { + type = "s"; + } + if (sawType && sawType != type) { + if (dir < 0) { + dir = 1; + moveOnce(); + pos.sticky = "after"; + } + break; + } + if (type) { + sawType = type; + } + if (dir > 0 && !moveOnce(!first)) { + break; + } + } + } + var result = skipAtomic(doc2, pos, oldPos, origDir, true); + if (equalCursorPos(oldPos, result)) { + result.hitSide = true; + } + return result; + } + function findPosV(cm, pos, dir, unit) { + var doc2 = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc2(cm).documentElement.clientHeight); + var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3); + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + var target; + for (; ; ) { + target = coordsChar(cm, x, y); + if (!target.outside) { + break; + } + if (dir < 0 ? y <= 0 : y >= doc2.height) { + target.hitSide = true; + break; + } + y += dir * 5; + } + return target; + } + var ContentEditableInput = function(cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.composing = null; + this.gracePeriod = false; + this.readDOMTimeout = null; + }; + ContentEditableInput.prototype.init = function(display) { + var this$1$1 = this; + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = true; + disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); + function belongsToInput(e) { + for (var t = e.target; t; t = t.parentNode) { + if (t == div) { + return true; + } + if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { + break; + } + } + return false; + } + on(div, "paste", function(e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; + } + if (ie_version <= 11) { + setTimeout(operation(cm, function() { + return this$1$1.updateFromDOM(); + }), 20); + } + }); + on(div, "compositionstart", function(e) { + this$1$1.composing = { data: e.data, done: false }; + }); + on(div, "compositionupdate", function(e) { + if (!this$1$1.composing) { + this$1$1.composing = { data: e.data, done: false }; + } + }); + on(div, "compositionend", function(e) { + if (this$1$1.composing) { + if (e.data != this$1$1.composing.data) { + this$1$1.readFromDOMSoon(); + } + this$1$1.composing.done = true; + } + }); + on(div, "touchstart", function() { + return input.forceCompositionEnd(); + }); + on(div, "input", function() { + if (!this$1$1.composing) { + this$1$1.readFromDOMSoon(); + } + }); + function onCopyCut(e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ lineWise: false, text: cm.getSelections() }); + if (e.type == "cut") { + cm.replaceSelection("", null, "cut"); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ lineWise: true, text: ranges.text }); + if (e.type == "cut") { + cm.operation(function() { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + if (e.clipboardData) { + e.clipboardData.clearData(); + var content = lastCopied.text.join("\n"); + e.clipboardData.setData("Text", content); + if (e.clipboardData.getData("Text") == content) { + e.preventDefault(); + return; + } + } + var kludge = hiddenTextarea(), te = kludge.firstChild; + disableBrowserMagic(te); + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.text.join("\n"); + var hadFocus = activeElt(rootNode(div)); + selectInput(te); + setTimeout(function() { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + if (hadFocus == div) { + input.showPrimarySelection(); + } + }, 50); + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }; + ContentEditableInput.prototype.screenReaderLabelChanged = function(label) { + if (label) { + this.div.setAttribute("aria-label", label); + } else { + this.div.removeAttribute("aria-label"); + } + }; + ContentEditableInput.prototype.prepareSelection = function() { + var result = prepareSelection(this.cm, false); + result.focus = activeElt(rootNode(this.div)) == this.div; + return result; + }; + ContentEditableInput.prototype.showSelection = function(info, takeFocus) { + if (!info || !this.cm.display.view.length) { + return; + } + if (info.focus || takeFocus) { + this.showPrimarySelection(); + } + this.showMultipleSelections(info); + }; + ContentEditableInput.prototype.getSelection = function() { + return this.cm.display.wrapper.ownerDocument.getSelection(); + }; + ContentEditableInput.prototype.showPrimarySelection = function() { + var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); + var from = prim.from(), to = prim.to(); + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges(); + return; + } + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { + return; + } + var view = cm.display.view; + var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { node: view[0].measure.map[2], offset: 0 }; + var end = to.line < cm.display.viewTo && posToDOM(cm, to); + if (!end) { + var measure = view[view.length - 1].measure; + var map2 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = { node: map2[map2.length - 1], offset: map2[map2.length - 2] - map2[map2.length - 3] }; + } + if (!start || !end) { + sel.removeAllRanges(); + return; + } + var old = sel.rangeCount && sel.getRangeAt(0), rng; + try { + rng = range(start.node, start.offset, end.offset, end.node); + } catch (e) { + } + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) { + sel.removeAllRanges(); + sel.addRange(rng); + } + } else { + sel.removeAllRanges(); + sel.addRange(rng); + } + if (old && sel.anchorNode == null) { + sel.addRange(old); + } else if (gecko) { + this.startGracePeriod(); + } + } + this.rememberSelection(); + }; + ContentEditableInput.prototype.startGracePeriod = function() { + var this$1$1 = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function() { + this$1$1.gracePeriod = false; + if (this$1$1.selectionChanged()) { + this$1$1.cm.operation(function() { + return this$1$1.cm.curOp.selectionChanged = true; + }); + } + }, 20); + }; + ContentEditableInput.prototype.showMultipleSelections = function(info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }; + ContentEditableInput.prototype.rememberSelection = function() { + var sel = this.getSelection(); + this.lastAnchorNode = sel.anchorNode; + this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; + this.lastFocusOffset = sel.focusOffset; + }; + ContentEditableInput.prototype.selectionInEditor = function() { + var sel = this.getSelection(); + if (!sel.rangeCount) { + return false; + } + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }; + ContentEditableInput.prototype.focus = function() { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor() || activeElt(rootNode(this.div)) != this.div) { + this.showSelection(this.prepareSelection(), true); + } + this.div.focus(); + } + }; + ContentEditableInput.prototype.blur = function() { + this.div.blur(); + }; + ContentEditableInput.prototype.getField = function() { + return this.div; + }; + ContentEditableInput.prototype.supportsTouch = function() { + return true; + }; + ContentEditableInput.prototype.receivedFocus = function() { + var this$1$1 = this; + var input = this; + if (this.selectionInEditor()) { + setTimeout(function() { + return this$1$1.pollSelection(); + }, 20); + } else { + runInOp(this.cm, function() { + return input.cm.curOp.selectionChanged = true; + }); + } + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }; + ContentEditableInput.prototype.selectionChanged = function() { + var sel = this.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }; + ContentEditableInput.prototype.pollSelection = function() { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { + return; + } + var sel = this.getSelection(), cm = this.cm; + if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({ type: "keydown", keyCode: 8, preventDefault: Math.abs }); + this.blur(); + this.focus(); + return; + } + if (this.composing) { + return; + } + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function() { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) { + cm.curOp.selectionChanged = true; + } + }); + } + }; + ContentEditableInput.prototype.pollContent = function() { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout); + this.readDOMTimeout = null; + } + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.ch == 0 && from.line > cm.firstLine()) { + from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); + } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { + to = Pos(to.line + 1, 0); + } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { + return false; + } + var fromIndex, fromLine, fromNode; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line); + fromNode = display.view[0].node; + } else { + fromLine = lineNo(display.view[fromIndex].line); + fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + var toLine, toNode; + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1; + toNode = display.lineDiv.lastChild; + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1; + toNode = display.view[toIndex + 1].node.previousSibling; + } + if (!fromNode) { + return false; + } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { + newText.pop(); + oldText.pop(); + toLine--; + } else if (newText[0] == oldText[0]) { + newText.shift(); + oldText.shift(); + fromLine++; + } else { + break; + } + } + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { + ++cutFront; + } + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min( + newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0) + ); + while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + ++cutEnd; + } + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront--; + cutEnd++; + } + } + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }; + ContentEditableInput.prototype.ensurePolled = function() { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.reset = function() { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.forceCompositionEnd = function() { + if (!this.composing) { + return; + } + clearTimeout(this.readDOMTimeout); + this.composing = null; + this.updateFromDOM(); + this.div.blur(); + this.div.focus(); + }; + ContentEditableInput.prototype.readFromDOMSoon = function() { + var this$1$1 = this; + if (this.readDOMTimeout != null) { + return; + } + this.readDOMTimeout = setTimeout(function() { + this$1$1.readDOMTimeout = null; + if (this$1$1.composing) { + if (this$1$1.composing.done) { + this$1$1.composing = null; + } else { + return; + } + } + this$1$1.updateFromDOM(); + }, 80); + }; + ContentEditableInput.prototype.updateFromDOM = function() { + var this$1$1 = this; + if (this.cm.isReadOnly() || !this.pollContent()) { + runInOp(this.cm, function() { + return regChange(this$1$1.cm); + }); + } + }; + ContentEditableInput.prototype.setUneditable = function(node) { + node.contentEditable = "false"; + }; + ContentEditableInput.prototype.onKeyPress = function(e) { + if (e.charCode == 0 || this.composing) { + return; + } + e.preventDefault(); + if (!this.cm.isReadOnly()) { + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + } + }; + ContentEditableInput.prototype.readOnlyChanged = function(val) { + this.div.contentEditable = String(val != "nocursor"); + }; + ContentEditableInput.prototype.onContextMenu = function() { + }; + ContentEditableInput.prototype.resetPosition = function() { + }; + ContentEditableInput.prototype.needsContentAttribute = true; + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) { + return null; + } + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + var order = getOrder(line, cm.doc.direction), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; + } + function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) { + if (/CodeMirror-gutter-wrapper/.test(scan.className)) { + return true; + } + } + return false; + } + function badPos(pos, bad) { + if (bad) { + pos.bad = true; + } + return pos; + } + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; + function recognizeMarker(id) { + return function(marker) { + return marker.id == id; + }; + } + function close() { + if (closing) { + text += lineSep; + if (extraLinebreak) { + text += lineSep; + } + closing = extraLinebreak = false; + } + } + function addText(str) { + if (str) { + close(); + text += str; + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText) { + addText(cmText); + return; + } + var markerID = node.getAttribute("cm-marker"), range2; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range2 = found[0].find(0))) { + addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep)); + } + return; + } + if (node.getAttribute("contenteditable") == "false") { + return; + } + var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); + if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { + return; + } + if (isBlock) { + close(); + } + for (var i2 = 0; i2 < node.childNodes.length; i2++) { + walk(node.childNodes[i2]); + } + if (/^(pre|p)$/i.test(node.nodeName)) { + extraLinebreak = true; + } + if (isBlock) { + closing = true; + } + } else if (node.nodeType == 3) { + addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); + } + } + for (; ; ) { + walk(from); + if (from == to) { + break; + } + from = from.nextSibling; + extraLinebreak = false; + } + return text; + } + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) { + return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + } + node = null; + offset = 0; + } else { + for (lineNode = node; ; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { + return null; + } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { + break; + } + } + } + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + var lineView = cm.display.view[i2]; + if (lineView.node == lineNode) { + return locateNodeInLineView(lineView, node, offset); + } + } + } + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) { + return badPos(Pos(lineNo(lineView.line), 0), true); + } + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) { + offset = textNode.nodeValue.length; + } + } + while (topNode.parentNode != wrapper) { + topNode = topNode.parentNode; + } + var measure = lineView.measure, maps = measure.maps; + function find(textNode2, topNode2, offset2) { + for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { + var map2 = i2 < 0 ? measure.map : maps[i2]; + for (var j = 0; j < map2.length; j += 3) { + var curNode = map2[j + 2]; + if (curNode == textNode2 || curNode == topNode2) { + var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]); + var ch = map2[j] + offset2; + if (offset2 < 0 || curNode != textNode2) { + ch = map2[j + (offset2 ? 1 : 0)]; + } + return Pos(line2, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) { + return badPos(found, bad); + } + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) { + return badPos(Pos(found.line, found.ch - dist), bad); + } else { + dist += after.textContent.length; + } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) { + return badPos(Pos(found.line, found.ch + dist$1), bad); + } else { + dist$1 += before.textContent.length; + } + } + } + var TextareaInput = function(cm) { + this.cm = cm; + this.prevInput = ""; + this.pollingFast = false; + this.polling = new Delayed(); + this.hasSelection = false; + this.composing = null; + this.resetting = false; + }; + TextareaInput.prototype.init = function(display) { + var this$1$1 = this; + var input = this, cm = this.cm; + this.createField(display); + var te = this.textarea; + display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); + if (ios) { + te.style.width = "0px"; + } + on(te, "input", function() { + if (ie && ie_version >= 9 && this$1$1.hasSelection) { + this$1$1.hasSelection = null; + } + input.poll(); + }); + on(te, "paste", function(e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; + } + cm.state.pasteIncoming = +/* @__PURE__ */ new Date(); + input.fastPoll(); + }); + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ lineWise: false, text: cm.getSelections() }); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ lineWise: true, text: ranges.text }); + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") { + cm.state.cutIncoming = +/* @__PURE__ */ new Date(); + } + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + on(display.scroller, "paste", function(e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { + return; + } + if (!te.dispatchEvent) { + cm.state.pasteIncoming = +/* @__PURE__ */ new Date(); + input.focus(); + return; + } + var event = new Event("paste"); + event.clipboardData = e.clipboardData; + te.dispatchEvent(event); + }); + on(display.lineSpace, "selectstart", function(e) { + if (!eventInWidget(display, e)) { + e_preventDefault(e); + } + }); + on(te, "compositionstart", function() { + var start = cm.getCursor("from"); + if (input.composing) { + input.composing.range.clear(); + } + input.composing = { + start, + range: cm.markText(start, cm.getCursor("to"), { className: "CodeMirror-composing" }) + }; + }); + on(te, "compositionend", function() { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }; + TextareaInput.prototype.createField = function(_display) { + this.wrapper = hiddenTextarea(); + this.textarea = this.wrapper.firstChild; + var opts = this.cm.options; + disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize); + }; + TextareaInput.prototype.screenReaderLabelChanged = function(label) { + if (label) { + this.textarea.setAttribute("aria-label", label); + } else { + this.textarea.removeAttribute("aria-label"); + } + }; + TextareaInput.prototype.prepareSelection = function() { + var cm = this.cm, display = cm.display, doc2 = cm.doc; + var result = prepareSelection(cm); + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc2.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min( + display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top + )); + result.teLeft = Math.max(0, Math.min( + display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left + )); + } + return result; + }; + TextareaInput.prototype.showSelection = function(drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }; + TextareaInput.prototype.reset = function(typing) { + if (this.contextMenuPending || this.composing && typing) { + return; + } + var cm = this.cm; + this.resetting = true; + if (cm.somethingSelected()) { + this.prevInput = ""; + var content = cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) { + selectInput(this.textarea); + } + if (ie && ie_version >= 9) { + this.hasSelection = content; + } + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) { + this.hasSelection = null; + } + } + this.resetting = false; + }; + TextareaInput.prototype.getField = function() { + return this.textarea; + }; + TextareaInput.prototype.supportsTouch = function() { + return false; + }; + TextareaInput.prototype.focus = function() { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(rootNode(this.textarea)) != this.textarea)) { + try { + this.textarea.focus(); + } catch (e) { + } + } + }; + TextareaInput.prototype.blur = function() { + this.textarea.blur(); + }; + TextareaInput.prototype.resetPosition = function() { + this.wrapper.style.top = this.wrapper.style.left = 0; + }; + TextareaInput.prototype.receivedFocus = function() { + this.slowPoll(); + }; + TextareaInput.prototype.slowPoll = function() { + var this$1$1 = this; + if (this.pollingFast) { + return; + } + this.polling.set(this.cm.options.pollInterval, function() { + this$1$1.poll(); + if (this$1$1.cm.state.focused) { + this$1$1.slowPoll(); + } + }); + }; + TextareaInput.prototype.fastPoll = function() { + var missed = false, input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) { + missed = true; + input.polling.set(60, p); + } else { + input.pollingFast = false; + input.slowPoll(); + } + } + input.polling.set(20, p); + }; + TextareaInput.prototype.poll = function() { + var this$1$1 = this; + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + if (this.contextMenuPending || this.resetting || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { + return false; + } + var text = input.value; + if (text == prevInput && !cm.somethingSelected()) { + return false; + } + if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 8203 && !prevInput) { + prevInput = "​"; + } + if (first == 8666) { + this.reset(); + return this.cm.execCommand("undo"); + } + } + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { + ++same; + } + runInOp(cm, function() { + applyTextInput( + cm, + text.slice(same), + prevInput.length - same, + null, + this$1$1.composing ? "*compose" : null + ); + if (text.length > 1e3 || text.indexOf("\n") > -1) { + input.value = this$1$1.prevInput = ""; + } else { + this$1$1.prevInput = text; + } + if (this$1$1.composing) { + this$1$1.composing.range.clear(); + this$1$1.composing.range = cm.markText( + this$1$1.composing.start, + cm.getCursor("to"), + { className: "CodeMirror-composing" } + ); + } + }); + return true; + }; + TextareaInput.prototype.ensurePolled = function() { + if (this.pollingFast && this.poll()) { + this.pollingFast = false; + } + }; + TextareaInput.prototype.onKeyPress = function() { + if (ie && ie_version >= 9) { + this.hasSelection = null; + } + this.fastPoll(); + }; + TextareaInput.prototype.onContextMenu = function(e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + if (input.contextMenuPending) { + input.contextMenuPending(); + } + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) { + return; + } + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) { + operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + } + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; + var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); + input.wrapper.style.cssText = "position: static"; + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + var oldScrollY; + if (webkit) { + oldScrollY = te.ownerDocument.defaultView.scrollY; + } + display.input.focus(); + if (webkit) { + te.ownerDocument.defaultView.scrollTo(null, oldScrollY); + } + display.input.reset(); + if (!cm.somethingSelected()) { + te.value = input.prevInput = " "; + } + input.contextMenuPending = rehide; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "​" + (selected ? te.value : ""); + te.value = "⇚"; + te.value = extval; + input.prevInput = selected ? "" : "​"; + te.selectionStart = 1; + te.selectionEnd = extval.length; + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + if (input.contextMenuPending != rehide) { + return; + } + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) { + display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + } + if (te.selectionStart != null) { + if (!ie || ie && ie_version < 9) { + prepareSelectAllHack(); + } + var i2 = 0, poll = function() { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "​") { + operation(cm, selectAll)(cm); + } else if (i2++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500); + } else { + display.selForContextMenu = null; + display.input.reset(); + } + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + if (ie && ie_version >= 9) { + prepareSelectAllHack(); + } + if (captureRightClick) { + e_stop(e); + var mouseup = function() { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }; + TextareaInput.prototype.readOnlyChanged = function(val) { + if (!val) { + this.reset(); + } + this.textarea.disabled = val == "nocursor"; + this.textarea.readOnly = !!val; + }; + TextareaInput.prototype.setUneditable = function() { + }; + TextareaInput.prototype.needsContentAttribute = false; + function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) { + options.tabindex = textarea.tabIndex; + } + if (!options.placeholder && textarea.placeholder) { + options.placeholder = textarea.placeholder; + } + if (options.autofocus == null) { + var hasFocus = activeElt(rootNode(textarea)); + options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + function save() { + textarea.value = cm.getValue(); + } + var realSubmit; + if (textarea.form) { + on(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form; + realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function() { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch (e) { + } + } + } + options.finishInit = function(cm2) { + cm2.save = save; + cm2.getTextArea = function() { + return textarea; + }; + cm2.toTextArea = function() { + cm2.toTextArea = isNaN; + save(); + textarea.parentNode.removeChild(cm2.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { + textarea.form.submit = realSubmit; + } + } + }; + }; + textarea.style.display = "none"; + var cm = CodeMirror( + function(node) { + return textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, + options + ); + return cm; + } + function addLegacyProps(CodeMirror2) { + CodeMirror2.off = off; + CodeMirror2.on = on; + CodeMirror2.wheelEventPixels = wheelEventPixels; + CodeMirror2.Doc = Doc; + CodeMirror2.splitLines = splitLinesAuto; + CodeMirror2.countColumn = countColumn; + CodeMirror2.findColumn = findColumn; + CodeMirror2.isWordChar = isWordCharBasic; + CodeMirror2.Pass = Pass; + CodeMirror2.signal = signal; + CodeMirror2.Line = Line; + CodeMirror2.changeEnd = changeEnd; + CodeMirror2.scrollbarModel = scrollbarModel; + CodeMirror2.Pos = Pos; + CodeMirror2.cmpPos = cmp; + CodeMirror2.modes = modes; + CodeMirror2.mimeModes = mimeModes; + CodeMirror2.resolveMode = resolveMode; + CodeMirror2.getMode = getMode; + CodeMirror2.modeExtensions = modeExtensions; + CodeMirror2.extendMode = extendMode; + CodeMirror2.copyState = copyState; + CodeMirror2.startState = startState; + CodeMirror2.innerMode = innerMode; + CodeMirror2.commands = commands; + CodeMirror2.keyMap = keyMap; + CodeMirror2.keyName = keyName; + CodeMirror2.isModifierKey = isModifierKey; + CodeMirror2.lookupKey = lookupKey; + CodeMirror2.normalizeKeyMap = normalizeKeyMap; + CodeMirror2.StringStream = StringStream; + CodeMirror2.SharedTextMarker = SharedTextMarker; + CodeMirror2.TextMarker = TextMarker; + CodeMirror2.LineWidget = LineWidget; + CodeMirror2.e_preventDefault = e_preventDefault; + CodeMirror2.e_stopPropagation = e_stopPropagation; + CodeMirror2.e_stop = e_stop; + CodeMirror2.addClass = addClass; + CodeMirror2.contains = contains; + CodeMirror2.rmClass = rmClass; + CodeMirror2.keyNames = keyNames; + } + defineOptions(CodeMirror); + addEditorMethods(CodeMirror); + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { + CodeMirror.prototype[prop] = /* @__PURE__ */ function(method) { + return function() { + return method.apply(this.doc, arguments); + }; + }(Doc.prototype[prop]); + } + } + eventMixin(Doc); + CodeMirror.inputStyles = { "textarea": TextareaInput, "contenteditable": ContentEditableInput }; + CodeMirror.defineMode = function(name) { + if (!CodeMirror.defaults.mode && name != "null") { + CodeMirror.defaults.mode = name; + } + defineMode.apply(this, arguments); + }; + CodeMirror.defineMIME = defineMIME; + CodeMirror.defineMode("null", function() { + return { token: function(stream) { + return stream.skipToEnd(); + } }; + }); + CodeMirror.defineMIME("text/plain", "null"); + CodeMirror.defineExtension = function(name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function(name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.fromTextArea = fromTextArea; + addLegacyProps(CodeMirror); + CodeMirror.version = "5.65.18"; + return CodeMirror; + }); + })(codemirror$2); + return codemirror$2.exports; +} +var codemirrorExports = requireCodemirror(); +const codemirror = /* @__PURE__ */ getDefaultExportFromCjs(codemirrorExports); +var css = { exports: {} }; +var hasRequiredCss; +function requireCss() { + if (hasRequiredCss) return css.exports; + hasRequiredCss = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline; + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + var indentUnit = config.indentUnit, tokenHooks = parserConfig.tokenHooks, documentTypes2 = parserConfig.documentTypes || {}, mediaTypes2 = parserConfig.mediaTypes || {}, mediaFeatures2 = parserConfig.mediaFeatures || {}, mediaValueKeywords2 = parserConfig.mediaValueKeywords || {}, propertyKeywords2 = parserConfig.propertyKeywords || {}, nonStandardPropertyKeywords2 = parserConfig.nonStandardPropertyKeywords || {}, fontProperties2 = parserConfig.fontProperties || {}, counterDescriptors2 = parserConfig.counterDescriptors || {}, colorKeywords2 = parserConfig.colorKeywords || {}, valueKeywords2 = parserConfig.valueKeywords || {}, allowNested = parserConfig.allowNested, lineComment = parserConfig.lineComment, supportsAtComponent = parserConfig.supportsAtComponent === true, highlightNonStandardPropertyKeywords = config.highlightNonStandardPropertyKeywords !== false; + var type, override; + function ret(style, tp) { + type = tp; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]*/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if (stream.match(/^[\w-.]+(?=\()/)) { + if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) { + state.tokenize = tokenParenthesized; + } + return ret("variable callee", "variable"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + function tokenParenthesized(stream, state) { + stream.next(); + if (!stream.match(/^\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + function Context(type2, indent, prev) { + this.type = type2; + this.indent = indent; + this.prev = prev; + } + function pushContext(state, stream, type2, indent) { + state.context = new Context(type2, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type2; + } + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + function pass(type2, stream, state) { + return states[state.context.type](type2, stream, state); + } + function popAndPass(type2, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type2, stream, state); + } + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords2.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords2.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + var states = {}; + states.top = function(type2, stream, state) { + if (type2 == "{") { + return pushContext(state, stream, "block"); + } else if (type2 == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/i.test(type2)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/i.test(type2)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type2)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/i.test(type2)) { + state.stateArg = type2; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type2)) { + return "keyframes"; + } else if (type2 && type2.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type2 == "hash") { + override = "builtin"; + } else if (type2 == "word") { + override = "tag"; + } else if (type2 == "variable-definition") { + return "maybeprop"; + } else if (type2 == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type2 == ":") { + return "pseudo"; + } else if (allowNested && type2 == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + states.block = function(type2, stream, state) { + if (type2 == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords2.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords2.hasOwnProperty(word)) { + override = highlightNonStandardPropertyKeywords ? "string-2" : "property"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type2 == "meta") { + return "block"; + } else if (!allowNested && (type2 == "hash" || type2 == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type2, stream, state); + } + }; + states.maybeprop = function(type2, stream, state) { + if (type2 == ":") return pushContext(state, stream, "prop"); + return pass(type2, stream, state); + }; + states.prop = function(type2, stream, state) { + if (type2 == ";") return popContext(state); + if (type2 == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type2 == "}" || type2 == "{") return popAndPass(type2, stream, state); + if (type2 == "(") return pushContext(state, stream, "parens"); + if (type2 == "hash" && !/^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(stream.current())) { + override += " error"; + } else if (type2 == "word") { + wordAsValue(stream); + } else if (type2 == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + states.propBlock = function(type2, _stream, state) { + if (type2 == "}") return popContext(state); + if (type2 == "word") { + override = "property"; + return "maybeprop"; + } + return state.context.type; + }; + states.parens = function(type2, stream, state) { + if (type2 == "{" || type2 == "}") return popAndPass(type2, stream, state); + if (type2 == ")") return popContext(state); + if (type2 == "(") return pushContext(state, stream, "parens"); + if (type2 == "interpolation") return pushContext(state, stream, "interpolation"); + if (type2 == "word") wordAsValue(stream); + return "parens"; + }; + states.pseudo = function(type2, stream, state) { + if (type2 == "meta") return "pseudo"; + if (type2 == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type2, stream, state); + }; + states.documentTypes = function(type2, stream, state) { + if (type2 == "word" && documentTypes2.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type2, stream, state); + } + }; + states.atBlock = function(type2, stream, state) { + if (type2 == "(") return pushContext(state, stream, "atBlock_parens"); + if (type2 == "}" || type2 == ";") return popAndPass(type2, stream, state); + if (type2 == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + if (type2 == "interpolation") return pushContext(state, stream, "interpolation"); + if (type2 == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes2.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures2.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords2.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords2.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords2.hasOwnProperty(word)) + override = highlightNonStandardPropertyKeywords ? "string-2" : "property"; + else if (valueKeywords2.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords2.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + states.atComponentBlock = function(type2, stream, state) { + if (type2 == "}") + return popAndPass(type2, stream, state); + if (type2 == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type2 == "word") + override = "error"; + return state.context.type; + }; + states.atBlock_parens = function(type2, stream, state) { + if (type2 == ")") return popContext(state); + if (type2 == "{" || type2 == "}") return popAndPass(type2, stream, state, 2); + return states.atBlock(type2, stream, state); + }; + states.restricted_atBlock_before = function(type2, stream, state) { + if (type2 == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type2 == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type2, stream, state); + }; + states.restricted_atBlock = function(type2, stream, state) { + if (type2 == "}") { + state.stateArg = null; + return popContext(state); + } + if (type2 == "word") { + if (state.stateArg == "@font-face" && !fontProperties2.hasOwnProperty(stream.current().toLowerCase()) || state.stateArg == "@counter-style" && !counterDescriptors2.hasOwnProperty(stream.current().toLowerCase())) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + states.keyframes = function(type2, stream, state) { + if (type2 == "word") { + override = "variable"; + return "keyframes"; + } + if (type2 == "{") return pushContext(state, stream, "top"); + return pass(type2, stream, state); + }; + states.at = function(type2, stream, state) { + if (type2 == ";") return popContext(state); + if (type2 == "{" || type2 == "}") return popAndPass(type2, stream, state); + if (type2 == "word") override = "tag"; + else if (type2 == "hash") override = "builtin"; + return "at"; + }; + states.interpolation = function(type2, stream, state) { + if (type2 == "}") return popContext(state); + if (type2 == "{" || type2 == ";") return popAndPass(type2, stream, state); + if (type2 == "word") override = "variable"; + else if (type2 != "variable" && type2 != "(" && type2 != ")") override = "error"; + return "interpolation"; + }; + return { + startState: function(base) { + return { + tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null) + }; + }, + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + if (type != "comment") + state.state = states[state.state](type, stream, state); + return override; + }, + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + indent = Math.max(0, cx.indent - indentUnit); + } + } + return indent; + }, + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * ", + lineComment, + fold: "brace" + }; + }); + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i].toLowerCase()] = true; + } + return keys; + } + var documentTypes_ = [ + "domain", + "regexp", + "url", + "url-prefix" + ], documentTypes = keySet(documentTypes_); + var mediaTypes_ = [ + "all", + "aural", + "braille", + "handheld", + "print", + "projection", + "screen", + "tty", + "tv", + "embossed" + ], mediaTypes = keySet(mediaTypes_); + var mediaFeatures_ = [ + "width", + "min-width", + "max-width", + "height", + "min-height", + "max-height", + "device-width", + "min-device-width", + "max-device-width", + "device-height", + "min-device-height", + "max-device-height", + "aspect-ratio", + "min-aspect-ratio", + "max-aspect-ratio", + "device-aspect-ratio", + "min-device-aspect-ratio", + "max-device-aspect-ratio", + "color", + "min-color", + "max-color", + "color-index", + "min-color-index", + "max-color-index", + "monochrome", + "min-monochrome", + "max-monochrome", + "resolution", + "min-resolution", + "max-resolution", + "scan", + "grid", + "orientation", + "device-pixel-ratio", + "min-device-pixel-ratio", + "max-device-pixel-ratio", + "pointer", + "any-pointer", + "hover", + "any-hover", + "prefers-color-scheme", + "dynamic-range", + "video-dynamic-range" + ], mediaFeatures = keySet(mediaFeatures_); + var mediaValueKeywords_ = [ + "landscape", + "portrait", + "none", + "coarse", + "fine", + "on-demand", + "hover", + "interlace", + "progressive", + "dark", + "light", + "standard", + "high" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + var propertyKeywords_ = [ + "align-content", + "align-items", + "align-self", + "alignment-adjust", + "alignment-baseline", + "all", + "anchor-point", + "animation", + "animation-delay", + "animation-direction", + "animation-duration", + "animation-fill-mode", + "animation-iteration-count", + "animation-name", + "animation-play-state", + "animation-timing-function", + "appearance", + "azimuth", + "backdrop-filter", + "backface-visibility", + "background", + "background-attachment", + "background-blend-mode", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-position-x", + "background-position-y", + "background-repeat", + "background-size", + "baseline-shift", + "binding", + "bleed", + "block-size", + "bookmark-label", + "bookmark-level", + "bookmark-state", + "bookmark-target", + "border", + "border-bottom", + "border-bottom-color", + "border-bottom-left-radius", + "border-bottom-right-radius", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-image", + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-style", + "border-top", + "border-top-color", + "border-top-left-radius", + "border-top-right-radius", + "border-top-style", + "border-top-width", + "border-width", + "bottom", + "box-decoration-break", + "box-shadow", + "box-sizing", + "break-after", + "break-before", + "break-inside", + "caption-side", + "caret-color", + "clear", + "clip", + "color", + "color-profile", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-color", + "column-rule-style", + "column-rule-width", + "column-span", + "column-width", + "columns", + "contain", + "content", + "counter-increment", + "counter-reset", + "crop", + "cue", + "cue-after", + "cue-before", + "cursor", + "direction", + "display", + "dominant-baseline", + "drop-initial-after-adjust", + "drop-initial-after-align", + "drop-initial-before-adjust", + "drop-initial-before-align", + "drop-initial-size", + "drop-initial-value", + "elevation", + "empty-cells", + "fit", + "fit-content", + "fit-position", + "flex", + "flex-basis", + "flex-direction", + "flex-flow", + "flex-grow", + "flex-shrink", + "flex-wrap", + "float", + "float-offset", + "flow-from", + "flow-into", + "font", + "font-family", + "font-feature-settings", + "font-kerning", + "font-language-override", + "font-optical-sizing", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-synthesis", + "font-variant", + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + "font-variation-settings", + "font-weight", + "gap", + "grid", + "grid-area", + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-column", + "grid-column-end", + "grid-column-gap", + "grid-column-start", + "grid-gap", + "grid-row", + "grid-row-end", + "grid-row-gap", + "grid-row-start", + "grid-template", + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + "hanging-punctuation", + "height", + "hyphens", + "icon", + "image-orientation", + "image-rendering", + "image-resolution", + "inline-box-align", + "inset", + "inset-block", + "inset-block-end", + "inset-block-start", + "inset-inline", + "inset-inline-end", + "inset-inline-start", + "isolation", + "justify-content", + "justify-items", + "justify-self", + "left", + "letter-spacing", + "line-break", + "line-height", + "line-height-step", + "line-stacking", + "line-stacking-ruby", + "line-stacking-shift", + "line-stacking-strategy", + "list-style", + "list-style-image", + "list-style-position", + "list-style-type", + "margin", + "margin-bottom", + "margin-left", + "margin-right", + "margin-top", + "marks", + "marquee-direction", + "marquee-loop", + "marquee-play-count", + "marquee-speed", + "marquee-style", + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-repeat", + "mask-size", + "mask-type", + "max-block-size", + "max-height", + "max-inline-size", + "max-width", + "min-block-size", + "min-height", + "min-inline-size", + "min-width", + "mix-blend-mode", + "move-to", + "nav-down", + "nav-index", + "nav-left", + "nav-right", + "nav-up", + "object-fit", + "object-position", + "offset", + "offset-anchor", + "offset-distance", + "offset-path", + "offset-position", + "offset-rotate", + "opacity", + "order", + "orphans", + "outline", + "outline-color", + "outline-offset", + "outline-style", + "outline-width", + "overflow", + "overflow-style", + "overflow-wrap", + "overflow-x", + "overflow-y", + "padding", + "padding-bottom", + "padding-left", + "padding-right", + "padding-top", + "page", + "page-break-after", + "page-break-before", + "page-break-inside", + "page-policy", + "pause", + "pause-after", + "pause-before", + "perspective", + "perspective-origin", + "pitch", + "pitch-range", + "place-content", + "place-items", + "place-self", + "play-during", + "position", + "presentation-level", + "punctuation-trim", + "quotes", + "region-break-after", + "region-break-before", + "region-break-inside", + "region-fragment", + "rendering-intent", + "resize", + "rest", + "rest-after", + "rest-before", + "richness", + "right", + "rotate", + "rotation", + "rotation-point", + "row-gap", + "ruby-align", + "ruby-overhang", + "ruby-position", + "ruby-span", + "scale", + "scroll-behavior", + "scroll-margin", + "scroll-margin-block", + "scroll-margin-block-end", + "scroll-margin-block-start", + "scroll-margin-bottom", + "scroll-margin-inline", + "scroll-margin-inline-end", + "scroll-margin-inline-start", + "scroll-margin-left", + "scroll-margin-right", + "scroll-margin-top", + "scroll-padding", + "scroll-padding-block", + "scroll-padding-block-end", + "scroll-padding-block-start", + "scroll-padding-bottom", + "scroll-padding-inline", + "scroll-padding-inline-end", + "scroll-padding-inline-start", + "scroll-padding-left", + "scroll-padding-right", + "scroll-padding-top", + "scroll-snap-align", + "scroll-snap-type", + "shape-image-threshold", + "shape-inside", + "shape-margin", + "shape-outside", + "size", + "speak", + "speak-as", + "speak-header", + "speak-numeral", + "speak-punctuation", + "speech-rate", + "stress", + "string-set", + "tab-size", + "table-layout", + "target", + "target-name", + "target-new", + "target-position", + "text-align", + "text-align-last", + "text-combine-upright", + "text-decoration", + "text-decoration-color", + "text-decoration-line", + "text-decoration-skip", + "text-decoration-skip-ink", + "text-decoration-style", + "text-emphasis", + "text-emphasis-color", + "text-emphasis-position", + "text-emphasis-style", + "text-height", + "text-indent", + "text-justify", + "text-orientation", + "text-outline", + "text-overflow", + "text-rendering", + "text-shadow", + "text-size-adjust", + "text-space-collapse", + "text-transform", + "text-underline-position", + "text-wrap", + "top", + "touch-action", + "transform", + "transform-origin", + "transform-style", + "transition", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + "translate", + "unicode-bidi", + "user-select", + "vertical-align", + "visibility", + "voice-balance", + "voice-duration", + "voice-family", + "voice-pitch", + "voice-range", + "voice-rate", + "voice-stress", + "voice-volume", + "volume", + "white-space", + "widows", + "width", + "will-change", + "word-break", + "word-spacing", + "word-wrap", + "writing-mode", + "z-index", + // SVG-specific + "clip-path", + "clip-rule", + "mask", + "enable-background", + "filter", + "flood-color", + "flood-opacity", + "lighting-color", + "stop-color", + "stop-opacity", + "pointer-events", + "color-interpolation", + "color-interpolation-filters", + "color-rendering", + "fill", + "fill-opacity", + "fill-rule", + "image-rendering", + "marker", + "marker-end", + "marker-mid", + "marker-start", + "paint-order", + "shape-rendering", + "stroke", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "text-rendering", + "baseline-shift", + "dominant-baseline", + "glyph-orientation-horizontal", + "glyph-orientation-vertical", + "text-anchor", + "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + var nonStandardPropertyKeywords_ = [ + "accent-color", + "aspect-ratio", + "border-block", + "border-block-color", + "border-block-end", + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + "border-block-start", + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + "border-block-style", + "border-block-width", + "border-inline", + "border-inline-color", + "border-inline-end", + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + "border-inline-start", + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + "border-inline-style", + "border-inline-width", + "content-visibility", + "margin-block", + "margin-block-end", + "margin-block-start", + "margin-inline", + "margin-inline-end", + "margin-inline-start", + "overflow-anchor", + "overscroll-behavior", + "padding-block", + "padding-block-end", + "padding-block-start", + "padding-inline", + "padding-inline-end", + "padding-inline-start", + "scroll-snap-stop", + "scrollbar-3d-light-color", + "scrollbar-arrow-color", + "scrollbar-base-color", + "scrollbar-dark-shadow-color", + "scrollbar-face-color", + "scrollbar-highlight-color", + "scrollbar-shadow-color", + "scrollbar-track-color", + "searchfield-cancel-button", + "searchfield-decoration", + "searchfield-results-button", + "searchfield-results-decoration", + "shape-inside", + "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + var fontProperties_ = [ + "font-display", + "font-family", + "src", + "unicode-range", + "font-variant", + "font-feature-settings", + "font-stretch", + "font-weight", + "font-style" + ], fontProperties = keySet(fontProperties_); + var counterDescriptors_ = [ + "additive-symbols", + "fallback", + "negative", + "pad", + "prefix", + "range", + "speak-as", + "suffix", + "symbols", + "system" + ], counterDescriptors = keySet(counterDescriptors_); + var colorKeywords_ = [ + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgreen", + "darkgrey", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "grey", + "green", + "greenyellow", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgreen", + "lightgrey", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "rebeccapurple", + "red", + "rosybrown", + "royalblue", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + var valueKeywords_ = [ + "above", + "absolute", + "activeborder", + "additive", + "activecaption", + "afar", + "after-white-space", + "ahead", + "alias", + "all", + "all-scroll", + "alphabetic", + "alternate", + "always", + "amharic", + "amharic-abegede", + "antialiased", + "appworkspace", + "arabic-indic", + "armenian", + "asterisks", + "attr", + "auto", + "auto-flow", + "avoid", + "avoid-column", + "avoid-page", + "avoid-region", + "axis-pan", + "background", + "backwards", + "baseline", + "below", + "bidi-override", + "binary", + "bengali", + "blink", + "block", + "block-axis", + "blur", + "bold", + "bolder", + "border", + "border-box", + "both", + "bottom", + "break", + "break-all", + "break-word", + "brightness", + "bullets", + "button", + "buttonface", + "buttonhighlight", + "buttonshadow", + "buttontext", + "calc", + "cambodian", + "capitalize", + "caps-lock-indicator", + "caption", + "captiontext", + "caret", + "cell", + "center", + "checkbox", + "circle", + "cjk-decimal", + "cjk-earthly-branch", + "cjk-heavenly-stem", + "cjk-ideographic", + "clear", + "clip", + "close-quote", + "col-resize", + "collapse", + "color", + "color-burn", + "color-dodge", + "column", + "column-reverse", + "compact", + "condensed", + "conic-gradient", + "contain", + "content", + "contents", + "content-box", + "context-menu", + "continuous", + "contrast", + "copy", + "counter", + "counters", + "cover", + "crop", + "cross", + "crosshair", + "cubic-bezier", + "currentcolor", + "cursive", + "cyclic", + "darken", + "dashed", + "decimal", + "decimal-leading-zero", + "default", + "default-button", + "dense", + "destination-atop", + "destination-in", + "destination-out", + "destination-over", + "devanagari", + "difference", + "disc", + "discard", + "disclosure-closed", + "disclosure-open", + "document", + "dot-dash", + "dot-dot-dash", + "dotted", + "double", + "down", + "drop-shadow", + "e-resize", + "ease", + "ease-in", + "ease-in-out", + "ease-out", + "element", + "ellipse", + "ellipsis", + "embed", + "end", + "ethiopic", + "ethiopic-abegede", + "ethiopic-abegede-am-et", + "ethiopic-abegede-gez", + "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", + "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", + "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", + "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", + "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", + "ethiopic-halehame-ti-et", + "ethiopic-halehame-tig", + "ethiopic-numeric", + "ew-resize", + "exclusion", + "expanded", + "extends", + "extra-condensed", + "extra-expanded", + "fantasy", + "fast", + "fill", + "fill-box", + "fixed", + "flat", + "flex", + "flex-end", + "flex-start", + "footnotes", + "forwards", + "from", + "geometricPrecision", + "georgian", + "grayscale", + "graytext", + "grid", + "groove", + "gujarati", + "gurmukhi", + "hand", + "hangul", + "hangul-consonant", + "hard-light", + "hebrew", + "help", + "hidden", + "hide", + "higher", + "highlight", + "highlighttext", + "hiragana", + "hiragana-iroha", + "horizontal", + "hsl", + "hsla", + "hue", + "hue-rotate", + "icon", + "ignore", + "inactiveborder", + "inactivecaption", + "inactivecaptiontext", + "infinite", + "infobackground", + "infotext", + "inherit", + "initial", + "inline", + "inline-axis", + "inline-block", + "inline-flex", + "inline-grid", + "inline-table", + "inset", + "inside", + "intrinsic", + "invert", + "italic", + "japanese-formal", + "japanese-informal", + "justify", + "kannada", + "katakana", + "katakana-iroha", + "keep-all", + "khmer", + "korean-hangul-formal", + "korean-hanja-formal", + "korean-hanja-informal", + "landscape", + "lao", + "large", + "larger", + "left", + "level", + "lighter", + "lighten", + "line-through", + "linear", + "linear-gradient", + "lines", + "list-item", + "listbox", + "listitem", + "local", + "logical", + "loud", + "lower", + "lower-alpha", + "lower-armenian", + "lower-greek", + "lower-hexadecimal", + "lower-latin", + "lower-norwegian", + "lower-roman", + "lowercase", + "ltr", + "luminosity", + "malayalam", + "manipulation", + "match", + "matrix", + "matrix3d", + "media-play-button", + "media-slider", + "media-sliderthumb", + "media-volume-slider", + "media-volume-sliderthumb", + "medium", + "menu", + "menulist", + "menulist-button", + "menutext", + "message-box", + "middle", + "min-intrinsic", + "mix", + "mongolian", + "monospace", + "move", + "multiple", + "multiple_mask_images", + "multiply", + "myanmar", + "n-resize", + "narrower", + "ne-resize", + "nesw-resize", + "no-close-quote", + "no-drop", + "no-open-quote", + "no-repeat", + "none", + "normal", + "not-allowed", + "nowrap", + "ns-resize", + "numbers", + "numeric", + "nw-resize", + "nwse-resize", + "oblique", + "octal", + "opacity", + "open-quote", + "optimizeLegibility", + "optimizeSpeed", + "oriya", + "oromo", + "outset", + "outside", + "outside-shape", + "overlay", + "overline", + "padding", + "padding-box", + "painted", + "page", + "paused", + "persian", + "perspective", + "pinch-zoom", + "plus-darker", + "plus-lighter", + "pointer", + "polygon", + "portrait", + "pre", + "pre-line", + "pre-wrap", + "preserve-3d", + "progress", + "push-button", + "radial-gradient", + "radio", + "read-only", + "read-write", + "read-write-plaintext-only", + "rectangle", + "region", + "relative", + "repeat", + "repeating-linear-gradient", + "repeating-radial-gradient", + "repeating-conic-gradient", + "repeat-x", + "repeat-y", + "reset", + "reverse", + "rgb", + "rgba", + "ridge", + "right", + "rotate", + "rotate3d", + "rotateX", + "rotateY", + "rotateZ", + "round", + "row", + "row-resize", + "row-reverse", + "rtl", + "run-in", + "running", + "s-resize", + "sans-serif", + "saturate", + "saturation", + "scale", + "scale3d", + "scaleX", + "scaleY", + "scaleZ", + "screen", + "scroll", + "scrollbar", + "scroll-position", + "se-resize", + "searchfield", + "searchfield-cancel-button", + "searchfield-decoration", + "searchfield-results-button", + "searchfield-results-decoration", + "self-start", + "self-end", + "semi-condensed", + "semi-expanded", + "separate", + "sepia", + "serif", + "show", + "sidama", + "simp-chinese-formal", + "simp-chinese-informal", + "single", + "skew", + "skewX", + "skewY", + "skip-white-space", + "slide", + "slider-horizontal", + "slider-vertical", + "sliderthumb-horizontal", + "sliderthumb-vertical", + "slow", + "small", + "small-caps", + "small-caption", + "smaller", + "soft-light", + "solid", + "somali", + "source-atop", + "source-in", + "source-out", + "source-over", + "space", + "space-around", + "space-between", + "space-evenly", + "spell-out", + "square", + "square-button", + "start", + "static", + "status-bar", + "stretch", + "stroke", + "stroke-box", + "sub", + "subpixel-antialiased", + "svg_masks", + "super", + "sw-resize", + "symbolic", + "symbols", + "system-ui", + "table", + "table-caption", + "table-cell", + "table-column", + "table-column-group", + "table-footer-group", + "table-header-group", + "table-row", + "table-row-group", + "tamil", + "telugu", + "text", + "text-bottom", + "text-top", + "textarea", + "textfield", + "thai", + "thick", + "thin", + "threeddarkshadow", + "threedface", + "threedhighlight", + "threedlightshadow", + "threedshadow", + "tibetan", + "tigre", + "tigrinya-er", + "tigrinya-er-abegede", + "tigrinya-et", + "tigrinya-et-abegede", + "to", + "top", + "trad-chinese-formal", + "trad-chinese-informal", + "transform", + "translate", + "translate3d", + "translateX", + "translateY", + "translateZ", + "transparent", + "ultra-condensed", + "ultra-expanded", + "underline", + "unidirectional-pan", + "unset", + "up", + "upper-alpha", + "upper-armenian", + "upper-greek", + "upper-hexadecimal", + "upper-latin", + "upper-norwegian", + "upper-roman", + "uppercase", + "urdu", + "url", + "var", + "vertical", + "vertical-text", + "view-box", + "visible", + "visibleFill", + "visiblePainted", + "visibleStroke", + "visual", + "w-resize", + "wait", + "wave", + "wider", + "window", + "windowframe", + "windowtext", + "words", + "wrap", + "wrap-reverse", + "x-large", + "x-small", + "xor", + "xx-large", + "xx-small" + ], valueKeywords = keySet(valueKeywords_); + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_).concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_).concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = ch == "*"; + } + return ["comment", "comment"]; + } + CodeMirror.defineMIME("text/css", { + documentTypes, + mediaTypes, + mediaFeatures, + mediaValueKeywords, + propertyKeywords, + nonStandardPropertyKeywords, + fontProperties, + counterDescriptors, + colorKeywords, + valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + CodeMirror.defineMIME("text/x-scss", { + mediaTypes, + mediaFeatures, + mediaValueKeywords, + propertyKeywords, + nonStandardPropertyKeywords, + colorKeywords, + valueKeywords, + fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/^\s*\{/, false)) + return [null, null]; + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + CodeMirror.defineMIME("text/x-less", { + mediaTypes, + mediaFeatures, + mediaValueKeywords, + propertyKeywords, + nonStandardPropertyKeywords, + colorKeywords, + valueKeywords, + fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + CodeMirror.defineMIME("text/x-gss", { + documentTypes, + mediaTypes, + mediaFeatures, + propertyKeywords, + nonStandardPropertyKeywords, + fontProperties, + counterDescriptors, + colorKeywords, + valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + }); + })(); + return css.exports; +} +requireCss(); +var htmlmixed = { exports: {} }; +var xml = { exports: {} }; +var hasRequiredXml; +function requireXml() { + if (hasRequiredXml) return xml.exports; + hasRequiredXml = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + var htmlConfig = { + autoSelfClosers: { + "area": true, + "base": true, + "br": true, + "col": true, + "command": true, + "embed": true, + "frame": true, + "hr": true, + "img": true, + "input": true, + "keygen": true, + "link": true, + "meta": true, + "param": true, + "source": true, + "track": true, + "wbr": true, + "menuitem": true + }, + implicitlyClosed: { + "dd": true, + "li": true, + "optgroup": true, + "option": true, + "p": true, + "rp": true, + "rt": true, + "tbody": true, + "td": true, + "tfoot": true, + "th": true, + "tr": true + }, + contextGrabbers: { + "dd": { "dd": true, "dt": true }, + "dt": { "dd": true, "dt": true }, + "li": { "li": true }, + "option": { "option": true, "optgroup": true }, + "optgroup": { "optgroup": true }, + "p": { + "address": true, + "article": true, + "aside": true, + "blockquote": true, + "dir": true, + "div": true, + "dl": true, + "fieldset": true, + "footer": true, + "form": true, + "h1": true, + "h2": true, + "h3": true, + "h4": true, + "h5": true, + "h6": true, + "header": true, + "hgroup": true, + "hr": true, + "menu": true, + "nav": true, + "ol": true, + "p": true, + "pre": true, + "section": true, + "table": true, + "ul": true + }, + "rp": { "rp": true, "rt": true }, + "rt": { "rp": true, "rt": true }, + "tbody": { "tbody": true, "tfoot": true }, + "td": { "td": true, "th": true }, + "tfoot": { "tbody": true }, + "th": { "td": true, "th": true }, + "thead": { "tbody": true, "tfoot": true }, + "tr": { "tr": true } + }, + doNotIndent: { "pre": true }, + allowUnquoted: true, + allowMissing: true, + caseFold: true + }; + var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + allowMissingTagName: false, + caseFold: false + }; + CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit; + var config = {}; + var defaults = config_.htmlMode ? htmlConfig : xmlConfig; + for (var prop in defaults) config[prop] = defaults[prop]; + for (var prop in config_) config[prop] = config_[prop]; + var type, setStyle; + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) { + return chain(inBlock("comment", "-->")); + } else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else { + return null; + } + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + type = stream.eat("/") ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag bracket"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + inText.isInText = true; + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || ch == "/" && stream.eat(">")) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag bracket"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (ch == "<") { + state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; + var next = state.tokenize(stream, state); + return next ? next + " tag error" : "tag error"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + state.stringStartCol = stream.column(); + return state.tokenize(stream, state); + } else { + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); + return "word"; + } + } + function inAttribute(quote) { + var closure = function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + closure.isInAttribute = true; + return closure; + } + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + }; + } + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + function lower(tagName) { + return tagName && tagName.toLowerCase(); + } + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName || ""; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || state.context && state.context.noIndent) + this.noIndent = true; + } + function popContext(state) { + if (state.context) state.context = state.context.prev; + } + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(lower(parentTagName)) || !config.contextGrabbers[lower(parentTagName)].hasOwnProperty(lower(nextTagName))) { + return; + } + popContext(state); + } + } + function baseState(type2, stream, state) { + if (type2 == "openTag") { + state.tagStart = stream.column(); + return tagNameState; + } else if (type2 == "closeTag") { + return closeTagNameState; + } else { + return baseState; + } + } + function tagNameState(type2, stream, state) { + if (type2 == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else if (config.allowMissingTagName && type2 == "endTag") { + setStyle = "tag bracket"; + return attrState(type2, stream, state); + } else { + setStyle = "error"; + return tagNameState; + } + } + function closeTagNameState(type2, stream, state) { + if (type2 == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && config.implicitlyClosed.hasOwnProperty(lower(state.context.tagName))) + popContext(state); + if (state.context && state.context.tagName == tagName || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; + } + } else if (config.allowMissingTagName && type2 == "endTag") { + setStyle = "tag bracket"; + return closeState(type2, stream, state); + } else { + setStyle = "error"; + return closeStateErr; + } + } + function closeState(type2, _stream, state) { + if (type2 != "endTag") { + setStyle = "error"; + return closeState; + } + popContext(state); + return baseState; + } + function closeStateErr(type2, stream, state) { + setStyle = "error"; + return closeState(type2, stream, state); + } + function attrState(type2, _stream, state) { + if (type2 == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type2 == "endTag" || type2 == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type2 == "selfcloseTag" || config.autoSelfClosers.hasOwnProperty(lower(tagName))) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } + setStyle = "error"; + return attrState; + } + function attrEqState(type2, stream, state) { + if (type2 == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type2, stream, state); + } + function attrValueState(type2, stream, state) { + if (type2 == "string") return attrContinuedState; + if (type2 == "word" && config.allowUnquoted) { + setStyle = "string"; + return attrState; + } + setStyle = "error"; + return attrState(type2, stream, state); + } + function attrContinuedState(type2, stream, state) { + if (type2 == "string") return attrContinuedState; + return attrState(type2, stream, state); + } + return { + startState: function(baseIndent) { + var state = { + tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, + tagStart: null, + context: null + }; + if (baseIndent != null) state.baseIndent = baseIndent; + return state; + }, + token: function(stream, state) { + if (!state.tagName && stream.sol()) + state.indented = stream.indentation(); + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; + } + return style; + }, + indent: function(state, textAfter, fullLine) { + var context = state.context; + if (state.tokenize.isInAttribute) { + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; + } + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + if (state.tagName) { + if (config.multilineTagIndentPastTag !== false) + return state.tagStart + state.tagName.length + 2; + else + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); + } + if (config.alignCDATA && /$/, + blockCommentStart: "", + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState; + }, + xmlCurrentTag: function(state) { + return state.tagName ? { name: state.tagName, close: state.type == "closeTag" } : null; + }, + xmlCurrentContext: function(state) { + var context = []; + for (var cx = state.context; cx; cx = cx.prev) + context.push(cx.tagName); + return context.reverse(); + } + }; + }); + CodeMirror.defineMIME("text/xml", "xml"); + CodeMirror.defineMIME("application/xml", "xml"); + if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) + CodeMirror.defineMIME("text/html", { name: "xml", htmlMode: true }); + }); + })(); + return xml.exports; +} +var javascript = { exports: {} }; +var hasRequiredJavascript; +function requireJavascript() { + if (hasRequiredJavascript) return javascript.exports; + hasRequiredJavascript = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var trackScope = parserConfig.trackScope !== false; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + var keywords = function() { + function kw(type2) { + return { type: type2, style: "keyword" }; + } + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); + var operator = kw("operator"), atom = { type: "atom", style: "atom" }; + return { + "if": kw("if"), + "while": A, + "with": A, + "else": B, + "do": B, + "try": B, + "finally": B, + "return": D, + "break": D, + "continue": D, + "new": kw("new"), + "delete": C, + "void": C, + "throw": C, + "debugger": kw("debugger"), + "var": kw("var"), + "const": kw("var"), + "let": kw("var"), + "function": kw("function"), + "catch": kw("catch"), + "for": kw("for"), + "switch": kw("switch"), + "case": kw("case"), + "default": kw("default"), + "in": operator, + "typeof": operator, + "instanceof": operator, + "true": atom, + "false": atom, + "null": atom, + "undefined": atom, + "NaN": atom, + "Infinity": atom, + "this": kw("this"), + "class": kw("class"), + "super": kw("atom"), + "yield": C, + "export": kw("export"), + "import": kw("import"), + "extends": C, + "await": C + }; + }(); + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + var type, content; + function ret(tp, style, cont2) { + type = tp; + content = cont2; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#" && stream.peek() == "!") { + stream.skipToEnd(); + return ret("meta", "meta"); + } else if (ch == "#" && stream.eatWhile(wordRE)) { + return ret("variable", "property"); + } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("="); + } else if (/[<>*+\-|&?]/.test(ch)) { + stream.eat(ch); + if (ch == ">") stream.eat(ch); + } + } + if (ch == "?" && stream.eat(".")) return ret("."); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(); + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word]; + return ret(kw.type, kw.style, word); + } + if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) + return ret("async", "keyword", word); + } + return ret("variable", "variable", word); + } + } + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = ch == "*"; + } + return ret("comment", "comment"); + } + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + var brackets = "([{}])"; + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + if (isTS) { + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)); + if (m) arrow = m.index; + } + var depth = 0, sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { + ++pos; + break; + } + if (--depth == 0) { + if (ch == "(") sawSomething = true; + break; + } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (; ; --pos) { + if (pos == 0) return; + var next = stream.string.charAt(pos - 1); + if (next == ch && stream.string.charAt(pos - 2) != "\\") { + pos--; + break; + } + } + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + var atomicTypes = { + "atom": true, + "number": true, + "variable": true, + "string": true, + "regexp": true, + "this": true, + "import": true, + "jsonld-keyword": true + }; + function JSLexical(indented, column, type2, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type2; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + function inScope(state, varname) { + if (!trackScope) return false; + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx2 = state.context; cx2; cx2 = cx2.prev) { + for (var v = cx2.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + function parseJS(state, style, type2, content2, stream) { + var cc = state.cc; + cx.state = state; + cx.stream = stream; + cx.marked = null, cx.cc = cc; + cx.style = style; + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + while (true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type2, content2)) { + while (cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type2 == "variable" && inScope(state, content2)) return "variable-2"; + return style; + } + } + } + var cx = { state: null, marked: null, cc: null }; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) if (v.name == name) return true; + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (!trackScope) return; + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + var newContext = registerVarScoped(varname, state.context); + if (newContext != null) { + state.context = newContext; + return; + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars); + return; + } + } + if (parserConfig.globalVars && !inList(varname, state.globalVars)) + state.globalVars = new Var(varname, state.globalVars); + } + function registerVarScoped(varname, context) { + if (!context) { + return null; + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev); + if (!inner) return null; + if (inner == context.prev) return context; + return new Context(inner, context.vars, true); + } else if (inList(varname, context.vars)) { + return context; + } else { + return new Context(context.prev, new Var(varname, context.vars), false); + } + } + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; + } + function Context(prev, vars, block2) { + this.prev = prev; + this.vars = vars; + this.block = block2; + } + function Var(name, next) { + this.name = name; + this.next = next; + } + var defaultVars = new Var("this", new Var("arguments", null)); + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false); + cx.state.localVars = defaultVars; + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true); + cx.state.localVars = null; + } + pushcontext.lex = pushblockcontext.lex = true; + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + popcontext.lex = true; + function pushlex(type2, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type2, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + function expect(wanted) { + function exp(type2) { + if (type2 == wanted) return cont(); + else if (wanted == ";" || type2 == "}" || type2 == ")" || type2 == "]") return pass(); + else return cont(exp); + } + return exp; + } + function statement(type2, value) { + if (type2 == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type2 == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type2 == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type2 == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type2 == "debugger") return cont(expect(";")); + if (type2 == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type2 == ";") return cont(); + if (type2 == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type2 == "function") return cont(functiondef); + if (type2 == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form", type2 == "class" ? type2 : value), className, poplex); + } + if (type2 == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword"; + return cont(statement); + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword"; + if (value == "enum") return cont(enumdef); + else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); + else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); + } else if (isTS && value == "namespace") { + cx.marked = "keyword"; + return cont(pushlex("form"), expression, statement, poplex); + } else if (isTS && value == "abstract") { + cx.marked = "keyword"; + return cont(statement); + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type2 == "switch") return cont( + pushlex("form"), + parenExpr, + expect("{"), + pushlex("}", "switch"), + pushblockcontext, + block, + poplex, + poplex, + popcontext + ); + if (type2 == "case") return cont(expression, expect(":")); + if (type2 == "default") return cont(expect(":")); + if (type2 == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type2 == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type2 == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type2 == "async") return cont(statement); + if (value == "@") return cont(expression, statement); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type2) { + if (type2 == "(") return cont(funarg, expect(")")); + } + function expression(type2, value) { + return expressionInner(type2, value, false); + } + function expressionNoComma(type2, value) { + return expressionInner(type2, value, true); + } + function parenExpr(type2) { + if (type2 != "(") return pass(); + return cont(pushlex(")"), maybeexpression, expect(")"), poplex); + } + function expressionInner(type2, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); + else if (type2 == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); + if (type2 == "function") return cont(functiondef, maybeop); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form"), classExpression, poplex); + } + if (type2 == "keyword c" || type2 == "async") return cont(noComma ? expressionNoComma : expression); + if (type2 == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type2 == "operator" || type2 == "spread") return cont(noComma ? expressionNoComma : expression); + if (type2 == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type2 == "{") return contCommasep(objprop, "}", null, maybeop); + if (type2 == "quasi") return pass(quasi, maybeop); + if (type2 == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type2) { + if (type2.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + function maybeoperatorComma(type2, value) { + if (type2 == ",") return cont(maybeexpression); + return maybeoperatorNoComma(type2, value, false); + } + function maybeoperatorNoComma(type2, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type2 == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type2 == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type2 == "quasi") { + return pass(quasi, me); + } + if (type2 == ";") return; + if (type2 == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type2 == ".") return cont(property, me); + if (type2 == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { + cx.marked = "keyword"; + return cont(typeexpr, me); + } + if (type2 == "regexp") { + cx.state.lastType = cx.marked = "operator"; + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); + return cont(expr); + } + } + function quasi(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(maybeexpression, continueQuasi); + } + function continueQuasi(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expression); + } + function arrowBodyNoComma(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type2) { + if (type2 == ".") return cont(noComma ? targetNoComma : target); + else if (type2 == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma); + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorComma); + } + } + function targetNoComma(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorNoComma); + } + } + function maybelabel(type2) { + if (type2 == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type2) { + if (type2 == "variable") { + cx.marked = "property"; + return cont(); + } + } + function objprop(type2, value) { + if (type2 == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + var m; + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) + cx.state.fatArrowAt = cx.stream.pos + m[0].length; + return cont(afterprop); + } else if (type2 == "number" || type2 == "string") { + cx.marked = jsonldMode ? "property" : cx.style + " property"; + return cont(afterprop); + } else if (type2 == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type2 == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == ":") { + return pass(afterprop); + } + } + function getterSetter(type2) { + if (type2 != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type2) { + if (type2 == ":") return cont(expressionNoComma); + if (type2 == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type2, value) { + if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function(type3, value2) { + if (type3 == end || value2 == end) return pass(); + return pass(what); + }, proceed); + } + if (type2 == end || value == end) return cont(); + if (sep && sep.indexOf(";") > -1) return pass(what); + return cont(expect(end)); + } + return function(type2, value) { + if (type2 == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type2) { + if (type2 == "}") return cont(); + return pass(statement, block); + } + function maybetype(type2, value) { + if (isTS) { + if (type2 == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function maybetypeOrIn(type2, value) { + if (isTS && (type2 == ":" || value == "in")) return cont(typeexpr); + } + function mayberettype(type2) { + if (isTS && type2 == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr); + else return cont(typeexpr); + } + } + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword"; + return cont(); + } + } + function typeexpr(type2, value) { + if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { + cx.marked = "keyword"; + return cont(value == "typeof" ? expressionNoComma : typeexpr); + } + if (type2 == "variable" || value == "void") { + cx.marked = "type"; + return cont(afterType); + } + if (value == "|" || value == "&") return cont(typeexpr); + if (type2 == "string" || type2 == "number" || type2 == "atom") return cont(afterType); + if (type2 == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); + if (type2 == "{") return cont(pushlex("}"), typeprops, poplex, afterType); + if (type2 == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType); + if (type2 == "<") return cont(commasep(typeexpr, ">"), typeexpr); + if (type2 == "quasi") { + return pass(quasiType, afterType); + } + } + function maybeReturnType(type2) { + if (type2 == "=>") return cont(typeexpr); + } + function typeprops(type2) { + if (type2.match(/[\}\)\]]/)) return cont(); + if (type2 == "," || type2 == ";") return cont(typeprops); + return pass(typeprop, typeprops); + } + function typeprop(type2, value) { + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(typeprop); + } else if (value == "?" || type2 == "number" || type2 == "string") { + return cont(typeprop); + } else if (type2 == ":") { + return cont(typeexpr); + } else if (type2 == "[") { + return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); + } else if (type2 == "(") { + return pass(functiondecl, typeprop); + } else if (!type2.match(/[;\}\)\],]/)) { + return cont(); + } + } + function quasiType(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasiType); + return cont(typeexpr, continueQuasiType); + } + function continueQuasiType(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasiType); + } + } + function typearg(type2, value) { + if (type2 == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg); + if (type2 == ":") return cont(typeexpr); + if (type2 == "spread") return cont(typearg); + return pass(typeexpr); + } + function afterType(type2, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + if (value == "|" || type2 == "." || value == "&") return cont(typeexpr); + if (type2 == "[") return cont(typeexpr, expect("]"), afterType); + if (value == "extends" || value == "implements") { + cx.marked = "keyword"; + return cont(typeexpr); + } + if (value == "?") return cont(typeexpr, expect(":"), typeexpr); + } + function maybeTypeArgs(_, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault); + } + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr); + } + function vardef(_, value) { + if (value == "enum") { + cx.marked = "keyword"; + return cont(enumdef); + } + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type2, value) { + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(pattern); + } + if (type2 == "variable") { + register(value); + return cont(); + } + if (type2 == "spread") return cont(pattern); + if (type2 == "[") return contCommasep(eltpattern, "]"); + if (type2 == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type2, value) { + if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type2 == "variable") cx.marked = "property"; + if (type2 == "spread") return cont(pattern); + if (type2 == "}") return pass(); + if (type2 == "[") return cont(expression, expect("]"), expect(":"), proppattern); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign); + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type2) { + if (type2 == ",") return cont(vardef); + } + function maybeelse(type2, value) { + if (type2 == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type2, value) { + if (value == "await") return cont(forspec); + if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type2) { + if (type2 == "var") return cont(vardef, forspec2); + if (type2 == "variable") return cont(forspec2); + return pass(forspec2); + } + function forspec2(type2, value) { + if (type2 == ")") return cont(); + if (type2 == ";") return cont(forspec2); + if (value == "in" || value == "of") { + cx.marked = "keyword"; + return cont(expression, forspec2); + } + return pass(expression, forspec2); + } + function functiondef(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondef); + } + if (type2 == "variable") { + register(value); + return cont(functiondef); + } + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); + } + function functiondecl(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondecl); + } + if (type2 == "variable") { + register(value); + return cont(functiondecl); + } + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); + } + function typename(type2, value) { + if (type2 == "keyword" || type2 == "variable") { + cx.marked = "type"; + return cont(typename); + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex); + } + } + function funarg(type2, value) { + if (value == "@") cont(expression, funarg); + if (type2 == "spread") return cont(funarg); + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(funarg); + } + if (isTS && type2 == "this") return cont(maybetype, maybeAssign); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type2, value) { + if (type2 == "variable") return className(type2, value); + return classNameAfter(type2, value); + } + function className(type2, value) { + if (type2 == "variable") { + register(value); + return cont(classNameAfter); + } + } + function classNameAfter(type2, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); + if (value == "extends" || value == "implements" || isTS && type2 == ",") { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type2 == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type2, value) { + if (type2 == "async" || type2 == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+#?[\w$\xa1-\uffff]/, false)) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(classfield, classBody); + } + if (type2 == "number" || type2 == "string") return cont(classfield, classBody); + if (type2 == "[") + return cont(expression, maybetype, expect("]"), classfield, classBody); + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type2 == "(") return pass(functiondecl, classBody); + if (type2 == ";" || type2 == ",") return cont(classBody); + if (type2 == "}") return cont(); + if (value == "@") return cont(expression, classBody); + } + function classfield(type2, value) { + if (value == "!") return cont(classfield); + if (value == "?") return cont(classfield); + if (type2 == ":") return cont(typeexpr, maybeAssign); + if (value == "=") return cont(expressionNoComma); + var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"; + return pass(isInterface ? functiondecl : functiondef); + } + function afterExport(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(maybeFrom, expect(";")); + } + if (value == "default") { + cx.marked = "keyword"; + return cont(expression, expect(";")); + } + if (type2 == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type2, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(expect("variable")); + } + if (type2 == "variable") return pass(expressionNoComma, exportField); + } + function afterImport(type2) { + if (type2 == "string") return cont(); + if (type2 == "(") return pass(expression); + if (type2 == ".") return pass(maybeoperatorComma); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type2, value) { + if (type2 == "{") return contCommasep(importSpec, "}"); + if (type2 == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type2) { + if (type2 == ",") return cont(importSpec, maybeMoreImports); + } + function maybeAs(_type, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(importSpec); + } + } + function maybeFrom(_type, value) { + if (value == "from") { + cx.marked = "keyword"; + return cont(expression); + } + } + function arrayLiteral(type2) { + if (type2 == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); + } + function enummember() { + return pass(pattern, maybeAssign); + } + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); + } + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); + } + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + indent: function(state, textAfter) { + if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top; + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse && c != popcontext) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) + lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type2 = lexical.type, closing = firstChar == type2; + if (type2 == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); + else if (type2 == "form" && firstChar == "{") return lexical.indented; + else if (type2 == "form") return lexical.indented + indentUnit; + else if (type2 == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + helperType: jsonMode ? "json" : "javascript", + jsonldMode, + jsonMode, + expressionAllowed, + skipExpression: function(state) { + parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); + } + }; + }); + CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + CodeMirror.defineMIME("text/javascript", "javascript"); + CodeMirror.defineMIME("text/ecmascript", "javascript"); + CodeMirror.defineMIME("application/javascript", "javascript"); + CodeMirror.defineMIME("application/x-javascript", "javascript"); + CodeMirror.defineMIME("application/ecmascript", "javascript"); + CodeMirror.defineMIME("application/json", { name: "javascript", json: true }); + CodeMirror.defineMIME("application/x-json", { name: "javascript", json: true }); + CodeMirror.defineMIME("application/manifest+json", { name: "javascript", json: true }); + CodeMirror.defineMIME("application/ld+json", { name: "javascript", jsonld: true }); + CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); + CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + }); + })(); + return javascript.exports; +} +var hasRequiredHtmlmixed; +function requireHtmlmixed() { + if (hasRequiredHtmlmixed) return htmlmixed.exports; + hasRequiredHtmlmixed = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror(), requireXml(), requireJavascript(), requireCss()); + })(function(CodeMirror) { + var defaultTags = { + script: [ + ["lang", /(javascript|babel)/i, "javascript"], + ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], + ["type", /./, "text/plain"], + [null, null, "javascript"] + ], + style: [ + ["lang", /^css$/i, "css"], + ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], + ["type", /./, "text/plain"], + [null, null, "css"] + ] + }; + function maybeBackup(stream, pat, style) { + var cur = stream.current(), close = cur.search(pat); + if (close > -1) { + stream.backUp(cur.length - close); + } else if (cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur); + } + return style; + } + var attrRegexpCache = {}; + function getAttrRegexp(attr) { + var regexp = attrRegexpCache[attr]; + if (regexp) return regexp; + return attrRegexpCache[attr] = new RegExp("\\s+" + attr + `\\s*=\\s*('|")?([^'"]+)('|")?\\s*`); + } + function getAttrValue(text, attr) { + var match = text.match(getAttrRegexp(attr)); + return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : ""; + } + function getTagRegexp(tagName, anchored) { + return new RegExp((anchored ? "^" : "") + "", "i"); + } + function addTags(from, to) { + for (var tag in from) { + var dest = to[tag] || (to[tag] = []); + var source = from[tag]; + for (var i = source.length - 1; i >= 0; i--) + dest.unshift(source[i]); + } + } + function findMatchingMode(tagInfo, tagText) { + for (var i = 0; i < tagInfo.length; i++) { + var spec = tagInfo[i]; + if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; + } + } + CodeMirror.defineMode("htmlmixed", function(config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true, + multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, + multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag, + allowMissingTagName: parserConfig.allowMissingTagName + }); + var tags = {}; + var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; + addTags(defaultTags, tags); + if (configTags) addTags(configTags, tags); + if (configScript) for (var i = configScript.length - 1; i >= 0; i--) + tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]); + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName; + if (tag && !/[<>\s\/]/.test(stream.current()) && (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && tags.hasOwnProperty(tagName)) { + state.inTag = tagName + " "; + } else if (state.inTag && tag && />$/.test(stream.current())) { + var inTag = /^([\S]+) (.*)/.exec(state.inTag); + state.inTag = null; + var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]); + var mode = CodeMirror.getMode(config, modeSpec); + var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); + state.token = function(stream2, state2) { + if (stream2.match(endTagA, false)) { + state2.token = html; + state2.localState = state2.localMode = null; + return null; + } + return maybeBackup(stream2, endTag, state2.localMode.token(stream2, state2.localState)); + }; + state.localMode = mode; + state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", "")); + } else if (state.inTag) { + state.inTag += stream.current(); + if (stream.eol()) state.inTag += " "; + } + return style; + } + return { + startState: function() { + var state = CodeMirror.startState(htmlMode); + return { token: html, inTag: null, localMode: null, localState: null, htmlState: state }; + }, + copyState: function(state) { + var local; + if (state.localState) { + local = CodeMirror.copyState(state.localMode, state.localState); + } + return { + token: state.token, + inTag: state.inTag, + localMode: state.localMode, + localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState) + }; + }, + token: function(stream, state) { + return state.token(stream, state); + }, + indent: function(state, textAfter, line) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter, line); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter, line); + else + return CodeMirror.Pass; + }, + innerMode: function(state) { + return { state: state.localState || state.htmlState, mode: state.localMode || htmlMode }; + } + }; + }, "xml", "javascript", "css"); + CodeMirror.defineMIME("text/html", "htmlmixed"); + }); + })(); + return htmlmixed.exports; +} +requireHtmlmixed(); +requireJavascript(); +var python = { exports: {} }; +var hasRequiredPython; +function requirePython() { + if (hasRequiredPython) return python.exports; + hasRequiredPython = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + function wordRegexp(words2) { + return new RegExp("^((" + words2.join(")|(") + "))\\b"); + } + var wordOperators = wordRegexp(["and", "or", "not", "is"]); + var commonKeywords = [ + "as", + "assert", + "break", + "class", + "continue", + "def", + "del", + "elif", + "else", + "except", + "finally", + "for", + "from", + "global", + "if", + "import", + "lambda", + "pass", + "raise", + "return", + "try", + "while", + "with", + "yield", + "in", + "False", + "True" + ]; + var commonBuiltins = [ + "abs", + "all", + "any", + "bin", + "bool", + "bytearray", + "callable", + "chr", + "classmethod", + "compile", + "complex", + "delattr", + "dict", + "dir", + "divmod", + "enumerate", + "eval", + "filter", + "float", + "format", + "frozenset", + "getattr", + "globals", + "hasattr", + "hash", + "help", + "hex", + "id", + "input", + "int", + "isinstance", + "issubclass", + "iter", + "len", + "list", + "locals", + "map", + "max", + "memoryview", + "min", + "next", + "object", + "oct", + "open", + "ord", + "pow", + "property", + "range", + "repr", + "reversed", + "round", + "set", + "setattr", + "slice", + "sorted", + "staticmethod", + "str", + "sum", + "super", + "tuple", + "type", + "vars", + "zip", + "__import__", + "NotImplemented", + "Ellipsis", + "__debug__" + ]; + CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins).concat(["exec", "print"])); + function top(state) { + return state.scopes[state.scopes.length - 1]; + } + CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = "error"; + var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/; + var operators = [ + parserConf.singleOperators, + parserConf.doubleOperators, + parserConf.doubleDelimiters, + parserConf.tripleDelimiters, + parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/ + ]; + for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1); + var hangingIndent = parserConf.hangingIndent || conf.indentUnit; + var myKeywords = commonKeywords, myBuiltins = commonBuiltins; + if (parserConf.extra_keywords != void 0) + myKeywords = myKeywords.concat(parserConf.extra_keywords); + if (parserConf.extra_builtins != void 0) + myBuiltins = myBuiltins.concat(parserConf.extra_builtins); + var py3 = !(parserConf.version && Number(parserConf.version) < 3); + if (py3) { + var identifiers = parserConf.identifiers || /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/; + myKeywords = myKeywords.concat(["nonlocal", "None", "aiter", "anext", "async", "await", "breakpoint", "match", "case"]); + myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]); + var stringPrefixes = new RegExp(`^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|"{3}|['"]))`, "i"); + } else { + var identifiers = parserConf.identifiers || /^[_A-Za-z][_A-Za-z0-9]*/; + myKeywords = myKeywords.concat(["exec", "print"]); + myBuiltins = myBuiltins.concat([ + "apply", + "basestring", + "buffer", + "cmp", + "coerce", + "execfile", + "file", + "intern", + "long", + "raw_input", + "reduce", + "reload", + "unichr", + "unicode", + "xrange", + "None" + ]); + var stringPrefixes = new RegExp(`^(([rubf]|(ur)|(br))?('{3}|"{3}|['"]))`, "i"); + } + var keywords = wordRegexp(myKeywords); + var builtins = wordRegexp(myBuiltins); + function tokenBase(stream, state) { + var sol = stream.sol() && state.lastToken != "\\"; + if (sol) state.indent = stream.indentation(); + if (sol && top(state).type == "py") { + var scopeOffset = top(state).offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) + pushPyScope(state); + else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") + state.errorToken = true; + return null; + } else { + var style = tokenBaseInner(stream, state); + if (scopeOffset > 0 && dedent(stream, state)) + style += " " + ERRORCLASS; + return style; + } + } + return tokenBaseInner(stream, state); + } + function tokenBaseInner(stream, state, inFormat) { + if (stream.eatSpace()) return null; + if (!inFormat && stream.match(/^#.*/)) return "comment"; + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { + floatLiteral = true; + } + if (stream.match(/^[\d_]+\.\d*/)) { + floatLiteral = true; + } + if (stream.match(/^\.\d+/)) { + floatLiteral = true; + } + if (floatLiteral) { + stream.eat(/J/i); + return "number"; + } + var intLiteral = false; + if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true; + if (stream.match(/^0b[01_]+/i)) intLiteral = true; + if (stream.match(/^0o[0-7_]+/i)) intLiteral = true; + if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) { + stream.eat(/J/i); + intLiteral = true; + } + if (stream.match(/^0(?![\dx])/i)) intLiteral = true; + if (intLiteral) { + stream.eat(/L/i); + return "number"; + } + } + if (stream.match(stringPrefixes)) { + var isFmtString = stream.current().toLowerCase().indexOf("f") !== -1; + if (!isFmtString) { + state.tokenize = tokenStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } else { + state.tokenize = formatStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } + } + for (var i2 = 0; i2 < operators.length; i2++) + if (stream.match(operators[i2])) return "operator"; + if (stream.match(delimiters)) return "punctuation"; + if (state.lastToken == "." && stream.match(identifiers)) + return "property"; + if (stream.match(keywords) || stream.match(wordOperators)) + return "keyword"; + if (stream.match(builtins)) + return "builtin"; + if (stream.match(/^(self|cls)\b/)) + return "variable-2"; + if (stream.match(identifiers)) { + if (state.lastToken == "def" || state.lastToken == "class") + return "def"; + return "variable"; + } + stream.next(); + return inFormat ? null : ERRORCLASS; + } + function formatStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + function tokenNestedExpr(depth) { + return function(stream, state) { + var inner = tokenBaseInner(stream, state, true); + if (inner == "punctuation") { + if (stream.current() == "{") { + state.tokenize = tokenNestedExpr(depth + 1); + } else if (stream.current() == "}") { + if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1); + else state.tokenize = tokenString; + } + } + return inner; + }; + } + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\{\}\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else if (stream.match("{{")) { + return OUTCLASS; + } else if (stream.match("{", false)) { + state.tokenize = tokenNestedExpr(0); + if (stream.current()) return OUTCLASS; + else return state.tokenize(stream, state); + } else if (stream.match("}}")) { + return OUTCLASS; + } else if (stream.match("}")) { + return ERRORCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + function tokenStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + function pushPyScope(state) { + while (top(state).type != "py") state.scopes.pop(); + state.scopes.push({ + offset: top(state).offset + conf.indentUnit, + type: "py", + align: null + }); + } + function pushBracketScope(stream, state, type) { + var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1; + state.scopes.push({ + offset: state.indent + hangingIndent, + type, + align + }); + } + function dedent(stream, state) { + var indented = stream.indentation(); + while (state.scopes.length > 1 && top(state).offset > indented) { + if (top(state).type != "py") return true; + state.scopes.pop(); + } + return top(state).offset != indented; + } + function tokenLexer(stream, state) { + if (stream.sol()) { + state.beginningOfLine = true; + state.dedent = false; + } + var style = state.tokenize(stream, state); + var current = stream.current(); + if (state.beginningOfLine && current == "@") + return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS; + if (/\S/.test(current)) state.beginningOfLine = false; + if ((style == "variable" || style == "builtin") && state.lastToken == "meta") + style = "meta"; + if (current == "pass" || current == "return") + state.dedent = true; + if (current == "lambda") state.lambda = true; + if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false)) + pushPyScope(state); + if (current.length == 1 && !/string|comment/.test(style)) { + var delimiter_index = "[({".indexOf(current); + if (delimiter_index != -1) + pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index + 1)); + delimiter_index = "])}".indexOf(current); + if (delimiter_index != -1) { + if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent; + else return ERRORCLASS; + } + } + if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1) + state.scopes.pop(); + return style; + } + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{ offset: basecolumn || 0, type: "py", align: null }], + indent: basecolumn || 0, + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + token: function(stream, state) { + var addErr = state.errorToken; + if (addErr) state.errorToken = false; + var style = tokenLexer(stream, state); + if (style && style != "comment") + state.lastToken = style == "keyword" || style == "punctuation" ? stream.current() : style; + if (style == "punctuation") style = null; + if (stream.eol() && state.lambda) + state.lambda = false; + return addErr ? style + " " + ERRORCLASS : style; + }, + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) + return state.tokenize.isString ? CodeMirror.Pass : 0; + var scope = top(state); + var closing = scope.type == textAfter.charAt(0) || scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter); + if (scope.align != null) + return scope.align - (closing ? 1 : 0); + else + return scope.offset - (closing ? hangingIndent : 0); + }, + electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/, + closeBrackets: { triples: `'"` }, + lineComment: "#", + fold: "indent" + }; + return external; + }); + CodeMirror.defineMIME("text/x-python", "python"); + var words = function(str) { + return str.split(" "); + }; + CodeMirror.defineMIME("text/x-cython", { + name: "python", + extra_keywords: words("by cdef cimport cpdef ctypedef enum except extern gil include nogil property public readonly struct union DEF IF ELIF ELSE") + }); + }); + })(); + return python.exports; +} +requirePython(); +var clike = { exports: {} }; +var hasRequiredClike; +function requireClike() { + if (hasRequiredClike) return clike.exports; + hasRequiredClike = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + function Context(indented, column, type, info, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.info = info; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type, info) { + var indent = state.indented; + if (state.context && state.context.type == "statement" && type != "statement") + indent = state.context.indented; + return state.context = new Context(indent, col, type, info, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + function typeBefore(stream, state, pos) { + if (state.prevToken == "variable" || state.prevToken == "type") return true; + if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; + if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; + } + function isTopScope(context) { + for (; ; ) { + if (!context || context.type == "top") return true; + if (context.type == "}" && context.prev.info != "namespace") return false; + context = context.prev; + } + } + CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, dontAlignCalls = parserConfig.dontAlignCalls, keywords = parserConfig.keywords || {}, types = parserConfig.types || {}, builtin = parserConfig.builtin || {}, blockKeywords = parserConfig.blockKeywords || {}, defKeywords = parserConfig.defKeywords || {}, atoms = parserConfig.atoms || {}, hooks = parserConfig.hooks || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false, indentSwitch = parserConfig.indentSwitch !== false, namespaceSeparator = parserConfig.namespaceSeparator, isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, numberStart = parserConfig.numberStart || /[\d\.]/, number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/, isReservedIdentifier = parserConfig.isReservedIdentifier || false; + var curPunc, isDefKeyword; + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (numberStart.test(ch)) { + stream.backUp(1); + if (stream.match(number)) return "number"; + stream.next(); + } + if (isPunctuationChar.test(ch)) { + curPunc = ch; + return null; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) { + } + return "operator"; + } + stream.eatWhile(isIdentifierChar); + if (namespaceSeparator) while (stream.match(namespaceSeparator)) + stream.eatWhile(isIdentifierChar); + var cur = stream.current(); + if (contains(keywords, cur)) { + if (contains(blockKeywords, cur)) curPunc = "newstatement"; + if (contains(defKeywords, cur)) isDefKeyword = true; + return "keyword"; + } + if (contains(types, cur)) return "type"; + if (contains(builtin, cur) || isReservedIdentifier && isReservedIdentifier(cur)) { + if (contains(blockKeywords, cur)) curPunc = "newstatement"; + return "builtin"; + } + if (contains(atoms, cur)) return "atom"; + return "variable"; + } + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) { + end = true; + break; + } + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = null; + return "string"; + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = ch == "*"; + } + return "comment"; + } + function maybeEOL(stream, state) { + if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) + state.typeAtEndOfLine = typeBefore(stream, state, stream.pos); + } + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), + indented: 0, + startOfLine: true, + prevToken: null + }; + }, + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) { + maybeEOL(stream, state); + return null; + } + curPunc = isDefKeyword = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + if (curPunc == ";" || curPunc == ":" || curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false)) + while (state.context.type == "statement") popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } else if (curPunc == ctx.type) popContext(state); + else if (indentStatements && ((ctx.type == "}" || ctx.type == "top") && curPunc != ";" || ctx.type == "statement" && curPunc == "newstatement")) { + pushContext(state, stream.column(), "statement", stream.current()); + } + if (style == "variable" && (state.prevToken == "def" || parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && isTopScope(state.context) && stream.match(/^\s*\(/, false))) + style = "def"; + if (hooks.token) { + var result = hooks.token(stream, state, style); + if (result !== void 0) style = result; + } + if (style == "def" && parserConfig.styleDefs === false) style = "variable"; + state.startOfLine = false; + state.prevToken = isDefKeyword ? "def" : style || curPunc; + maybeEOL(stream, state); + return style; + }, + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine && isTopScope(state.context)) + return CodeMirror.Pass; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + var closing = firstChar == ctx.type; + if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; + if (parserConfig.dontIndentStatements) + while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) + ctx = ctx.prev; + if (hooks.indent) { + var hook = hooks.indent(state, ctx, textAfter, indentUnit); + if (typeof hook == "number") return hook; + } + var switchBlock = ctx.prev && ctx.prev.info == "switch"; + if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { + while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev; + return ctx.indented; + } + if (ctx.type == "statement") + return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); + if (ctx.align && (!dontAlignCalls || ctx.type != ")")) + return ctx.column + (closing ? 0 : 1); + if (ctx.type == ")" && !closing) + return ctx.indented + statementIndentUnit; + return ctx.indented + (closing ? 0 : indentUnit) + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); + }, + electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, + blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * ", + lineComment: "//", + fold: "brace" + }; + }); + function words(str) { + var obj = {}, words2 = str.split(" "); + for (var i = 0; i < words2.length; ++i) obj[words2[i]] = true; + return obj; + } + function contains(words2, word) { + if (typeof words2 === "function") { + return words2(word); + } else { + return words2.propertyIsEnumerable(word); + } + } + var cKeywords = "auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran"; + var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch class compl concept constexpr const_cast decltype delete dynamic_cast explicit export final friend import module mutable namespace new noexcept not not_eq operator or or_eq override private protected public reinterpret_cast requires static_assert static_cast template this thread_local throw try typeid typename using virtual xor xor_eq"; + var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd @interface @implementation @end @protocol @encode @property @synthesize @dynamic @class @public @package @private @protected @required @optional @try @catch @finally @import @selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"; + var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT"; + var basicCTypes = words("int long char short double float unsigned signed void bool"); + var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL"); + function cTypes(identifier) { + return contains(basicCTypes, identifier) || /.+_t$/.test(identifier); + } + function objCTypes(identifier) { + return cTypes(identifier) || contains(basicObjCTypes, identifier); + } + var cBlockKeywords = "case do else for if switch while struct enum union"; + var cDefKeywords = "struct enum union"; + function cppHook(stream, state) { + if (!state.startOfLine) return false; + for (var ch, next = null; ch = stream.peek(); ) { + if (ch == "\\" && stream.match(/^.$/)) { + next = cppHook; + break; + } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { + break; + } + stream.next(); + } + state.tokenize = next; + return "meta"; + } + function pointerHook(_stream, state) { + if (state.prevToken == "type") return "type"; + return false; + } + function cIsReservedIdentifier(token) { + if (!token || token.length < 2) return false; + if (token[0] != "_") return false; + return token[1] == "_" || token[1] !== token[1].toLowerCase(); + } + function cpp14Literal(stream) { + stream.eatWhile(/[\w\.']/); + return "number"; + } + function cpp11StringHook(stream, state) { + stream.backUp(1); + if (stream.match(/^(?:R|u8R|uR|UR|LR)/)) { + var match = stream.match(/^"([^\s\\()]{0,16})\(/); + if (!match) { + return false; + } + state.cpp11RawStringDelim = match[1]; + state.tokenize = tokenRawString; + return tokenRawString(stream, state); + } + if (stream.match(/^(?:u8|u|U|L)/)) { + if (stream.match( + /^["']/, + /* eat */ + false + )) { + return "string"; + } + return false; + } + stream.next(); + return false; + } + function cppLooksLikeConstructor(word) { + var lastTwo = /(\w+)::~?(\w+)$/.exec(word); + return lastTwo && lastTwo[1] == lastTwo[2]; + } + function tokenAtString(stream, state) { + var next; + while ((next = stream.next()) != null) { + if (next == '"' && !stream.eat('"')) { + state.tokenize = null; + break; + } + } + return "string"; + } + function tokenRawString(stream, state) { + var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, "\\$&"); + var match = stream.match(new RegExp(".*?\\)" + delim + '"')); + if (match) + state.tokenize = null; + else + stream.skipToEnd(); + return "string"; + } + function def(mimes, mode) { + if (typeof mimes == "string") mimes = [mimes]; + var words2 = []; + function add(obj) { + if (obj) { + for (var prop in obj) if (obj.hasOwnProperty(prop)) + words2.push(prop); + } + } + add(mode.keywords); + add(mode.types); + add(mode.builtin); + add(mode.atoms); + if (words2.length) { + mode.helperType = mimes[0]; + CodeMirror.registerHelper("hintWords", mimes[0], words2); + } + for (var i = 0; i < mimes.length; ++i) + CodeMirror.defineMIME(mimes[i], mode); + } + def(["text/x-csrc", "text/x-c", "text/x-chdr"], { + name: "clike", + keywords: words(cKeywords), + types: cTypes, + blockKeywords: words(cBlockKeywords), + defKeywords: words(cDefKeywords), + typeFirstDefinitions: true, + atoms: words("NULL true false"), + isReservedIdentifier: cIsReservedIdentifier, + hooks: { + "#": cppHook, + "*": pointerHook + }, + modeProps: { fold: ["brace", "include"] } + }); + def(["text/x-c++src", "text/x-c++hdr"], { + name: "clike", + keywords: words(cKeywords + " " + cppKeywords), + types: cTypes, + blockKeywords: words(cBlockKeywords + " class try catch"), + defKeywords: words(cDefKeywords + " class namespace"), + typeFirstDefinitions: true, + atoms: words("true false NULL nullptr"), + dontIndentStatements: /^template$/, + isIdentifierChar: /[\w\$_~\xa1-\uffff]/, + isReservedIdentifier: cIsReservedIdentifier, + hooks: { + "#": cppHook, + "*": pointerHook, + "u": cpp11StringHook, + "U": cpp11StringHook, + "L": cpp11StringHook, + "R": cpp11StringHook, + "0": cpp14Literal, + "1": cpp14Literal, + "2": cpp14Literal, + "3": cpp14Literal, + "4": cpp14Literal, + "5": cpp14Literal, + "6": cpp14Literal, + "7": cpp14Literal, + "8": cpp14Literal, + "9": cpp14Literal, + token: function(stream, state, style) { + if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) + return "def"; + } + }, + namespaceSeparator: "::", + modeProps: { fold: ["brace", "include"] } + }); + def("text/x-java", { + name: "clike", + keywords: words("abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while @interface"), + types: words("var byte short int long float double boolean char void Boolean Byte Character Double Float Integer Long Number Object Short String StringBuffer StringBuilder Void"), + blockKeywords: words("catch class do else finally for if switch try while"), + defKeywords: words("class interface enum @interface"), + typeFirstDefinitions: true, + atoms: words("true false null"), + number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, + hooks: { + "@": function(stream) { + if (stream.match("interface", false)) return false; + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + if (!stream.match(/""$/)) return false; + state.tokenize = tokenTripleString; + return state.tokenize(stream, state); + } + }, + modeProps: { fold: ["brace", "import"] } + }); + def("text/x-csharp", { + name: "clike", + keywords: words("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in init interface internal is lock namespace new operator out override params private protected public readonly record ref required return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual void volatile while add alias ascending descending dynamic from get global group into join let orderby partial remove select set value var yield"), + types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32 UInt64 bool byte char decimal double short int long object sbyte float string ushort uint ulong"), + blockKeywords: words("catch class do else finally for foreach if struct switch try while"), + defKeywords: words("class interface namespace record struct var"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { + "@": function(stream, state) { + if (stream.eat('"')) { + state.tokenize = tokenAtString; + return tokenAtString(stream, state); + } + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + function tokenTripleString(stream, state) { + var escaped = false; + while (!stream.eol()) { + if (!escaped && stream.match('"""')) { + state.tokenize = null; + break; + } + escaped = stream.next() == "\\" && !escaped; + } + return "string"; + } + function tokenNestedComment(depth) { + return function(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "*" && stream.eat("/")) { + if (depth == 1) { + state.tokenize = null; + break; + } else { + state.tokenize = tokenNestedComment(depth - 1); + return state.tokenize(stream, state); + } + } else if (ch == "/" && stream.eat("*")) { + state.tokenize = tokenNestedComment(depth + 1); + return state.tokenize(stream, state); + } + } + return "comment"; + }; + } + def("text/x-scala", { + name: "clike", + keywords: words( + /* scala */ + "abstract case catch class def do else extends final finally for forSome if implicit import lazy match new null object override package private protected return sealed super this throw trait try type val var while with yield _ assert assume require print println printf readLine readBoolean readByte readShort readChar readInt readLong readFloat readDouble" + ), + types: words( + "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + ), + multiLineStrings: true, + blockKeywords: words("catch class enum do else finally for forSome if match switch try while"), + defKeywords: words("class enum def object package trait type val var"), + atoms: words("true false null"), + indentStatements: false, + indentSwitch: false, + isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + if (!stream.match('""')) return false; + state.tokenize = tokenTripleString; + return state.tokenize(stream, state); + }, + "'": function(stream) { + if (stream.match(/^(\\[^'\s]+|[^\\'])'/)) return "string-2"; + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + }, + "=": function(stream, state) { + var cx = state.context; + if (cx.type == "}" && cx.align && stream.eat(">")) { + state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev); + return "operator"; + } else { + return false; + } + }, + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenNestedComment(1); + return state.tokenize(stream, state); + } + }, + modeProps: { closeBrackets: { pairs: '()[]{}""', triples: '"' } } + }); + function tokenKotlinString(tripleString) { + return function(stream, state) { + var escaped = false, next, end = false; + while (!stream.eol()) { + if (!tripleString && !escaped && stream.match('"')) { + end = true; + break; + } + if (tripleString && stream.match('"""')) { + end = true; + break; + } + next = stream.next(); + if (!escaped && next == "$" && stream.match("{")) + stream.skipTo("}"); + escaped = !escaped && next == "\\" && !tripleString; + } + if (end || !tripleString) + state.tokenize = null; + return "string"; + }; + } + def("text/x-kotlin", { + name: "clike", + keywords: words( + /*keywords*/ + "package as typealias class interface this super val operator var fun for is in This throw return annotation break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix suspend actual expect setparam value" + ), + types: words( + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy LazyThreadSafetyMode LongArray Nothing ShortArray Unit" + ), + intendSwitch: false, + indentStatements: false, + multiLineStrings: true, + number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, + blockKeywords: words("catch class do else finally for if where try while enum"), + defKeywords: words("class val var object interface fun"), + atoms: words("true false null this"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + "*": function(_stream, state) { + return state.prevToken == "." ? "variable" : "operator"; + }, + '"': function(stream, state) { + state.tokenize = tokenKotlinString(stream.match('""')); + return state.tokenize(stream, state); + }, + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenNestedComment(1); + return state.tokenize(stream, state); + }, + indent: function(state, ctx, textAfter, indentUnit) { + var firstChar = textAfter && textAfter.charAt(0); + if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "") + return state.indented; + if (state.prevToken == "operator" && textAfter != "}" && state.context.type != "}" || state.prevToken == "variable" && firstChar == "." || (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".") + return indentUnit * 2 + ctx.indented; + if (ctx.align && ctx.type == "}") + return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit); + } + }, + modeProps: { closeBrackets: { triples: '"' } } + }); + def(["x-shader/x-vertex", "x-shader/x-fragment"], { + name: "clike", + keywords: words("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"), + types: words("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"), + blockKeywords: words("for while do if else struct"), + builtin: words("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"), + atoms: words("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TextureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"), + indentSwitch: false, + hooks: { "#": cppHook }, + modeProps: { fold: ["brace", "include"] } + }); + def("text/x-nesc", { + name: "clike", + keywords: words(cKeywords + " as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"), + types: cTypes, + blockKeywords: words(cBlockKeywords), + atoms: words("null true false"), + hooks: { "#": cppHook }, + modeProps: { fold: ["brace", "include"] } + }); + def("text/x-objectivec", { + name: "clike", + keywords: words(cKeywords + " " + objCKeywords), + types: objCTypes, + builtin: words(objCBuiltins), + blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"), + defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"), + dontIndentStatements: /^@.*$/, + typeFirstDefinitions: true, + atoms: words("YES NO NULL Nil nil true false nullptr"), + isReservedIdentifier: cIsReservedIdentifier, + hooks: { + "#": cppHook, + "*": pointerHook + }, + modeProps: { fold: ["brace", "include"] } + }); + def("text/x-objectivec++", { + name: "clike", + keywords: words(cKeywords + " " + objCKeywords + " " + cppKeywords), + types: objCTypes, + builtin: words(objCBuiltins), + blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"), + defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class class namespace"), + dontIndentStatements: /^@.*$|^template$/, + typeFirstDefinitions: true, + atoms: words("YES NO NULL Nil nil true false nullptr"), + isReservedIdentifier: cIsReservedIdentifier, + hooks: { + "#": cppHook, + "*": pointerHook, + "u": cpp11StringHook, + "U": cpp11StringHook, + "L": cpp11StringHook, + "R": cpp11StringHook, + "0": cpp14Literal, + "1": cpp14Literal, + "2": cpp14Literal, + "3": cpp14Literal, + "4": cpp14Literal, + "5": cpp14Literal, + "6": cpp14Literal, + "7": cpp14Literal, + "8": cpp14Literal, + "9": cpp14Literal, + token: function(stream, state, style) { + if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) + return "def"; + } + }, + namespaceSeparator: "::", + modeProps: { fold: ["brace", "include"] } + }); + def("text/x-squirrel", { + name: "clike", + keywords: words("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"), + types: cTypes, + blockKeywords: words("case catch class else for foreach if switch try while"), + defKeywords: words("function local class"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { "#": cppHook }, + modeProps: { fold: ["brace", "include"] } + }); + var stringTokenizer = null; + function tokenCeylonString(type) { + return function(stream, state) { + var escaped = false, next, end = false; + while (!stream.eol()) { + if (!escaped && stream.match('"') && (type == "single" || stream.match('""'))) { + end = true; + break; + } + if (!escaped && stream.match("``")) { + stringTokenizer = tokenCeylonString(type); + end = true; + break; + } + next = stream.next(); + escaped = type == "single" && !escaped && next == "\\"; + } + if (end) + state.tokenize = null; + return "string"; + }; + } + def("text/x-ceylon", { + name: "clike", + keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"), + types: function(word) { + var first = word.charAt(0); + return first === first.toUpperCase() && first !== first.toLowerCase(); + }, + blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), + defKeywords: words("class dynamic function interface module object package value"), + builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"), + isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, + isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, + numberStart: /[\d#$]/, + number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, + multiLineStrings: true, + typeFirstDefinitions: true, + atoms: words("true false null larger smaller equal empty finished"), + indentSwitch: false, + styleDefs: false, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); + return state.tokenize(stream, state); + }, + "`": function(stream, state) { + if (!stringTokenizer || !stream.match("`")) return false; + state.tokenize = stringTokenizer; + stringTokenizer = null; + return state.tokenize(stream, state); + }, + "'": function(stream) { + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + }, + token: function(_stream, state, style) { + if ((style == "variable" || style == "type") && state.prevToken == ".") { + return "variable-2"; + } + } + }, + modeProps: { + fold: ["brace", "import"], + closeBrackets: { triples: '"' } + } + }); + }); + })(); + return clike.exports; +} +requireClike(); +var markdown = { exports: {} }; +var meta = { exports: {} }; +var hasRequiredMeta; +function requireMeta() { + if (hasRequiredMeta) return meta.exports; + hasRequiredMeta = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + CodeMirror.modeInfo = [ + { name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"] }, + { name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"] }, + { name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"] }, + { name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i }, + { name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"] }, + { name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"] }, + { name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"] }, + { name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy", "cbl"] }, + { name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp", "cs"] }, + { name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"] }, + { name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"] }, + { name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"] }, + { name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists\.txt$/ }, + { name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"] }, + { name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"] }, + { name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"] }, + { name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"] }, + { name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"] }, + { name: "CSS", mime: "text/css", mode: "css", ext: ["css"] }, + { name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"] }, + { name: "D", mime: "text/x-d", mode: "d", ext: ["d"] }, + { name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"] }, + { name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"] }, + { name: "Django", mime: "text/x-django", mode: "django" }, + { name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/ }, + { name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"] }, + { name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"] }, + { name: "EBNF", mime: "text/x-ebnf", mode: "ebnf" }, + { name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"] }, + { name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"] }, + { name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"] }, + { name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"] }, + { name: "Embedded JavaScript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"] }, + { name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"] }, + { name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"] }, + { name: "Esper", mime: "text/x-esper", mode: "sql" }, + { name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"] }, + { name: "FCL", mime: "text/x-fcl", mode: "fcl" }, + { name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"] }, + { name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90", "f95"] }, + { name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"] }, + { name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"] }, + { name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"] }, + { name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history)\.md$/i }, + { name: "Go", mime: "text/x-go", mode: "go", ext: ["go"] }, + { name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/ }, + { name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"] }, + { name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"] }, + { name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"] }, + { name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"] }, + { name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"] }, + { name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"] }, + { name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"] }, + { name: "HTTP", mime: "message/http", mode: "http" }, + { name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"] }, + { name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"] }, + { name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"] }, + { name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"] }, + { + name: "JavaScript", + mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"], + mode: "javascript", + ext: ["js"], + alias: ["ecmascript", "js", "node"] + }, + { name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"] }, + { name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"] }, + { name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"] }, + { name: "Jinja2", mime: "text/jinja2", mode: "jinja2", ext: ["j2", "jinja", "jinja2"] }, + { name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"], alias: ["jl"] }, + { name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"] }, + { name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"] }, + { name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"] }, + { name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"] }, + { name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"] }, + { name: "mIRC", mime: "text/mirc", mode: "mirc" }, + { name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql" }, + { name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb", "wl", "wls"] }, + { name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"] }, + { name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"] }, + { name: "MS SQL", mime: "text/x-mssql", mode: "sql" }, + { name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"] }, + { name: "MySQL", mime: "text/x-mysql", mode: "sql" }, + { name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i }, + { name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"] }, + { + name: "NTriples", + mimes: ["application/n-triples", "application/n-quads", "text/n-triples"], + mode: "ntriples", + ext: ["nt", "nq"] + }, + { name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m"], alias: ["objective-c", "objc"] }, + { name: "Objective-C++", mime: "text/x-objectivec++", mode: "clike", ext: ["mm"], alias: ["objective-c++", "objc++"] }, + { name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"] }, + { name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"] }, + { name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"] }, + { name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"] }, + { name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"] }, + { name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"] }, + { name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"] }, + { name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"] }, + { name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"] }, + { name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"] }, + { name: "PostgreSQL", mime: "text/x-pgsql", mode: "sql" }, + { name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"] }, + { name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"] }, + { name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"] }, + { name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/ }, + { name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"] }, + { name: "Q", mime: "text/x-q", mode: "q", ext: ["q"] }, + { name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"] }, + { name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"] }, + { name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm" }, + { name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"] }, + { name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"] }, + { name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"] }, + { name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"] }, + { name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"] }, + { name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"] }, + { name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"] }, + { name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"] }, + { name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/ }, + { name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"] }, + { name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"] }, + { name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"] }, + { name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"] }, + { name: "Solr", mime: "text/x-solr", mode: "solr" }, + { name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"] }, + { name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"] }, + { name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"] }, + { name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"] }, + { name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"] }, + { name: "SQLite", mime: "text/x-sqlite", mode: "sql" }, + { name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"] }, + { name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"] }, + { name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"] }, + { name: "sTeX", mime: "text/x-stex", mode: "stex" }, + { name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"] }, + { name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"] }, + { name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"] }, + { name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"] }, + { name: "TiddlyWiki", mime: "text/x-tiddlywiki", mode: "tiddlywiki" }, + { name: "Tiki wiki", mime: "text/tiki", mode: "tiki" }, + { name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"] }, + { name: "Tornado", mime: "text/x-tornado", mode: "tornado" }, + { name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"] }, + { name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"] }, + { name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"] }, + { name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"] }, + { name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"] }, + { name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"] }, + { name: "Twig", mime: "text/x-twig", mode: "twig" }, + { name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"] }, + { name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"] }, + { name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"] }, + { name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"] }, + { name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"] }, + { name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"] }, + { name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"] }, + { name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"] }, + { name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"] }, + { name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"] }, + { name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"] }, + { name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"] }, + { name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"] }, + { name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"] }, + { name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"] }, + { name: "WebAssembly", mime: "text/webassembly", mode: "wast", ext: ["wat", "wast"] } + ]; + for (var i = 0; i < CodeMirror.modeInfo.length; i++) { + var info = CodeMirror.modeInfo[i]; + if (info.mimes) info.mime = info.mimes[0]; + } + CodeMirror.findModeByMIME = function(mime) { + mime = mime.toLowerCase(); + for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) { + var info2 = CodeMirror.modeInfo[i2]; + if (info2.mime == mime) return info2; + if (info2.mimes) { + for (var j = 0; j < info2.mimes.length; j++) + if (info2.mimes[j] == mime) return info2; + } + } + if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml"); + if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json"); + }; + CodeMirror.findModeByExtension = function(ext) { + ext = ext.toLowerCase(); + for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) { + var info2 = CodeMirror.modeInfo[i2]; + if (info2.ext) { + for (var j = 0; j < info2.ext.length; j++) + if (info2.ext[j] == ext) return info2; + } + } + }; + CodeMirror.findModeByFileName = function(filename) { + for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) { + var info2 = CodeMirror.modeInfo[i2]; + if (info2.file && info2.file.test(filename)) return info2; + } + var dot = filename.lastIndexOf("."); + var ext = dot > -1 && filename.substring(dot + 1, filename.length); + if (ext) return CodeMirror.findModeByExtension(ext); + }; + CodeMirror.findModeByName = function(name) { + name = name.toLowerCase(); + for (var i2 = 0; i2 < CodeMirror.modeInfo.length; i2++) { + var info2 = CodeMirror.modeInfo[i2]; + if (info2.name.toLowerCase() == name) return info2; + if (info2.alias) { + for (var j = 0; j < info2.alias.length; j++) + if (info2.alias[j].toLowerCase() == name) return info2; + } + } + }; + }); + })(); + return meta.exports; +} +var hasRequiredMarkdown; +function requireMarkdown() { + if (hasRequiredMarkdown) return markdown.exports; + hasRequiredMarkdown = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror(), requireXml(), requireMeta()); + })(function(CodeMirror) { + CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { + var htmlMode = CodeMirror.getMode(cmCfg, "text/html"); + var htmlModeMissing = htmlMode.name == "null"; + function getMode(name) { + if (CodeMirror.findModeByName) { + var found = CodeMirror.findModeByName(name); + if (found) name = found.mime || found.mimes[0]; + } + var mode2 = CodeMirror.getMode(cmCfg, name); + return mode2.name == "null" ? null : mode2; + } + if (modeCfg.highlightFormatting === void 0) + modeCfg.highlightFormatting = false; + if (modeCfg.maxBlockquoteDepth === void 0) + modeCfg.maxBlockquoteDepth = 0; + if (modeCfg.taskLists === void 0) modeCfg.taskLists = false; + if (modeCfg.strikethrough === void 0) + modeCfg.strikethrough = false; + if (modeCfg.emoji === void 0) + modeCfg.emoji = false; + if (modeCfg.fencedCodeBlockHighlighting === void 0) + modeCfg.fencedCodeBlockHighlighting = true; + if (modeCfg.fencedCodeBlockDefaultMode === void 0) + modeCfg.fencedCodeBlockDefaultMode = "text/plain"; + if (modeCfg.xml === void 0) + modeCfg.xml = true; + if (modeCfg.tokenTypeOverrides === void 0) + modeCfg.tokenTypeOverrides = {}; + var tokenTypes = { + header: "header", + code: "comment", + quote: "quote", + list1: "variable-2", + list2: "variable-3", + list3: "keyword", + hr: "hr", + image: "image", + imageAltText: "image-alt-text", + imageMarker: "image-marker", + formatting: "formatting", + linkInline: "link", + linkEmail: "link", + linkText: "link", + linkHref: "string", + em: "em", + strong: "strong", + strikethrough: "strikethrough", + emoji: "builtin" + }; + for (var tokenType in tokenTypes) { + if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) { + tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType]; + } + } + var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/, listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/, taskListRE = /^\[(x| )\](?=\s)/i, atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/, setextHeaderRE = /^ {0,3}(?:\={1,}|-{2,})\s*$/, textRE = /^[^#!\[\]*_\\<>` "'(~:]+/, fencedCodeRE = /^(~~~+|```+)[ \t]*([\w\/+#-]*)[^\n`]*$/, linkDefRE = /^\s*\[[^\]]+?\]:.*$/, punctuation = /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/, expandedTab = " "; + function switchInline(stream, state, f) { + state.f = state.inline = f; + return f(stream, state); + } + function switchBlock(stream, state, f) { + state.f = state.block = f; + return f(stream, state); + } + function lineIsEmpty(line) { + return !line || !/\S/.test(line.string); + } + function blankLine(state) { + state.linkTitle = false; + state.linkHref = false; + state.linkText = false; + state.em = false; + state.strong = false; + state.strikethrough = false; + state.quote = 0; + state.indentedCode = false; + if (state.f == htmlBlock) { + var exit = htmlModeMissing; + if (!exit) { + var inner = CodeMirror.innerMode(htmlMode, state.htmlState); + exit = inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText); + } + if (exit) { + state.f = inlineNormal; + state.block = blockNormal; + state.htmlState = null; + } + } + state.trailingSpace = 0; + state.trailingSpaceNewLine = false; + state.prevLine = state.thisLine; + state.thisLine = { stream: null }; + return null; + } + function blockNormal(stream, state) { + var firstTokenOnLine = stream.column() === state.indentation; + var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream); + var prevLineIsIndentedCode = state.indentedCode; + var prevLineIsHr = state.prevLine.hr; + var prevLineIsList = state.list !== false; + var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3; + state.indentedCode = false; + var lineIndentation = state.indentation; + if (state.indentationDiff === null) { + state.indentationDiff = state.indentation; + if (prevLineIsList) { + state.list = null; + while (lineIndentation < state.listStack[state.listStack.length - 1]) { + state.listStack.pop(); + if (state.listStack.length) { + state.indentation = state.listStack[state.listStack.length - 1]; + } else { + state.list = false; + } + } + if (state.list !== false) { + state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]; + } + } + } + var allowsInlineContinuation = !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header && (!prevLineIsList || !prevLineIsIndentedCode) && !state.prevLine.fencedCodeEnd; + var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) && state.indentation <= maxNonCodeIndentation && stream.match(hrRE); + var match = null; + if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd || state.prevLine.header || prevLineLineIsEmpty)) { + stream.skipToEnd(); + state.indentedCode = true; + return tokenTypes.code; + } else if (stream.eatSpace()) { + return null; + } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) { + state.quote = 0; + state.header = match[1].length; + state.thisLine.header = true; + if (modeCfg.highlightFormatting) state.formatting = "header"; + state.f = state.inline; + return getType(state); + } else if (state.indentation <= maxNonCodeIndentation && stream.eat(">")) { + state.quote = firstTokenOnLine ? 1 : state.quote + 1; + if (modeCfg.highlightFormatting) state.formatting = "quote"; + stream.eatSpace(); + return getType(state); + } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) { + var listType = match[1] ? "ol" : "ul"; + state.indentation = lineIndentation + stream.current().length; + state.list = true; + state.quote = 0; + state.listStack.push(state.indentation); + state.em = false; + state.strong = false; + state.code = false; + state.strikethrough = false; + if (modeCfg.taskLists && stream.match(taskListRE, false)) { + state.taskList = true; + } + state.f = state.inline; + if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType]; + return getType(state); + } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) { + state.quote = 0; + state.fencedEndRE = new RegExp(match[1] + "+ *$"); + state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2] || modeCfg.fencedCodeBlockDefaultMode); + if (state.localMode) state.localState = CodeMirror.startState(state.localMode); + state.f = state.block = local; + if (modeCfg.highlightFormatting) state.formatting = "code-block"; + state.code = -1; + return getType(state); + } else if ( + // if setext set, indicates line after ---/=== + state.setext || // line before ---/=== + (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false && !state.code && !isHr && !linkDefRE.test(stream.string) && (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE)) + ) { + if (!state.setext) { + state.header = match[0].charAt(0) == "=" ? 1 : 2; + state.setext = state.header; + } else { + state.header = state.setext; + state.setext = 0; + stream.skipToEnd(); + if (modeCfg.highlightFormatting) state.formatting = "header"; + } + state.thisLine.header = true; + state.f = state.inline; + return getType(state); + } else if (isHr) { + stream.skipToEnd(); + state.hr = true; + state.thisLine.hr = true; + return tokenTypes.hr; + } else if (stream.peek() === "[") { + return switchInline(stream, state, footnoteLink); + } + return switchInline(stream, state, state.inline); + } + function htmlBlock(stream, state) { + var style = htmlMode.token(stream, state.htmlState); + if (!htmlModeMissing) { + var inner = CodeMirror.innerMode(htmlMode, state.htmlState); + if (inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText) || state.md_inside && stream.current().indexOf(">") > -1) { + state.f = inlineNormal; + state.block = blockNormal; + state.htmlState = null; + } + } + return style; + } + function local(stream, state) { + var currListInd = state.listStack[state.listStack.length - 1] || 0; + var hasExitedList = state.indentation < currListInd; + var maxFencedEndInd = currListInd + 3; + if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) { + if (modeCfg.highlightFormatting) state.formatting = "code-block"; + var returnType; + if (!hasExitedList) returnType = getType(state); + state.localMode = state.localState = null; + state.block = blockNormal; + state.f = inlineNormal; + state.fencedEndRE = null; + state.code = 0; + state.thisLine.fencedCodeEnd = true; + if (hasExitedList) return switchBlock(stream, state, state.block); + return returnType; + } else if (state.localMode) { + return state.localMode.token(stream, state.localState); + } else { + stream.skipToEnd(); + return tokenTypes.code; + } + } + function getType(state) { + var styles = []; + if (state.formatting) { + styles.push(tokenTypes.formatting); + if (typeof state.formatting === "string") state.formatting = [state.formatting]; + for (var i = 0; i < state.formatting.length; i++) { + styles.push(tokenTypes.formatting + "-" + state.formatting[i]); + if (state.formatting[i] === "header") { + styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header); + } + if (state.formatting[i] === "quote") { + if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { + styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote); + } else { + styles.push("error"); + } + } + } + } + if (state.taskOpen) { + styles.push("meta"); + return styles.length ? styles.join(" ") : null; + } + if (state.taskClosed) { + styles.push("property"); + return styles.length ? styles.join(" ") : null; + } + if (state.linkHref) { + styles.push(tokenTypes.linkHref, "url"); + } else { + if (state.strong) { + styles.push(tokenTypes.strong); + } + if (state.em) { + styles.push(tokenTypes.em); + } + if (state.strikethrough) { + styles.push(tokenTypes.strikethrough); + } + if (state.emoji) { + styles.push(tokenTypes.emoji); + } + if (state.linkText) { + styles.push(tokenTypes.linkText); + } + if (state.code) { + styles.push(tokenTypes.code); + } + if (state.image) { + styles.push(tokenTypes.image); + } + if (state.imageAltText) { + styles.push(tokenTypes.imageAltText, "link"); + } + if (state.imageMarker) { + styles.push(tokenTypes.imageMarker); + } + } + if (state.header) { + styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); + } + if (state.quote) { + styles.push(tokenTypes.quote); + if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { + styles.push(tokenTypes.quote + "-" + state.quote); + } else { + styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth); + } + } + if (state.list !== false) { + var listMod = (state.listStack.length - 1) % 3; + if (!listMod) { + styles.push(tokenTypes.list1); + } else if (listMod === 1) { + styles.push(tokenTypes.list2); + } else { + styles.push(tokenTypes.list3); + } + } + if (state.trailingSpaceNewLine) { + styles.push("trailing-space-new-line"); + } else if (state.trailingSpace) { + styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); + } + return styles.length ? styles.join(" ") : null; + } + function handleText(stream, state) { + if (stream.match(textRE, true)) { + return getType(state); + } + return void 0; + } + function inlineNormal(stream, state) { + var style = state.text(stream, state); + if (typeof style !== "undefined") + return style; + if (state.list) { + state.list = null; + return getType(state); + } + if (state.taskList) { + var taskOpen = stream.match(taskListRE, true)[1] === " "; + if (taskOpen) state.taskOpen = true; + else state.taskClosed = true; + if (modeCfg.highlightFormatting) state.formatting = "task"; + state.taskList = false; + return getType(state); + } + state.taskOpen = false; + state.taskClosed = false; + if (state.header && stream.match(/^#+$/, true)) { + if (modeCfg.highlightFormatting) state.formatting = "header"; + return getType(state); + } + var ch = stream.next(); + if (state.linkTitle) { + state.linkTitle = false; + var matchCh = ch; + if (ch === "(") { + matchCh = ")"; + } + matchCh = (matchCh + "").replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1"); + var regex = "^\\s*(?:[^" + matchCh + "\\\\]+|\\\\\\\\|\\\\.)" + matchCh; + if (stream.match(new RegExp(regex), true)) { + return tokenTypes.linkHref; + } + } + if (ch === "`") { + var previousFormatting = state.formatting; + if (modeCfg.highlightFormatting) state.formatting = "code"; + stream.eatWhile("`"); + var count = stream.current().length; + if (state.code == 0 && (!state.quote || count == 1)) { + state.code = count; + return getType(state); + } else if (count == state.code) { + var t = getType(state); + state.code = 0; + return t; + } else { + state.formatting = previousFormatting; + return getType(state); + } + } else if (state.code) { + return getType(state); + } + if (ch === "\\") { + stream.next(); + if (modeCfg.highlightFormatting) { + var type = getType(state); + var formattingEscape = tokenTypes.formatting + "-escape"; + return type ? type + " " + formattingEscape : formattingEscape; + } + } + if (ch === "!" && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { + state.imageMarker = true; + state.image = true; + if (modeCfg.highlightFormatting) state.formatting = "image"; + return getType(state); + } + if (ch === "[" && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) { + state.imageMarker = false; + state.imageAltText = true; + if (modeCfg.highlightFormatting) state.formatting = "image"; + return getType(state); + } + if (ch === "]" && state.imageAltText) { + if (modeCfg.highlightFormatting) state.formatting = "image"; + var type = getType(state); + state.imageAltText = false; + state.image = false; + state.inline = state.f = linkHref; + return type; + } + if (ch === "[" && !state.image) { + if (state.linkText && stream.match(/^.*?\]/)) return getType(state); + state.linkText = true; + if (modeCfg.highlightFormatting) state.formatting = "link"; + return getType(state); + } + if (ch === "]" && state.linkText) { + if (modeCfg.highlightFormatting) state.formatting = "link"; + var type = getType(state); + state.linkText = false; + state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal; + return type; + } + if (ch === "<" && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { + state.f = state.inline = linkInline; + if (modeCfg.highlightFormatting) state.formatting = "link"; + var type = getType(state); + if (type) { + type += " "; + } else { + type = ""; + } + return type + tokenTypes.linkInline; + } + if (ch === "<" && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { + state.f = state.inline = linkInline; + if (modeCfg.highlightFormatting) state.formatting = "link"; + var type = getType(state); + if (type) { + type += " "; + } else { + type = ""; + } + return type + tokenTypes.linkEmail; + } + if (modeCfg.xml && ch === "<" && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) { + var end = stream.string.indexOf(">", stream.pos); + if (end != -1) { + var atts = stream.string.substring(stream.start, end); + if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true; + } + stream.backUp(1); + state.htmlState = CodeMirror.startState(htmlMode); + return switchBlock(stream, state, htmlBlock); + } + if (modeCfg.xml && ch === "<" && stream.match(/^\/\w*?>/)) { + state.md_inside = false; + return "tag"; + } else if (ch === "*" || ch === "_") { + var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2); + while (len < 3 && stream.eat(ch)) len++; + var after = stream.peek() || " "; + var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before)); + var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after)); + var setEm = null, setStrong = null; + if (len % 2) { + if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before))) + setEm = true; + else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after))) + setEm = false; + } + if (len > 1) { + if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before))) + setStrong = true; + else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after))) + setStrong = false; + } + if (setStrong != null || setEm != null) { + if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em"; + if (setEm === true) state.em = ch; + if (setStrong === true) state.strong = ch; + var t = getType(state); + if (setEm === false) state.em = false; + if (setStrong === false) state.strong = false; + return t; + } + } else if (ch === " ") { + if (stream.eat("*") || stream.eat("_")) { + if (stream.peek() === " ") { + return getType(state); + } else { + stream.backUp(1); + } + } + } + if (modeCfg.strikethrough) { + if (ch === "~" && stream.eatWhile(ch)) { + if (state.strikethrough) { + if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; + var t = getType(state); + state.strikethrough = false; + return t; + } else if (stream.match(/^[^\s]/, false)) { + state.strikethrough = true; + if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; + return getType(state); + } + } else if (ch === " ") { + if (stream.match("~~", true)) { + if (stream.peek() === " ") { + return getType(state); + } else { + stream.backUp(2); + } + } + } + } + if (modeCfg.emoji && ch === ":" && stream.match(/^(?:[a-z_\d+][a-z_\d+-]*|\-[a-z_\d+][a-z_\d+-]*):/)) { + state.emoji = true; + if (modeCfg.highlightFormatting) state.formatting = "emoji"; + var retType = getType(state); + state.emoji = false; + return retType; + } + if (ch === " ") { + if (stream.match(/^ +$/, false)) { + state.trailingSpace++; + } else if (state.trailingSpace) { + state.trailingSpaceNewLine = true; + } + } + return getType(state); + } + function linkInline(stream, state) { + var ch = stream.next(); + if (ch === ">") { + state.f = state.inline = inlineNormal; + if (modeCfg.highlightFormatting) state.formatting = "link"; + var type = getType(state); + if (type) { + type += " "; + } else { + type = ""; + } + return type + tokenTypes.linkInline; + } + stream.match(/^[^>]+/, true); + return tokenTypes.linkInline; + } + function linkHref(stream, state) { + if (stream.eatSpace()) { + return null; + } + var ch = stream.next(); + if (ch === "(" || ch === "[") { + state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]"); + if (modeCfg.highlightFormatting) state.formatting = "link-string"; + state.linkHref = true; + return getType(state); + } + return "error"; + } + var linkRE = { + ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/, + "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/ + }; + function getLinkHrefInside(endChar) { + return function(stream, state) { + var ch = stream.next(); + if (ch === endChar) { + state.f = state.inline = inlineNormal; + if (modeCfg.highlightFormatting) state.formatting = "link-string"; + var returnState = getType(state); + state.linkHref = false; + return returnState; + } + stream.match(linkRE[endChar]); + state.linkHref = true; + return getType(state); + }; + } + function footnoteLink(stream, state) { + if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) { + state.f = footnoteLinkInside; + stream.next(); + if (modeCfg.highlightFormatting) state.formatting = "link"; + state.linkText = true; + return getType(state); + } + return switchInline(stream, state, inlineNormal); + } + function footnoteLinkInside(stream, state) { + if (stream.match("]:", true)) { + state.f = state.inline = footnoteUrl; + if (modeCfg.highlightFormatting) state.formatting = "link"; + var returnType = getType(state); + state.linkText = false; + return returnType; + } + stream.match(/^([^\]\\]|\\.)+/, true); + return tokenTypes.linkText; + } + function footnoteUrl(stream, state) { + if (stream.eatSpace()) { + return null; + } + stream.match(/^[^\s]+/, true); + if (stream.peek() === void 0) { + state.linkTitle = true; + } else { + stream.match(/^(?:\s+(?:"(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+'|\((?:[^)\\]|\\.)+\)))?/, true); + } + state.f = state.inline = inlineNormal; + return tokenTypes.linkHref + " url"; + } + var mode = { + startState: function() { + return { + f: blockNormal, + prevLine: { stream: null }, + thisLine: { stream: null }, + block: blockNormal, + htmlState: null, + indentation: 0, + inline: inlineNormal, + text: handleText, + formatting: false, + linkText: false, + linkHref: false, + linkTitle: false, + code: 0, + em: false, + strong: false, + header: 0, + setext: 0, + hr: false, + taskList: false, + list: false, + listStack: [], + quote: 0, + trailingSpace: 0, + trailingSpaceNewLine: false, + strikethrough: false, + emoji: false, + fencedEndRE: null + }; + }, + copyState: function(s) { + return { + f: s.f, + prevLine: s.prevLine, + thisLine: s.thisLine, + block: s.block, + htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState), + indentation: s.indentation, + localMode: s.localMode, + localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, + inline: s.inline, + text: s.text, + formatting: false, + linkText: s.linkText, + linkTitle: s.linkTitle, + linkHref: s.linkHref, + code: s.code, + em: s.em, + strong: s.strong, + strikethrough: s.strikethrough, + emoji: s.emoji, + header: s.header, + setext: s.setext, + hr: s.hr, + taskList: s.taskList, + list: s.list, + listStack: s.listStack.slice(0), + quote: s.quote, + indentedCode: s.indentedCode, + trailingSpace: s.trailingSpace, + trailingSpaceNewLine: s.trailingSpaceNewLine, + md_inside: s.md_inside, + fencedEndRE: s.fencedEndRE + }; + }, + token: function(stream, state) { + state.formatting = false; + if (stream != state.thisLine.stream) { + state.header = 0; + state.hr = false; + if (stream.match(/^\s*$/, true)) { + blankLine(state); + return null; + } + state.prevLine = state.thisLine; + state.thisLine = { stream }; + state.taskList = false; + state.trailingSpace = 0; + state.trailingSpaceNewLine = false; + if (!state.localState) { + state.f = state.block; + if (state.f != htmlBlock) { + var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length; + state.indentation = indentation; + state.indentationDiff = null; + if (indentation > 0) return null; + } + } + } + return state.f(stream, state); + }, + innerMode: function(state) { + if (state.block == htmlBlock) return { state: state.htmlState, mode: htmlMode }; + if (state.localState) return { state: state.localState, mode: state.localMode }; + return { state, mode }; + }, + indent: function(state, textAfter, line) { + if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line); + if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line); + return CodeMirror.Pass; + }, + blankLine, + getType, + blockCommentStart: "", + closeBrackets: "()[]{}''\"\"``", + fold: "markdown" + }; + return mode; + }, "xml"); + CodeMirror.defineMIME("text/markdown", "markdown"); + CodeMirror.defineMIME("text/x-markdown", "markdown"); + }); + })(); + return markdown.exports; +} +requireMarkdown(); +var placeholder = { exports: {} }; +var hasRequiredPlaceholder; +function requirePlaceholder() { + if (hasRequiredPlaceholder) return placeholder.exports; + hasRequiredPlaceholder = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + CodeMirror.defineOption("placeholder", "", function(cm, val, old) { + var prev = old && old != CodeMirror.Init; + if (val && !prev) { + cm.on("blur", onBlur); + cm.on("change", onChange); + cm.on("swapDoc", onChange); + CodeMirror.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function() { + onComposition(cm); + }); + onChange(cm); + } else if (!val && prev) { + cm.off("blur", onBlur); + cm.off("change", onChange); + cm.off("swapDoc", onChange); + CodeMirror.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose); + clearPlaceholder(cm); + var wrapper = cm.getWrapperElement(); + wrapper.className = wrapper.className.replace(" CodeMirror-empty", ""); + } + if (val && !cm.hasFocus()) onBlur(cm); + }); + function clearPlaceholder(cm) { + if (cm.state.placeholder) { + cm.state.placeholder.parentNode.removeChild(cm.state.placeholder); + cm.state.placeholder = null; + } + } + function setPlaceholder(cm) { + clearPlaceholder(cm); + var elt = cm.state.placeholder = document.createElement("pre"); + elt.style.cssText = "height: 0; overflow: visible"; + elt.style.direction = cm.getOption("direction"); + elt.className = "CodeMirror-placeholder CodeMirror-line-like"; + var placeHolder = cm.getOption("placeholder"); + if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder); + elt.appendChild(placeHolder); + cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild); + } + function onComposition(cm) { + setTimeout(function() { + var empty = false; + if (cm.lineCount() == 1) { + var input = cm.getInputField(); + empty = input.nodeName == "TEXTAREA" ? !cm.getLine(0).length : !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent); + } + if (empty) setPlaceholder(cm); + else clearPlaceholder(cm); + }, 20); + } + function onBlur(cm) { + if (isEmpty(cm)) setPlaceholder(cm); + } + function onChange(cm) { + var wrapper = cm.getWrapperElement(), empty = isEmpty(cm); + wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : ""); + if (empty) setPlaceholder(cm); + else clearPlaceholder(cm); + } + function isEmpty(cm) { + return cm.lineCount() === 1 && cm.getLine(0) === ""; + } + }); + })(); + return placeholder.exports; +} +requirePlaceholder(); +var simple = { exports: {} }; +var hasRequiredSimple; +function requireSimple() { + if (hasRequiredSimple) return simple.exports; + hasRequiredSimple = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + CodeMirror.defineSimpleMode = function(name, states) { + CodeMirror.defineMode(name, function(config) { + return CodeMirror.simpleMode(config, states); + }); + }; + CodeMirror.simpleMode = function(config, states) { + ensureState(states, "start"); + var states_ = {}, meta2 = states.meta || {}, hasIndentation = false; + for (var state in states) if (state != meta2 && states.hasOwnProperty(state)) { + var list = states_[state] = [], orig = states[state]; + for (var i = 0; i < orig.length; i++) { + var data = orig[i]; + list.push(new Rule(data, states)); + if (data.indent || data.dedent) hasIndentation = true; + } + } + var mode = { + startState: function() { + return { + state: "start", + pending: null, + local: null, + localState: null, + indent: hasIndentation ? [] : null + }; + }, + copyState: function(state2) { + var s = { + state: state2.state, + pending: state2.pending, + local: state2.local, + localState: null, + indent: state2.indent && state2.indent.slice(0) + }; + if (state2.localState) + s.localState = CodeMirror.copyState(state2.local.mode, state2.localState); + if (state2.stack) + s.stack = state2.stack.slice(0); + for (var pers = state2.persistentStates; pers; pers = pers.next) + s.persistentStates = { + mode: pers.mode, + spec: pers.spec, + state: pers.state == state2.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state), + next: s.persistentStates + }; + return s; + }, + token: tokenFunction(states_, config), + innerMode: function(state2) { + return state2.local && { mode: state2.local.mode, state: state2.localState }; + }, + indent: indentFunction(states_, meta2) + }; + if (meta2) { + for (var prop in meta2) if (meta2.hasOwnProperty(prop)) + mode[prop] = meta2[prop]; + } + return mode; + }; + function ensureState(states, name) { + if (!states.hasOwnProperty(name)) + throw new Error("Undefined state " + name + " in simple mode"); + } + function toRegex(val, caret) { + if (!val) return /(?:)/; + var flags = ""; + if (val instanceof RegExp) { + if (val.ignoreCase) flags = "i"; + if (val.unicode) flags += "u"; + val = val.source; + } else { + val = String(val); + } + return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags); + } + function asToken(val) { + if (!val) return null; + if (val.apply) return val; + if (typeof val == "string") return val.replace(/\./g, " "); + var result = []; + for (var i = 0; i < val.length; i++) + result.push(val[i] && val[i].replace(/\./g, " ")); + return result; + } + function Rule(data, states) { + if (data.next || data.push) ensureState(states, data.next || data.push); + this.regex = toRegex(data.regex); + this.token = asToken(data.token); + this.data = data; + } + function tokenFunction(states, config) { + return function(stream, state) { + if (state.pending) { + var pend = state.pending.shift(); + if (state.pending.length == 0) state.pending = null; + stream.pos += pend.text.length; + return pend.token; + } + if (state.local) { + if (state.local.end && stream.match(state.local.end)) { + var tok = state.local.endToken || null; + state.local = state.localState = null; + return tok; + } else { + var tok = state.local.mode.token(stream, state.localState), m; + if (state.local.endScan && (m = state.local.endScan.exec(stream.current()))) + stream.pos = stream.start + m.index; + return tok; + } + } + var curState = states[state.state]; + for (var i = 0; i < curState.length; i++) { + var rule = curState[i]; + var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex); + if (matches) { + if (rule.data.next) { + state.state = rule.data.next; + } else if (rule.data.push) { + (state.stack || (state.stack = [])).push(state.state); + state.state = rule.data.push; + } else if (rule.data.pop && state.stack && state.stack.length) { + state.state = state.stack.pop(); + } + if (rule.data.mode) + enterLocalMode(config, state, rule.data.mode, rule.token); + if (rule.data.indent) + state.indent.push(stream.indentation() + config.indentUnit); + if (rule.data.dedent) + state.indent.pop(); + var token = rule.token; + if (token && token.apply) token = token(matches); + if (matches.length > 2 && rule.token && typeof rule.token != "string") { + for (var j = 2; j < matches.length; j++) + if (matches[j]) + (state.pending || (state.pending = [])).push({ text: matches[j], token: rule.token[j - 1] }); + stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0)); + return token[0]; + } else if (token && token.join) { + return token[0]; + } else { + return token; + } + } + } + stream.next(); + return null; + }; + } + function cmp(a, b) { + if (a === b) return true; + if (!a || typeof a != "object" || !b || typeof b != "object") return false; + var props = 0; + for (var prop in a) if (a.hasOwnProperty(prop)) { + if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false; + props++; + } + for (var prop in b) if (b.hasOwnProperty(prop)) props--; + return props == 0; + } + function enterLocalMode(config, state, spec, token) { + var pers; + if (spec.persistent) { + for (var p = state.persistentStates; p && !pers; p = p.next) + if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p; + } + var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec); + var lState = pers ? pers.state : CodeMirror.startState(mode); + if (spec.persistent && !pers) + state.persistentStates = { mode, spec: spec.spec, state: lState, next: state.persistentStates }; + state.localState = lState; + state.local = { + mode, + end: spec.end && toRegex(spec.end), + endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false), + endToken: token && token.join ? token[token.length - 1] : token + }; + } + function indexOf(val, arr) { + for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true; + } + function indentFunction(states, meta2) { + return function(state, textAfter, line) { + if (state.local && state.local.mode.indent) + return state.local.mode.indent(state.localState, textAfter, line); + if (state.indent == null || state.local || meta2.dontIndentStates && indexOf(state.state, meta2.dontIndentStates) > -1) + return CodeMirror.Pass; + var pos = state.indent.length - 1, rules = states[state.state]; + scan: for (; ; ) { + for (var i = 0; i < rules.length; i++) { + var rule = rules[i]; + if (rule.data.dedent && rule.data.dedentIfLineStart !== false) { + var m = rule.regex.exec(textAfter); + if (m && m[0]) { + pos--; + if (rule.next || rule.push) rules = states[rule.next || rule.push]; + textAfter = textAfter.slice(m[0].length); + continue scan; + } + } + } + break; + } + return pos < 0 ? 0 : state.indent[pos]; + }; + } + }); + })(); + return simple.exports; +} +requireSimple(); +var yaml = { exports: {} }; +var hasRequiredYaml; +function requireYaml() { + if (hasRequiredYaml) return yaml.exports; + hasRequiredYaml = 1; + (function(module, exports) { + (function(mod) { + mod(requireCodemirror()); + })(function(CodeMirror) { + CodeMirror.defineMode("yaml", function() { + var cons = ["true", "false", "on", "off", "yes", "no"]; + var keywordRegex = new RegExp("\\b((" + cons.join(")|(") + "))$", "i"); + return { + token: function(stream, state) { + var ch = stream.peek(); + var esc = state.escaped; + state.escaped = false; + if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) { + stream.skipToEnd(); + return "comment"; + } + if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/)) + return "string"; + if (state.literal && stream.indentation() > state.keyCol) { + stream.skipToEnd(); + return "string"; + } else if (state.literal) { + state.literal = false; + } + if (stream.sol()) { + state.keyCol = 0; + state.pair = false; + state.pairStart = false; + if (stream.match("---")) { + return "def"; + } + if (stream.match("...")) { + return "def"; + } + if (stream.match(/\s*-\s+/)) { + return "meta"; + } + } + if (stream.match(/^(\{|\}|\[|\])/)) { + if (ch == "{") + state.inlinePairs++; + else if (ch == "}") + state.inlinePairs--; + else if (ch == "[") + state.inlineList++; + else + state.inlineList--; + return "meta"; + } + if (state.inlineList > 0 && !esc && ch == ",") { + stream.next(); + return "meta"; + } + if (state.inlinePairs > 0 && !esc && ch == ",") { + state.keyCol = 0; + state.pair = false; + state.pairStart = false; + stream.next(); + return "meta"; + } + if (state.pairStart) { + if (stream.match(/^\s*(\||\>)\s*/)) { + state.literal = true; + return "meta"; + } + if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { + return "variable-2"; + } + if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { + return "number"; + } + if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { + return "number"; + } + if (stream.match(keywordRegex)) { + return "keyword"; + } + } + if (!state.pair && stream.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^\s,\[\]{}#&*!|>'"%@`])[^#:]*(?=:($|\s))/)) { + state.pair = true; + state.keyCol = stream.indentation(); + return "atom"; + } + if (state.pair && stream.match(/^:\s*/)) { + state.pairStart = true; + return "meta"; + } + state.pairStart = false; + state.escaped = ch == "\\"; + stream.next(); + return null; + }, + startState: function() { + return { + pair: false, + pairStart: false, + keyCol: 0, + inlinePairs: 0, + inlineList: 0, + literal: false, + escaped: false + }; + }, + lineComment: "#", + fold: "indent" + }; + }); + CodeMirror.defineMIME("text/x-yaml", "yaml"); + CodeMirror.defineMIME("text/yaml", "yaml"); + }); + })(); + return yaml.exports; +} +requireYaml(); +export { + codemirror as default +}; diff --git a/extension/edge-share-crx/codicon.ttf b/extension/edge-share-crx/codicon.ttf new file mode 100644 index 0000000..27ee4c6 Binary files /dev/null and b/extension/edge-share-crx/codicon.ttf differ diff --git a/extension/edge-share-crx/connect.html b/extension/edge-share-crx/connect.html new file mode 100644 index 0000000..0582858 --- /dev/null +++ b/extension/edge-share-crx/connect.html @@ -0,0 +1,149 @@ + + + + + Connect Edge + + + +
+

Connect this Edge

+
+
+ Platform + - +
+
+ Workspace + - +
+
+ Relay + - +
+
+
+ + +
+
Loading request
+
+ + + diff --git a/extension/edge-share-crx/connect.js b/extension/edge-share-crx/connect.js new file mode 100644 index 0000000..05a5e64 --- /dev/null +++ b/extension/edge-share-crx/connect.js @@ -0,0 +1,95 @@ +"use strict"; + +const params = new URLSearchParams(window.location.search); +const requestId = params.get("requestId") || ""; + +const originEl = document.getElementById("origin"); +const workspaceEl = document.getElementById("workspace"); +const relayEl = document.getElementById("relay"); +const statusEl = document.getElementById("status"); +const approveButton = document.getElementById("approveButton"); +const rejectButton = document.getElementById("rejectButton"); + +let request = null; + +document.addEventListener("DOMContentLoaded", () => { + approveButton.addEventListener("click", approve); + rejectButton.addEventListener("click", reject); + loadRequest().catch(showError); +}); + +async function loadRequest() { + if (!requestId) { + throw new Error("Missing request id"); + } + + request = await sendMessage({ + type: "get_platform_connect_request", + requestId + }); + + originEl.textContent = request.origin || "-"; + workspaceEl.textContent = request.workspaceId || request.poolId || "current-runtime"; + relayEl.textContent = request.relayUrl || "-"; + statusEl.textContent = "Allow this page to control this Edge session through the relay."; +} + +async function approve() { + setBusy(true); + statusEl.classList.remove("error"); + statusEl.textContent = "Connecting"; + + try { + const result = await sendMessage({ + type: "approve_platform_connect", + requestId + }); + statusEl.textContent = result.connected + ? "Connected" + : "Share session created. Waiting for relay connection."; + setTimeout(() => window.close(), 900); + } catch (error) { + showError(error); + setBusy(false); + } +} + +async function reject() { + setBusy(true); + + try { + await sendMessage({ + type: "reject_platform_connect", + requestId + }); + } finally { + window.close(); + } +} + +function setBusy(busy) { + approveButton.disabled = busy; + rejectButton.disabled = busy; +} + +function sendMessage(message) { + return new Promise((resolve, reject) => { + chrome.runtime.sendMessage(message, (response) => { + const runtimeError = chrome.runtime.lastError; + if (runtimeError) { + reject(new Error(runtimeError.message)); + return; + } + if (!response || response.ok !== true) { + reject(new Error((response && response.error) || "Extension message failed")); + return; + } + resolve(response.result); + }); + }); +} + +function showError(error) { + statusEl.textContent = error.message || String(error); + statusEl.classList.add("error"); +} diff --git a/extension/edge-share-crx/edge_share_content.js b/extension/edge-share-crx/edge_share_content.js new file mode 100644 index 0000000..5f14ad2 --- /dev/null +++ b/extension/edge-share-crx/edge_share_content.js @@ -0,0 +1,66 @@ +"use strict"; + +const SOURCE_PAGE = "browser-connection:page"; +const SOURCE_CONTENT = "browser-connection:content"; + +injectProvider(); + +window.addEventListener("message", (event) => { + if (event.source !== window || event.origin !== window.location.origin) { + return; + } + const message = event.data; + if (!message || message.source !== SOURCE_PAGE || !message.id) { + return; + } + + chrome.runtime.sendMessage( + { + type: "platform_request", + id: message.id, + method: message.method, + params: message.params || {}, + origin: window.location.origin, + href: window.location.href, + title: document.title || "" + }, + (response) => { + const runtimeError = chrome.runtime.lastError; + if (runtimeError) { + postResponse(message.id, false, null, runtimeError.message); + return; + } + if (!response || response.ok !== true) { + postResponse( + message.id, + false, + null, + (response && response.error) || "Extension request failed" + ); + return; + } + postResponse(message.id, true, response.result, ""); + } + ); +}); + +function injectProvider() { + const script = document.createElement("script"); + script.src = chrome.runtime.getURL("provider.js"); + script.async = false; + script.onload = () => script.remove(); + (document.documentElement || document.head || document.body).appendChild(script); +} + +function postResponse(id, ok, result, error) { + window.postMessage( + { + source: SOURCE_CONTENT, + id, + ok, + result, + error + }, + window.location.origin + ); +} diff --git a/extension/edge-share-crx/edge_share_relay.js b/extension/edge-share-crx/edge_share_relay.js new file mode 100644 index 0000000..fde858b --- /dev/null +++ b/extension/edge-share-crx/edge_share_relay.js @@ -0,0 +1,1889 @@ +"use strict"; + +const PROTOCOL_VERSION = 1; +const DEFAULT_RELAY_URL = "http://127.0.0.1:8765"; +const STORAGE_KEY = "edgeShareState"; +const RECONNECT_MIN_MS = 1000; +const RECONNECT_MAX_MS = 30000; +const RECONNECT_ALARM_NAME = "edge-share-reconnect"; +const RELAY_KEEPALIVE_MS = 20 * 1000; +const PLATFORM_CONNECT_TTL_MS = 2 * 60 * 1000; +const PLATFORM_RELAY_CONNECT_TIMEOUT_MS = 8000; +const MAX_RECORDED_ACTIONS = 500; + +let state = { + sharing: false, + connected: false, + relayUrl: DEFAULT_RELAY_URL, + sessionId: "", + browserToken: "", + agentToken: "", + shareUrl: "", + status: "idle", + lastError: "", + activeTabId: null, + platformOrigin: "", + platformHref: "", + workspaceId: "", + poolId: "", + browserName: "", + recording: false, + recordingTabId: null, + recorderMode: "record", + recordingStartedAt: "", + recordingStoppedAt: "", + recordedActions: [], + lastInspect: null, + playbackRunning: false, + playbackError: "", + playbackStepId: "", + updatedAt: "" +}; + +let socket = null; +let reconnectTimer = null; +let keepAliveTimer = null; +let reconnectDelayMs = RECONNECT_MIN_MS; +let intentionallyClosed = false; +const attachedTabs = new Set(); +const pendingPlatformRequests = new Map(); +let crxRecorderState = { + mode: "none", + sources: [] +}; + +chrome.runtime.onInstalled.addListener(() => { + restoreState().then(connectIfNeeded).catch(reportError); +}); + +chrome.runtime.onStartup.addListener(() => { + restoreState().then(connectIfNeeded).catch(reportError); +}); + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + handleExtensionMessage(message, sender) + .then((result) => sendResponse({ ok: true, result })) + .catch((error) => sendResponse({ ok: false, error: errorMessage(error) })); + return true; +}); + +chrome.debugger.onDetach.addListener((source) => { + if (Number.isInteger(source.tabId)) { + attachedTabs.delete(source.tabId); + } +}); + +if (chrome.alarms && chrome.alarms.onAlarm) { + chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm && alarm.name === RECONNECT_ALARM_NAME) { + restoreState().then(connectIfNeeded).catch(reportError); + } + }); +} + +restoreState().then(connectIfNeeded).catch(reportError); + +async function handleExtensionMessage(message, sender) { + if (!message || typeof message.type !== "string") { + throw new Error("Invalid message"); + } + + if (message.type === "edge_share_crx_recorder_update") { + crxRecorderState = { + ...crxRecorderState, + mode: typeof message.mode === "string" ? message.mode : crxRecorderState.mode, + sources: Array.isArray(message.sources) ? message.sources : crxRecorderState.sources + }; + notifyRecordingChanged(); + return recordingState(); + } + + if (message.type === "get_state") { + await restoreState(); + return publicState(); + } + + if (message.type === "get_recording") { + await restoreState(); + return recordingState(); + } + + if (message.type === "start_share") { + return startShare(message.relayUrl || DEFAULT_RELAY_URL); + } + + if (message.type === "start_recording") { + await restoreState(); + return startRecording(message.params || {}); + } + + if (message.type === "set_recording_mode") { + await restoreState(); + return setRecordingMode(message.mode); + } + + if (message.type === "stop_recording") { + await restoreState(); + return stopRecording(); + } + + if (message.type === "clear_recording") { + await restoreState(); + return clearRecording(); + } + + if (message.type === "recorder_action") { + await restoreState(); + return recordContentAction(message.action || {}, sender); + } + + if (message.type === "inspect_target") { + await restoreState(); + return recordInspectTarget(message.target || {}, sender); + } + + if (message.type === "play_recording") { + await restoreState(); + return playRecording(); + } + + if (message.type === "platform_request") { + return handlePlatformRequest(message, sender); + } + + if (message.type === "get_platform_connect_request") { + return getPlatformConnectRequest(message.requestId); + } + + if (message.type === "approve_platform_connect") { + return approvePlatformConnect(message.requestId); + } + + if (message.type === "reject_platform_connect") { + return rejectPlatformConnect(message.requestId); + } + + if (message.type === "stop_share") { + return stopShare(); + } + + throw new Error(`Unknown popup message: ${message.type}`); +} + +async function startShare(relayUrlInput, options = {}) { + const relayUrl = normalizeRelayUrl(relayUrlInput); + const sessionId = randomHex(12); + const browserToken = randomHex(24); + const agentToken = randomHex(24); + const shareUrl = buildShareUrl(relayUrl, sessionId, agentToken); + + intentionallyClosed = false; + reconnectDelayMs = RECONNECT_MIN_MS; + + await persistState({ + sharing: true, + connected: false, + relayUrl, + sessionId, + browserToken, + agentToken, + shareUrl, + status: "connecting", + lastError: "", + activeTabId: null, + platformOrigin: options.platformOrigin || "", + platformHref: options.platformHref || "", + workspaceId: options.workspaceId || "", + poolId: options.poolId || "", + browserName: options.browserName || "" + }); + + connectRelay(); + return publicState(); +} + +async function stopShare() { + intentionallyClosed = true; + clearReconnectTimer(); + clearKeepAliveTimer(); + + if (socket) { + try { + socket.close(1000, "sharing stopped"); + } catch (_error) { + // Ignore close errors while stopping. + } + socket = null; + } + + await detachAllDebuggers(); + + await persistState({ + sharing: false, + connected: false, + sessionId: "", + browserToken: "", + agentToken: "", + shareUrl: "", + status: "stopped", + lastError: "", + recording: false, + recordingTabId: null, + recorderMode: "record", + recordingStoppedAt: new Date().toISOString(), + playbackRunning: false, + playbackError: "", + playbackStepId: "", + platformOrigin: "", + platformHref: "", + workspaceId: "", + poolId: "", + browserName: "" + }); + + return publicState(); +} + +async function restoreState() { + const stored = await chromeCall(chrome.storage.local.get, chrome.storage.local, STORAGE_KEY); + if (stored && stored[STORAGE_KEY]) { + state = { ...state, ...stored[STORAGE_KEY] }; + } +} + +async function persistState(patch) { + state = { + ...state, + ...patch, + updatedAt: new Date().toISOString() + }; + + await chromeCall(chrome.storage.local.set, chrome.storage.local, { + [STORAGE_KEY]: state + }); + + notifyPopup(); +} + +function publicState() { + return { + sharing: state.sharing, + connected: state.connected, + relayUrl: state.relayUrl || DEFAULT_RELAY_URL, + sessionId: state.sessionId, + shareUrl: state.shareUrl, + status: state.status, + lastError: state.lastError, + activeTabId: state.activeTabId, + recording: state.recording, + recordingTabId: state.recordingTabId, + recorderMode: state.recorderMode || "record", + recordingCount: Array.isArray(state.recordedActions) ? state.recordedActions.length : 0, + recordingStartedAt: state.recordingStartedAt, + recordingStoppedAt: state.recordingStoppedAt, + platformOrigin: state.platformOrigin, + workspaceId: state.workspaceId, + poolId: state.poolId, + browserName: state.browserName, + updatedAt: state.updatedAt + }; +} + +function notifyPopup() { + try { + chrome.runtime.sendMessage({ type: "state_changed", state: publicState() }, () => { + // Popup may be closed; reading lastError prevents noisy extension logs. + void chrome.runtime.lastError; + }); + } catch (_error) { + // Popup may be closed. + } +} + +function notifyRecordingChanged() { + const message = { + type: "recording_state_changed", + recording: recordingState() + }; + + try { + chrome.tabs.query({}, (tabs) => { + const error = chrome.runtime.lastError; + if (error || !Array.isArray(tabs)) { + return; + } + for (const tab of tabs) { + if (!Number.isInteger(tab.id) || !isRecordableUrl(tab.url || "")) { + continue; + } + chrome.tabs.sendMessage(tab.id, message, () => { + // Some pages will not have this content script yet. + void chrome.runtime.lastError; + }); + } + }); + } catch (_error) { + // Tabs may be unavailable in restricted extension contexts. + } +} + +function connectIfNeeded() { + if (state.sharing) { + connectRelay(); + } +} + +function connectRelay() { + if (!state.sharing || !state.relayUrl || !state.sessionId || !state.browserToken) { + return; + } + + clearReconnectTimer(); + clearKeepAliveTimer(); + + if (socket) { + try { + socket.close(1000, "reconnecting"); + } catch (_error) { + // Continue with a new socket. + } + } + + const wsUrl = buildBrowserWsUrl( + state.relayUrl, + state.sessionId, + state.browserToken, + state.agentToken + ); + socket = new WebSocket(wsUrl); + + persistState({ connected: false, status: "connecting", lastError: "" }).catch(reportError); + + socket.addEventListener("open", () => { + reconnectDelayMs = RECONNECT_MIN_MS; + clearReconnectTimer(); + persistState({ connected: true, status: "connected", lastError: "" }).catch(reportError); + sendSocket({ + type: "hello", + role: "browser", + protocolVersion: PROTOCOL_VERSION, + sessionId: state.sessionId, + userAgent: navigator.userAgent + }); + startKeepAliveTimer(); + }); + + socket.addEventListener("message", (event) => { + handleRelayMessage(event.data).catch((error) => { + sendSocket({ + type: "event", + event: "handler_error", + error: errorMessage(error) + }); + }); + }); + + socket.addEventListener("close", (event) => { + clearKeepAliveTimer(); + socket = null; + persistState({ + connected: false, + status: state.sharing ? "disconnected" : "stopped", + lastError: event.reason || "" + }).catch(reportError); + + if (state.sharing && !intentionallyClosed) { + scheduleReconnect(); + } + }); + + socket.addEventListener("error", () => { + clearKeepAliveTimer(); + persistState({ lastError: "WebSocket error" }).catch(reportError); + if (state.sharing && !intentionallyClosed) { + scheduleReconnect(); + } + }); +} + +function scheduleReconnect() { + clearReconnectTimer(); + const delayMs = reconnectDelayMs; + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + reconnectDelayMs = Math.min(reconnectDelayMs * 2, RECONNECT_MAX_MS); + connectRelay(); + }, delayMs); + if (chrome.alarms && chrome.alarms.create) { + chrome.alarms.create(RECONNECT_ALARM_NAME, { + delayInMinutes: Math.max(0.5, delayMs / 60000) + }); + } +} + +function clearReconnectTimer() { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + if (chrome.alarms && chrome.alarms.clear) { + chrome.alarms.clear(RECONNECT_ALARM_NAME, () => { + void chrome.runtime.lastError; + }); + } +} + +function startKeepAliveTimer() { + clearKeepAliveTimer(); + keepAliveTimer = setInterval(() => { + sendSocket({ + type: "keepalive", + at: new Date().toISOString() + }); + }, RELAY_KEEPALIVE_MS); +} + +function clearKeepAliveTimer() { + if (keepAliveTimer) { + clearInterval(keepAliveTimer); + keepAliveTimer = null; + } +} + +async function handlePlatformRequest(message, sender) { + if (message.method !== "connect") { + throw new Error(`Unsupported platform request method: ${message.method}`); + } + if (!sender || !sender.tab || !Number.isInteger(sender.tab.id) || !sender.url) { + throw new Error("Platform requests must come from a browser tab"); + } + + const pageUrl = new URL(sender.url); + if (pageUrl.protocol !== "http:" && pageUrl.protocol !== "https:") { + throw new Error("Platform requests must come from an http or https page"); + } + if (message.origin !== pageUrl.origin) { + throw new Error("Platform request origin did not match the sender tab"); + } + + const params = message.params && typeof message.params === "object" ? message.params : {}; + const requestId = randomHex(12); + const request = { + requestId, + origin: pageUrl.origin, + href: sender.url, + title: message.title || sender.tab.title || "", + tabId: sender.tab.id, + workspaceId: stringParam(params.workspaceId), + poolId: stringParam(params.poolId), + browserName: stringParam(params.displayName || params.browserName) || "Edge", + relayUrl: normalizeRelayUrl(stringParam(params.relayUrl) || pageUrl.origin), + createdAt: Date.now() + }; + + if (new URL(request.relayUrl).origin !== request.origin) { + throw new Error("Platform relayUrl must use the requesting page origin"); + } + + const reused = await tryReusePlatformShare(request); + if (reused) { + return reused; + } + + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pendingPlatformRequests.delete(requestId); + reject(new Error("Platform connect request expired")); + }, PLATFORM_CONNECT_TTL_MS); + + pendingPlatformRequests.set(requestId, { + request, + resolve, + reject, + timeout + }); + + chrome.windows.create( + { + url: chrome.runtime.getURL(`connect.html?requestId=${encodeURIComponent(requestId)}`), + type: "popup", + width: 420, + height: 560 + }, + () => { + const error = chrome.runtime.lastError; + if (error) { + clearTimeout(timeout); + pendingPlatformRequests.delete(requestId); + reject(new Error(error.message)); + } + } + ); + }); +} + +async function tryReusePlatformShare(request) { + await restoreState(); + if (!state.sharing || !state.shareUrl || !state.sessionId || !state.browserToken) { + return null; + } + if (normalizeRelayUrl(state.relayUrl) !== request.relayUrl) { + return null; + } + if (state.platformOrigin && state.platformOrigin !== request.origin) { + return null; + } + + intentionallyClosed = false; + reconnectDelayMs = RECONNECT_MIN_MS; + await persistState({ + platformOrigin: request.origin, + platformHref: request.href, + workspaceId: request.workspaceId, + poolId: request.poolId, + browserName: request.browserName, + relayUrl: request.relayUrl, + lastError: "", + status: state.connected ? "connected" : "connecting" + }); + if (!socket || socket.readyState !== WebSocket.OPEN) { + connectRelay(); + } + await waitForRelayConnection(PLATFORM_RELAY_CONNECT_TIMEOUT_MS); + const result = publicState(); + return { + shareUrl: result.shareUrl, + sessionId: result.sessionId, + connected: result.connected, + relayUrl: result.relayUrl, + platformOrigin: request.origin, + workspaceId: request.workspaceId, + poolId: request.poolId, + browserName: request.browserName + }; +} + +async function getPlatformConnectRequest(requestId) { + const entry = pendingPlatformRequests.get(String(requestId || "")); + if (!entry) { + throw new Error("Platform connect request was not found or expired"); + } + return sanitizePlatformRequest(entry.request); +} + +async function approvePlatformConnect(requestId) { + const id = String(requestId || ""); + const entry = pendingPlatformRequests.get(id); + if (!entry) { + throw new Error("Platform connect request was not found or expired"); + } + + pendingPlatformRequests.delete(id); + clearTimeout(entry.timeout); + + let started = false; + try { + await startShare(entry.request.relayUrl, { + platformOrigin: entry.request.origin, + platformHref: entry.request.href, + workspaceId: entry.request.workspaceId, + poolId: entry.request.poolId, + browserName: entry.request.browserName + }); + started = true; + if (!(await waitForRelayConnection(PLATFORM_RELAY_CONNECT_TIMEOUT_MS))) { + throw new Error(state.lastError || "Timed out connecting to browser relay"); + } + const result = publicState(); + const response = { + shareUrl: result.shareUrl, + sessionId: result.sessionId, + connected: result.connected, + relayUrl: result.relayUrl, + platformOrigin: entry.request.origin, + workspaceId: entry.request.workspaceId, + poolId: entry.request.poolId, + browserName: entry.request.browserName + }; + entry.resolve(response); + return response; + } catch (error) { + if (started) { + await stopShare().catch(reportError); + } + entry.reject(error); + throw error; + } +} + +async function rejectPlatformConnect(requestId) { + const id = String(requestId || ""); + const entry = pendingPlatformRequests.get(id); + if (!entry) { + return { rejected: true }; + } + + pendingPlatformRequests.delete(id); + clearTimeout(entry.timeout); + const error = new Error("User rejected browser connection"); + entry.reject(error); + return { rejected: true }; +} + +function sanitizePlatformRequest(request) { + return { + requestId: request.requestId, + origin: request.origin, + href: request.href, + title: request.title, + workspaceId: request.workspaceId, + poolId: request.poolId, + browserName: request.browserName, + relayUrl: request.relayUrl, + createdAt: request.createdAt + }; +} + +async function waitForRelayConnection(timeoutMs) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (state.connected) { + return true; + } + if (!state.sharing) { + return false; + } + await sleep(100); + } + return state.connected; +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function withTimeout(promise, timeoutMs, label) { + let timer = null; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error(`${label} timed out after ${timeoutMs}ms`)); + }, timeoutMs); + }); + return Promise.race([promise, timeout]).finally(() => { + if (timer) { + clearTimeout(timer); + } + }); +} + +async function handleRelayMessage(rawData) { + let message; + try { + message = JSON.parse(rawData); + } catch (_error) { + sendSocket({ type: "event", event: "invalid_json" }); + return; + } + + if (message.type === "ping") { + sendSocket({ type: "pong", at: new Date().toISOString() }); + return; + } + + const requestId = message.id || message.requestId; + const command = message.command || message.method; + const params = message.params || {}; + + if (!requestId || !command) { + sendSocket({ + type: "event", + event: "ignored_message", + reason: "missing id or command" + }); + return; + } + + try { + const result = await handleCommand(command, params); + sendSocket({ + type: "response", + id: requestId, + ok: true, + result + }); + } catch (error) { + sendSocket({ + type: "response", + id: requestId, + ok: false, + error: errorMessage(error) + }); + } +} + +async function handleCommand(command, params) { + if (command === "navigate") { + return commandNavigate(params); + } + if (command === "evaluate") { + return commandEvaluate(params); + } + if (command === "snapshot") { + return commandSnapshot(params); + } + if (command === "click") { + return commandClick(params); + } + if (command === "type") { + return commandType(params); + } + if (command === "press_key") { + return commandPressKey(params); + } + if (command === "screenshot") { + return commandScreenshot(params); + } + if (command === "list_tabs") { + return commandListTabs(); + } + if (command === "activate_tab") { + return commandActivateTab(params); + } + if (command === "run_playwright") { + return commandRunPlaywright(params); + } + if (command === "start_recording") { + return startRecording(params); + } + if (command === "set_recording_mode") { + return setRecordingMode(params.mode); + } + if (command === "stop_recording") { + return stopRecording(); + } + if (command === "clear_recording") { + return clearRecording(); + } + if (command === "play_recording") { + return playRecording(); + } + if (command === "recording_state") { + return recordingState(); + } + + throw new Error(`Unsupported command: ${command}`); +} + +async function commandNavigate(params) { + if (!params.url || typeof params.url !== "string") { + throw new Error("navigate requires params.url"); + } + + const tabId = await getTargetTabId(params); + const tab = await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { + url: params.url, + active: params.activate !== false + }); + + state.activeTabId = tab.id; + return { tab: tabSummary(tab) }; +} + +async function commandEvaluate(params) { + if (!params.expression || typeof params.expression !== "string") { + throw new Error("evaluate requires params.expression"); + } + + const tabId = await getTargetTabId(params); + const value = await evaluateInPage(tabId, params.expression); + return { + tab: await currentTabSummary(tabId), + value + }; +} + +async function commandSnapshot(params) { + const tabId = await getTargetTabId(params); + const snapshot = await runFunctionInPage(tabId, createSnapshot, [ + params.maxTextLength || 200000, + params.maxItems || 200 + ]); + + return { + tab: await currentTabSummary(tabId), + snapshot + }; +} + +async function commandClick(params) { + if (!params.selector || typeof params.selector !== "string") { + throw new Error("click requires params.selector"); + } + + const tabId = await getTargetTabId(params); + const result = await runFunctionInPage(tabId, clickSelector, [params.selector]); + return { + tab: await currentTabSummary(tabId), + action: result + }; +} + +async function commandType(params) { + if (typeof params.text !== "string") { + throw new Error("type requires params.text"); + } + + const tabId = await getTargetTabId(params); + const result = await runFunctionInPage(tabId, typeText, [ + params.selector || "", + params.text, + params.replace === true || params.clear === true + ]); + + return { + tab: await currentTabSummary(tabId), + action: result + }; +} + +async function commandPressKey(params) { + if (!params.key || typeof params.key !== "string") { + throw new Error("press_key requires params.key"); + } + + const tabId = await getTargetTabId(params); + const key = normalizeKey(params.key); + await sendKeyEvent(tabId, key, "rawKeyDown"); + + if (key.text) { + await sendKeyEvent(tabId, key, "char"); + } + + await sendKeyEvent(tabId, key, "keyUp"); + + return { + tab: await currentTabSummary(tabId), + action: { key: key.key, code: key.code } + }; +} + +async function commandScreenshot(params) { + const tabId = await getTargetTabId(params); + const format = params.format === "jpeg" ? "jpeg" : "png"; + const quality = format === "jpeg" ? clampNumber(params.quality || 80, 1, 100) : undefined; + + try { + await sendCdp(tabId, "Page.enable", {}); + const result = await sendCdp(tabId, "Page.captureScreenshot", { + format, + quality, + fromSurface: true, + captureBeyondViewport: params.fullPage === true + }); + + return { + tab: await currentTabSummary(tabId), + mimeType: `image/${format}`, + data: result.data + }; + } catch (error) { + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { active: true }); + const dataUrl = await chromeCall(chrome.tabs.captureVisibleTab, chrome.tabs, tab.windowId, { + format, + quality + }); + + return { + tab: tabSummary(tab), + mimeType: `image/${format}`, + dataUrl, + fallback: "tabs.captureVisibleTab", + warning: errorMessage(error) + }; + } +} + +async function commandListTabs() { + const windows = await chromeCall(chrome.windows.getAll, chrome.windows, { + populate: true + }); + const summaries = windows.map(windowSummary); + return { + windows: summaries, + tabs: summaries.flatMap((window) => window.tabs) + }; +} + +async function commandActivateTab(params) { + const tabId = await getTargetTabId(params); + const tab = await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { active: true }); + state.activeTabId = tab.id; + await persistState({ activeTabId: tab.id }); + return { tab: tabSummary(tab) }; +} + +async function commandRunPlaywright(params = {}) { + if (!params || typeof params.code !== "string" || !params.code.trim()) { + throw new Error("run_playwright requires params.code"); + } + if (typeof globalThis.getCrxApp !== "function") { + throw new Error("Playwright CRX runtime is not available in this extension build"); + } + if (params.allowClose !== true && /\.\s*close\s*\(/.test(params.code)) { + throw new Error("run_playwright blocks close() by default; pass --allow-close to allow it"); + } + + let tabId = await getTargetTabId(params); + let tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + if (/^chrome:\/\//i.test(tab.url || "")) { + tab = await chromeCall(chrome.tabs.create, chrome.tabs, { + windowId: tab.windowId, + url: "about:blank", + active: true + }); + tabId = tab.id; + } + if (!Number.isInteger(tabId)) { + throw new Error("run_playwright could not resolve a target tab"); + } + + const code = normalizePlaywrightCrxCode(params.code); + const timeoutMs = Number.isFinite(Number(params.timeoutMs)) + ? clampNumber(params.timeoutMs, 1000, 10 * 60 * 1000) + : 0; + + try { + const app = normalizeCrxApplication(await globalThis.getCrxApp(!!tab.incognito)); + const runner = crxRunner(app); + if (!app || typeof app.attach !== "function" || typeof runner.run !== "function") { + throw new Error(`Playwright CRX application does not expose attach/run or recorder.run: ${describeCrxApplication(app)}`); + } + const page = await app.attach(tabId); + const run = runner.acceptsPage ? runner.run(code, page) : runner.run(code); + if (timeoutMs > 0) { + await withTimeout(run, timeoutMs, "run_playwright"); + } else { + await run; + } + state.activeTabId = tabId; + await persistState({ activeTabId: tabId, lastError: "" }); + return { + ok: true, + mode: "playwright-crx", + tab: await currentTabSummary(tabId) + }; + } catch (error) { + await persistState({ lastError: errorMessage(error) }).catch(reportError); + throw error; + } +} + +function normalizeCrxApplication(app) { + if (app && typeof app.attach === "function" && typeof crxRunner(app).run === "function") { + return app; + } + if ( + app && + app.crxApplication && + typeof app.crxApplication.attach === "function" && + typeof crxRunner(app.crxApplication).run === "function" + ) { + return app.crxApplication; + } + if ( + app && + app._object && + typeof app._object.attach === "function" && + typeof crxRunner(app._object).run === "function" + ) { + return app._object; + } + return app; +} + +function crxRunner(app) { + if (!app || typeof app !== "object") { + return { run: null, acceptsPage: false }; + } + if (typeof app.run === "function") { + return { run: app.run.bind(app), acceptsPage: true }; + } + if (app.recorder && typeof app.recorder.run === "function") { + return { run: app.recorder.run.bind(app.recorder), acceptsPage: false }; + } + if (app._object) { + return crxRunner(app._object); + } + return { run: null, acceptsPage: false }; +} + +function describeCrxApplication(app) { + if (!app || typeof app !== "object") { + return String(app); + } + const keys = Object.keys(app).slice(0, 40).join(",") || "no enumerable keys"; + const proto = Object.getPrototypeOf(app); + const protoKeys = proto ? Object.getOwnPropertyNames(proto).slice(0, 40).join(",") : "no prototype"; + const recorder = app.recorder && typeof app.recorder === "object" + ? ` recorderKeys=[${Object.keys(app.recorder).slice(0, 20).join(",") || "no enumerable keys"}]` + : ""; + return `keys=[${keys}] proto=[${protoKeys}]${recorder}`; +} + +async function startRecording(params = {}) { + const tabId = Number.isInteger(params.tabId) ? params.tabId : await getTargetTabId({}); + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + await attachCrxRecorder(tab, normalizeCrxMode(params.mode)); + const startedAt = new Date().toISOString(); + const actions = []; + if (tab.url && isRecordableUrl(tab.url)) { + actions.push(recordedAction("navigate", { + url: tab.url, + title: tab.title || "", + tabId, + windowId: tab.windowId + })); + } + + await persistState({ + recording: true, + recordingTabId: null, + recorderMode: normalizeRecorderMode(params.mode), + recordingStartedAt: startedAt, + recordingStoppedAt: "", + recordedActions: actions, + lastInspect: null, + playbackError: "", + playbackStepId: "", + activeTabId: tabId + }); + + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function setRecordingMode(mode) { + if (!state.recording) { + return startRecording({ mode }); + } + const tabId = await getTargetTabId({}); + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + await attachCrxRecorder(tab, normalizeCrxMode(mode)); + await persistState({ + recorderMode: normalizeRecorderMode(mode), + lastInspect: null + }); + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function attachCrxRecorder(tab, mode) { + if (typeof globalThis.attach !== "function") { + return; + } + try { + await globalThis.attach(tab, mode); + } catch (error) { + await persistState({ lastError: errorMessage(error) }).catch(reportError); + throw error; + } +} + +async function setCrxRecorderStandby() { + if (typeof globalThis.getCrxApp !== "function") { + return; + } + try { + const app = await globalThis.getCrxApp(false); + if (app && app.recorder && typeof app.recorder.setMode === "function") { + await app.recorder.setMode("standby"); + } + } catch (_error) { + // The recorder may not be initialized yet; relay state can still stop. + } +} + +async function stopRecording() { + await setCrxRecorderStandby(); + await persistState({ + recording: false, + recorderMode: "record", + recordingStoppedAt: new Date().toISOString(), + lastInspect: null, + playbackRunning: false + }); + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function clearRecording() { + await setCrxRecorderStandby(); + await persistState({ + recording: false, + recordingTabId: null, + recorderMode: "record", + recordingStartedAt: "", + recordingStoppedAt: "", + recordedActions: [], + lastInspect: null, + playbackRunning: false, + playbackError: "", + playbackStepId: "" + }); + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function recordContentAction(action, sender) { + if (!state.recording || !sender?.tab || !Number.isInteger(sender.tab.id)) { + return { recorded: false }; + } + if ((state.recorderMode || "record") !== "record") { + return { recorded: false }; + } + if (!isRecordableUrl(sender.tab.url || action.url || "")) { + return { recorded: false }; + } + + const normalized = recordedAction(action.kind, { + ...action, + tabId: sender.tab.id, + windowId: sender.tab.windowId, + title: action.title || sender.tab.title || "", + url: action.url || sender.tab.url || "" + }); + if (!normalized) { + return { recorded: false }; + } + + const actions = Array.isArray(state.recordedActions) ? [...state.recordedActions] : []; + upsertRecordedAction(actions, normalized); + while (actions.length > MAX_RECORDED_ACTIONS) { + actions.shift(); + } + + await persistState({ recordedActions: actions, activeTabId: sender.tab.id }); + notifyRecordingChanged(); + return { recorded: true, action: normalized, count: actions.length }; +} + +async function recordInspectTarget(target, sender) { + if (!state.recording || (state.recorderMode || "record") !== "inspect") { + return { inspected: false }; + } + if (!sender?.tab || !Number.isInteger(sender.tab.id)) { + return { inspected: false }; + } + if (!isRecordableUrl(sender.tab.url || target.url || "")) { + return { inspected: false }; + } + + const inspected = { + at: new Date().toISOString(), + selector: String(target.selector || "").slice(0, 1024), + label: String(target.label || "").slice(0, 512), + tag: String(target.tag || "").slice(0, 64), + url: String(target.url || sender.tab.url || "").slice(0, 4096), + title: String(target.title || sender.tab.title || "").slice(0, 512), + tabId: sender.tab.id, + windowId: sender.tab.windowId + }; + + await persistState({ lastInspect: inspected, activeTabId: sender.tab.id }); + notifyRecordingChanged(); + return { inspected: true, target: inspected }; +} + +async function playRecording() { + const actions = Array.isArray(state.recordedActions) ? [...state.recordedActions] : []; + if (actions.length === 0) { + throw new Error("No recorded actions to play"); + } + + await persistState({ + playbackRunning: true, + playbackError: "", + playbackStepId: "" + }); + notifyRecordingChanged(); + + let caught = null; + try { + for (const action of actions) { + await persistState({ playbackStepId: action.id || "" }); + notifyRecordingChanged(); + await playRecordedAction(action); + } + } catch (error) { + caught = error; + await persistState({ playbackError: errorMessage(error) }); + } finally { + await persistState({ playbackRunning: false }); + notifyRecordingChanged(); + } + + if (caught) { + throw caught; + } + return recordingState(); +} + +async function playRecordedAction(action) { + const tabId = await playbackTabId(action); + if (action.kind === "navigate" && action.url) { + await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { + url: action.url, + active: true + }); + state.activeTabId = tabId; + await waitForTabReady(tabId, 10000); + return; + } + if (action.kind === "click" && action.selector) { + await runFunctionInPage(tabId, clickSelector, [action.selector]); + return; + } + if (action.kind === "fill" && action.selector) { + await runFunctionInPage(tabId, typeText, [action.selector, action.text || "", true]); + return; + } + if (action.kind === "press" && action.key) { + if (action.selector) { + await runFunctionInPage(tabId, focusSelector, [action.selector]); + } + const key = normalizeKey(action.key); + await sendKeyEvent(tabId, key, "rawKeyDown"); + if (key.text) { + await sendKeyEvent(tabId, key, "char"); + } + await sendKeyEvent(tabId, key, "keyUp"); + } +} + +async function playbackTabId(action) { + if (Number.isInteger(action.tabId)) { + try { + await chromeCall(chrome.tabs.get, chrome.tabs, action.tabId); + state.activeTabId = action.tabId; + return action.tabId; + } catch (_error) { + // The original tab was closed; fall back to the active tab. + } + } + return getTargetTabId({}); +} + +async function waitForTabReady(tabId, timeoutMs) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + if (tab.status === "complete") { + return; + } + } catch (_error) { + return; + } + await sleep(100); + } +} + +function recordingState() { + const actions = Array.isArray(state.recordedActions) ? state.recordedActions : []; + const crxSources = Array.isArray(crxRecorderState.sources) ? crxRecorderState.sources : []; + const preferredSource = + crxSources.find((source) => source && source.id === "playwright-test") || + crxSources.find((source) => source && typeof source.text === "string") || + null; + return { + recording: state.recording, + mode: state.recorderMode || "record", + crxMode: crxRecorderState.mode || "none", + tabId: state.recordingTabId, + startedAt: state.recordingStartedAt, + stoppedAt: state.recordingStoppedAt, + count: actions.length, + actions, + sources: crxSources, + lastInspect: state.lastInspect || null, + playing: !!state.playbackRunning, + playbackError: state.playbackError || "", + playbackStepId: state.playbackStepId || "", + script: preferredSource?.text || renderRecordedPlaywright(actions) + }; +} + +function normalizeRecorderMode(mode) { + return mode === "inspect" ? "inspect" : "record"; +} + +function normalizeCrxMode(mode) { + return mode === "inspect" || mode === "inspecting" ? "inspecting" : "recording"; +} + +function recordedAction(kind, fields) { + const actionKind = String(kind || ""); + if (!["navigate", "click", "fill", "press"].includes(actionKind)) { + return null; + } + const action = { + id: randomHex(6), + kind: actionKind, + at: new Date().toISOString(), + url: String(fields.url || "").slice(0, 4096), + title: String(fields.title || "").slice(0, 512), + tabId: Number.isInteger(fields.tabId) ? fields.tabId : null, + windowId: Number.isInteger(fields.windowId) ? fields.windowId : null + }; + if (fields.selector) action.selector = String(fields.selector).slice(0, 1024); + if (fields.text !== undefined) action.text = String(fields.text).slice(0, 4096); + if (fields.key) action.key = String(fields.key).slice(0, 128); + if (fields.label) action.label = String(fields.label).slice(0, 512); + if (fields.tag) action.tag = String(fields.tag).slice(0, 64); + return action; +} + +function upsertRecordedAction(actions, action) { + const previous = actions[actions.length - 1]; + if ( + previous && + action.kind === "fill" && + previous.kind === "fill" && + previous.selector === action.selector + ) { + actions[actions.length - 1] = { ...previous, ...action, id: previous.id }; + return; + } + if ( + previous && + action.kind === "navigate" && + previous.kind === "navigate" && + previous.url === action.url + ) { + return; + } + actions.push(action); +} + +function renderRecordedPlaywright(actions) { + const lines = [ + "import { test, expect } from '@playwright/test';", + "", + "test('rbc recording', async ({ page }) => {" + ]; + let previousTabId = null; + for (const action of actions) { + if (action.tabId && action.tabId !== previousTabId) { + lines.push(` // Tab ${action.tabId}${action.title ? `: ${action.title}` : ""}`); + previousTabId = action.tabId; + } + if (action.kind === "navigate" && action.url) { + lines.push(` await page.goto(${JSON.stringify(action.url)});`); + } else if (action.kind === "click" && action.selector) { + lines.push(` await page.locator(${JSON.stringify(action.selector)}).click();`); + } else if (action.kind === "fill" && action.selector) { + lines.push(` await page.locator(${JSON.stringify(action.selector)}).fill(${JSON.stringify(action.text || "")});`); + } else if (action.kind === "press" && action.key) { + if (action.selector) { + lines.push(` await page.locator(${JSON.stringify(action.selector)}).press(${JSON.stringify(action.key)});`); + } else { + lines.push(` await page.locator("body").press(${JSON.stringify(action.key)});`); + } + } + } + lines.push("});"); + return lines.join("\n"); +} + +function normalizePlaywrightCrxCode(code) { + const source = String(code || "").trim(); + if (!source) { + return source; + } + if (/\btest\s*\(/.test(source)) { + return source; + } + + const moduleMatch = source.match( + /^module\.exports\s*=\s*async\s*\(\s*\{\s*page\s*\}\s*\)\s*=>\s*\{([\s\S]*)\}\s*;?\s*$/ + ); + const body = moduleMatch ? moduleMatch[1].trim() : source; + return [ + "import { test, expect } from '@playwright/test';", + "", + "test('rbc', async ({ page }) => {", + indentPlaywrightBody(body), + "});" + ].join("\n"); +} + +function indentPlaywrightBody(body) { + return String(body || "") + .split(/\r?\n/) + .map((line) => (line.trim() ? ` ${line}` : "")) + .join("\n"); +} + +function isRecordableUrl(url) { + return /^https?:\/\//i.test(String(url || "")); +} + +async function getTargetTabId(params) { + if (Number.isInteger(params.tabId)) { + state.activeTabId = params.tabId; + return params.tabId; + } + + if (Number.isInteger(state.activeTabId)) { + try { + await chromeCall(chrome.tabs.get, chrome.tabs, state.activeTabId); + return state.activeTabId; + } catch (_error) { + state.activeTabId = null; + } + } + + const activeTabs = await chromeCall(chrome.tabs.query, chrome.tabs, { + active: true, + lastFocusedWindow: true + }); + + if (activeTabs.length > 0 && Number.isInteger(activeTabs[0].id)) { + state.activeTabId = activeTabs[0].id; + return activeTabs[0].id; + } + + const tabs = await chromeCall(chrome.tabs.query, chrome.tabs, { active: true }); + if (tabs.length > 0 && Number.isInteger(tabs[0].id)) { + state.activeTabId = tabs[0].id; + return tabs[0].id; + } + + throw new Error("No active tab found"); +} + +async function currentTabSummary(tabId) { + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + return tabSummary(tab); +} + +function windowSummary(window) { + return { + id: window.id, + focused: window.focused, + incognito: window.incognito, + profile: window.incognito ? "incognito" : "regular", + type: window.type || "", + state: window.state || "", + top: window.top, + left: window.left, + width: window.width, + height: window.height, + tabs: (window.tabs || []).map((tab) => tabSummary(tab, window)) + }; +} + +function tabSummary(tab, window) { + return { + id: tab.id, + windowId: tab.windowId, + active: tab.active, + index: tab.index, + incognito: tab.incognito || window?.incognito || false, + profile: tab.incognito || window?.incognito ? "incognito" : "regular", + pinned: tab.pinned || false, + audible: tab.audible || false, + discarded: tab.discarded || false, + title: tab.title || "", + url: tab.url || "", + status: tab.status || "" + }; +} + +async function evaluateInPage(tabId, expression) { + await sendCdp(tabId, "Runtime.enable", {}); + const result = await sendCdp(tabId, "Runtime.evaluate", { + expression, + awaitPromise: true, + returnByValue: true, + userGesture: true + }); + + if (result.exceptionDetails) { + throw new Error(formatException(result.exceptionDetails)); + } + + return unwrapRemoteObject(result.result); +} + +async function runFunctionInPage(tabId, fn, args) { + const expression = `(${fn.toString()})(${args.map((arg) => JSON.stringify(arg)).join(",")})`; + return evaluateInPage(tabId, expression); +} + +async function ensureDebugger(tabId) { + if (attachedTabs.has(tabId)) { + return; + } + + try { + await chromeCall(chrome.debugger.attach, chrome.debugger, { tabId }, "1.3"); + attachedTabs.add(tabId); + } catch (error) { + if (String(errorMessage(error)).includes("Another debugger is already attached")) { + attachedTabs.add(tabId); + return; + } + throw error; + } +} + +async function detachAllDebuggers() { + const tabIds = Array.from(attachedTabs); + attachedTabs.clear(); + + await Promise.all( + tabIds.map(async (tabId) => { + try { + await chromeCall(chrome.debugger.detach, chrome.debugger, { tabId }); + } catch (_error) { + // The tab may have closed or detached already. + } + }) + ); +} + +async function sendCdp(tabId, method, params) { + await ensureDebugger(tabId); + return chromeCall(chrome.debugger.sendCommand, chrome.debugger, { tabId }, method, params || {}); +} + +async function sendKeyEvent(tabId, key, type) { + await sendCdp(tabId, "Input.dispatchKeyEvent", { + type, + key: key.key, + code: key.code, + windowsVirtualKeyCode: key.keyCode, + nativeVirtualKeyCode: key.keyCode, + text: type === "char" ? key.text : "", + unmodifiedText: type === "char" ? key.text : "", + modifiers: 0 + }); +} + +function createSnapshot(maxTextLength, maxItems) { + function trim(value, length) { + return String(value || "").replace(/\s+/g, " ").trim().slice(0, length); + } + + function cssPath(element) { + if (!element || element.nodeType !== Node.ELEMENT_NODE) { + return ""; + } + + if (element.id) { + return `#${CSS.escape(element.id)}`; + } + + const parts = []; + let current = element; + + while (current && current.nodeType === Node.ELEMENT_NODE && parts.length < 5) { + let part = current.tagName.toLowerCase(); + if (current.classList.length > 0) { + part += `.${CSS.escape(current.classList[0])}`; + } + + const parent = current.parentElement; + if (parent) { + const siblings = Array.from(parent.children).filter((child) => child.tagName === current.tagName); + if (siblings.length > 1) { + part += `:nth-of-type(${siblings.indexOf(current) + 1})`; + } + } + + parts.unshift(part); + current = parent; + } + + return parts.join(" > "); + } + + function describe(element) { + return { + selector: cssPath(element), + tag: element.tagName.toLowerCase(), + role: element.getAttribute("role") || "", + label: trim( + element.getAttribute("aria-label") || + element.getAttribute("alt") || + element.getAttribute("title") || + element.value || + element.innerText, + 300 + ), + href: element.href || "", + type: element.getAttribute("type") || "" + }; + } + + const clickableSelector = "a,button,input,textarea,select,[role='button'],[contenteditable='true']"; + const elements = Array.from(document.querySelectorAll(clickableSelector)) + .slice(0, maxItems) + .map(describe); + + return { + url: location.href, + title: document.title, + text: trim(document.body ? document.body.innerText : "", maxTextLength), + activeElement: cssPath(document.activeElement), + elements + }; +} + +function clickSelector(selector) { + const element = document.querySelector(selector); + if (!element) { + throw new Error(`No element matches selector: ${selector}`); + } + + element.scrollIntoView({ block: "center", inline: "center", behavior: "auto" }); + const rect = element.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const y = rect.top + rect.height / 2; + + element.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, clientX: x, clientY: y })); + element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, clientX: x, clientY: y })); + element.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, clientX: x, clientY: y })); + element.click(); + + return { + selector, + text: String(element.innerText || element.value || "").trim().slice(0, 300), + rect: { + x: Math.round(rect.x), + y: Math.round(rect.y), + width: Math.round(rect.width), + height: Math.round(rect.height) + } + }; +} + +function typeText(selector, text, replace) { + const element = selector ? document.querySelector(selector) : document.activeElement; + if (!element) { + throw new Error(selector ? `No element matches selector: ${selector}` : "No active element"); + } + + element.scrollIntoView({ block: "center", inline: "center", behavior: "auto" }); + element.focus(); + + if (element.isContentEditable) { + if (replace) { + element.innerText = ""; + } + document.execCommand("insertText", false, text); + } else if ("value" in element) { + if (replace) { + element.value = text; + } else { + const start = Number.isInteger(element.selectionStart) ? element.selectionStart : element.value.length; + const end = Number.isInteger(element.selectionEnd) ? element.selectionEnd : element.value.length; + element.value = `${element.value.slice(0, start)}${text}${element.value.slice(end)}`; + const cursor = start + text.length; + if (element.setSelectionRange) { + element.setSelectionRange(cursor, cursor); + } + } + element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: text })); + element.dispatchEvent(new Event("change", { bubbles: true })); + } else { + throw new Error("Target element is not editable"); + } + + return { + selector: selector || "", + tag: element.tagName.toLowerCase(), + textLength: text.length + }; +} + +function focusSelector(selector) { + const element = document.querySelector(selector); + if (!element) { + throw new Error(`No element matches selector: ${selector}`); + } + + element.scrollIntoView({ block: "center", inline: "center", behavior: "auto" }); + element.focus(); + return { + selector, + tag: element.tagName.toLowerCase() + }; +} + +function normalizeKey(input) { + const aliases = { + escape: ["Escape", "Escape", 27], + esc: ["Escape", "Escape", 27], + enter: ["Enter", "Enter", 13], + tab: ["Tab", "Tab", 9], + backspace: ["Backspace", "Backspace", 8], + delete: ["Delete", "Delete", 46], + arrowup: ["ArrowUp", "ArrowUp", 38], + arrowdown: ["ArrowDown", "ArrowDown", 40], + arrowleft: ["ArrowLeft", "ArrowLeft", 37], + arrowright: ["ArrowRight", "ArrowRight", 39], + home: ["Home", "Home", 36], + end: ["End", "End", 35], + pageup: ["PageUp", "PageUp", 33], + pagedown: ["PageDown", "PageDown", 34], + space: [" ", "Space", 32] + }; + + const lower = input.toLowerCase(); + if (aliases[lower]) { + const [key, code, keyCode] = aliases[lower]; + return { key, code, keyCode, text: key.length === 1 ? key : "" }; + } + + if (input.length === 1) { + const keyCode = input.toUpperCase().charCodeAt(0); + return { key: input, code: `Key${input.toUpperCase()}`, keyCode, text: input }; + } + + return { key: input, code: input, keyCode: 0, text: "" }; +} + +function unwrapRemoteObject(remoteObject) { + if (!remoteObject) { + return null; + } + if (Object.prototype.hasOwnProperty.call(remoteObject, "value")) { + return remoteObject.value; + } + if (remoteObject.unserializableValue) { + return remoteObject.unserializableValue; + } + return remoteObject.description || null; +} + +function formatException(exceptionDetails) { + if (exceptionDetails.exception) { + return unwrapRemoteObject(exceptionDetails.exception) || exceptionDetails.exception.description || "Evaluation failed"; + } + return exceptionDetails.text || "Evaluation failed"; +} + +function sendSocket(message) { + if (!socket || socket.readyState !== WebSocket.OPEN) { + return false; + } + try { + socket.send(JSON.stringify(message)); + return true; + } catch (error) { + persistState({ lastError: errorMessage(error), connected: false }).catch(reportError); + if (state.sharing && !intentionallyClosed) { + scheduleReconnect(); + } + return false; + } +} + +function buildShareUrl(relayUrl, sessionId, agentToken) { + const url = new URL(relayUrl); + const prefix = url.pathname.replace(/\/+$/, ""); + url.pathname = `${prefix}/share/${encodeURIComponent(sessionId)}`; + url.search = ""; + url.hash = `agent=${encodeURIComponent(agentToken)}`; + return url.href; +} + +function buildBrowserWsUrl(relayUrl, sessionId, browserToken, agentToken) { + const url = new URL(relayUrl); + url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; + const prefix = url.pathname.replace(/\/+$/, ""); + url.pathname = `${prefix}/ws/browser/${encodeURIComponent(sessionId)}`; + url.search = `token=${encodeURIComponent(browserToken)}&agent_token=${encodeURIComponent(agentToken)}`; + url.hash = ""; + return url.href; +} + +function normalizeRelayUrl(input) { + const raw = String(input || "").trim(); + if (!raw) { + throw new Error("Relay URL is required"); + } + + const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`; + const url = new URL(withScheme); + + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("Relay URL must use http or https"); + } + + url.search = ""; + url.hash = ""; + url.pathname = url.pathname.replace(/\/+$/, ""); + return url.href.replace(/\/$/, ""); +} + +function stringParam(value) { + if (typeof value !== "string") { + return ""; + } + return value.trim().slice(0, 512); +} + +function randomHex(lengthBytes) { + const bytes = new Uint8Array(lengthBytes); + crypto.getRandomValues(bytes); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +function clampNumber(value, min, max) { + const number = Number(value); + if (!Number.isFinite(number)) { + return min; + } + return Math.min(Math.max(number, min), max); +} + +function chromeCall(fn, context, ...args) { + return new Promise((resolve, reject) => { + try { + fn.call(context, ...args, (result) => { + const error = chrome.runtime.lastError; + if (error) { + reject(new Error(error.message)); + } else { + resolve(result); + } + }); + } catch (error) { + reject(error); + } + }); +} + +function reportError(error) { + persistState({ lastError: errorMessage(error), status: "error" }).catch(() => { + // Avoid recursive error reporting. + }); +} + +function errorMessage(error) { + if (!error) { + return "Unknown error"; + } + if (error.message) { + return error.message; + } + return String(error); +} diff --git a/extension/edge-share-crx/empty.html b/extension/edge-share-crx/empty.html new file mode 100644 index 0000000..d3a3d8a --- /dev/null +++ b/extension/edge-share-crx/empty.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/extension/edge-share-crx/form.css b/extension/edge-share-crx/form.css new file mode 100644 index 0000000..6d78133 --- /dev/null +++ b/extension/edge-share-crx/form.css @@ -0,0 +1,53 @@ +form { + display: flex; + flex-direction: column; + gap: 10px; +} + +form h1 { + text-align: center; + margin-bottom: 15px; +} + +form label { + font-weight: bold; +} + +form input[type="text"], select { + padding: 5px; + border: 1px solid #ccc; + border-radius: 4px; +} + +form input[type="checkbox"] { + padding-left: 16px; +} + +form button[type="submit"] { + background-color: #4CAF50; + border: none; + color: white; + padding: 10px 20px; + text-align: center; + text-decoration: none; + display: inline-block; + font-size: 16px; + margin: 4px 2px; + cursor: pointer; + border-radius: 4px; + transition: background-color 0.2s ease-in-out; +} + +form button:hover { + background-color: #45A049; +} + +form button[type="submit"]:disabled { + background-color: #ccc; + color: #666; + cursor: not-allowed; +} + +form .note.error { + color: darkred; +} diff --git a/extension/edge-share-crx/form.js b/extension/edge-share-crx/form.js new file mode 100644 index 0000000..1213a7e --- /dev/null +++ b/extension/edge-share-crx/form.js @@ -0,0 +1,7168 @@ +import { d as defaultSettings, l as loadSettings, s as storeSettings } from "./settings.js"; +(function polyfill() { + const relList = document.createElement("link").relList; + if (relList && relList.supports && relList.supports("modulepreload")) { + return; + } + for (const link of document.querySelectorAll('link[rel="modulepreload"]')) { + processPreload(link); + } + new MutationObserver((mutations) => { + for (const mutation of mutations) { + if (mutation.type !== "childList") { + continue; + } + for (const node of mutation.addedNodes) { + if (node.tagName === "LINK" && node.rel === "modulepreload") + processPreload(node); + } + } + }).observe(document, { childList: true, subtree: true }); + function getFetchOpts(link) { + const fetchOpts = {}; + if (link.integrity) fetchOpts.integrity = link.integrity; + if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy; + if (link.crossOrigin === "use-credentials") + fetchOpts.credentials = "include"; + else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit"; + else fetchOpts.credentials = "same-origin"; + return fetchOpts; + } + function processPreload(link) { + if (link.ep) + return; + link.ep = true; + const fetchOpts = getFetchOpts(link); + fetch(link.href, fetchOpts); + } +})(); +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} +var jsxRuntime = { exports: {} }; +var reactJsxRuntime_production_min = {}; +var react = { exports: {} }; +var react_production_min = {}; +/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var hasRequiredReact_production_min; +function requireReact_production_min() { + if (hasRequiredReact_production_min) return react_production_min; + hasRequiredReact_production_min = 1; + var l = Symbol.for("react.element"), n = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), q = Symbol.for("react.strict_mode"), r = Symbol.for("react.profiler"), t = Symbol.for("react.provider"), u = Symbol.for("react.context"), v = Symbol.for("react.forward_ref"), w = Symbol.for("react.suspense"), x = Symbol.for("react.memo"), y = Symbol.for("react.lazy"), z = Symbol.iterator; + function A(a) { + if (null === a || "object" !== typeof a) return null; + a = z && a[z] || a["@@iterator"]; + return "function" === typeof a ? a : null; + } + var B = { isMounted: function() { + return false; + }, enqueueForceUpdate: function() { + }, enqueueReplaceState: function() { + }, enqueueSetState: function() { + } }, C = Object.assign, D = {}; + function E(a, b, e) { + this.props = a; + this.context = b; + this.refs = D; + this.updater = e || B; + } + E.prototype.isReactComponent = {}; + E.prototype.setState = function(a, b) { + if ("object" !== typeof a && "function" !== typeof a && null != a) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); + this.updater.enqueueSetState(this, a, b, "setState"); + }; + E.prototype.forceUpdate = function(a) { + this.updater.enqueueForceUpdate(this, a, "forceUpdate"); + }; + function F() { + } + F.prototype = E.prototype; + function G(a, b, e) { + this.props = a; + this.context = b; + this.refs = D; + this.updater = e || B; + } + var H = G.prototype = new F(); + H.constructor = G; + C(H, E.prototype); + H.isPureReactComponent = true; + var I = Array.isArray, J = Object.prototype.hasOwnProperty, K = { current: null }, L = { key: true, ref: true, __self: true, __source: true }; + function M(a, b, e) { + var d, c = {}, k = null, h = null; + if (null != b) for (d in void 0 !== b.ref && (h = b.ref), void 0 !== b.key && (k = "" + b.key), b) J.call(b, d) && !L.hasOwnProperty(d) && (c[d] = b[d]); + var g = arguments.length - 2; + if (1 === g) c.children = e; + else if (1 < g) { + for (var f = Array(g), m = 0; m < g; m++) f[m] = arguments[m + 2]; + c.children = f; + } + if (a && a.defaultProps) for (d in g = a.defaultProps, g) void 0 === c[d] && (c[d] = g[d]); + return { $$typeof: l, type: a, key: k, ref: h, props: c, _owner: K.current }; + } + function N(a, b) { + return { $$typeof: l, type: a.type, key: b, ref: a.ref, props: a.props, _owner: a._owner }; + } + function O(a) { + return "object" === typeof a && null !== a && a.$$typeof === l; + } + function escape(a) { + var b = { "=": "=0", ":": "=2" }; + return "$" + a.replace(/[=:]/g, function(a2) { + return b[a2]; + }); + } + var P = /\/+/g; + function Q(a, b) { + return "object" === typeof a && null !== a && null != a.key ? escape("" + a.key) : b.toString(36); + } + function R(a, b, e, d, c) { + var k = typeof a; + if ("undefined" === k || "boolean" === k) a = null; + var h = false; + if (null === a) h = true; + else switch (k) { + case "string": + case "number": + h = true; + break; + case "object": + switch (a.$$typeof) { + case l: + case n: + h = true; + } + } + if (h) return h = a, c = c(h), a = "" === d ? "." + Q(h, 0) : d, I(c) ? (e = "", null != a && (e = a.replace(P, "$&/") + "/"), R(c, b, e, "", function(a2) { + return a2; + })) : null != c && (O(c) && (c = N(c, e + (!c.key || h && h.key === c.key ? "" : ("" + c.key).replace(P, "$&/") + "/") + a)), b.push(c)), 1; + h = 0; + d = "" === d ? "." : d + ":"; + if (I(a)) for (var g = 0; g < a.length; g++) { + k = a[g]; + var f = d + Q(k, g); + h += R(k, b, e, f, c); + } + else if (f = A(a), "function" === typeof f) for (a = f.call(a), g = 0; !(k = a.next()).done; ) k = k.value, f = d + Q(k, g++), h += R(k, b, e, f, c); + else if ("object" === k) throw b = String(a), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b ? "object with keys {" + Object.keys(a).join(", ") + "}" : b) + "). If you meant to render a collection of children, use an array instead."); + return h; + } + function S(a, b, e) { + if (null == a) return a; + var d = [], c = 0; + R(a, d, "", "", function(a2) { + return b.call(e, a2, c++); + }); + return d; + } + function T(a) { + if (-1 === a._status) { + var b = a._result; + b = b(); + b.then(function(b2) { + if (0 === a._status || -1 === a._status) a._status = 1, a._result = b2; + }, function(b2) { + if (0 === a._status || -1 === a._status) a._status = 2, a._result = b2; + }); + -1 === a._status && (a._status = 0, a._result = b); + } + if (1 === a._status) return a._result.default; + throw a._result; + } + var U = { current: null }, V = { transition: null }, W = { ReactCurrentDispatcher: U, ReactCurrentBatchConfig: V, ReactCurrentOwner: K }; + function X() { + throw Error("act(...) is not supported in production builds of React."); + } + react_production_min.Children = { map: S, forEach: function(a, b, e) { + S(a, function() { + b.apply(this, arguments); + }, e); + }, count: function(a) { + var b = 0; + S(a, function() { + b++; + }); + return b; + }, toArray: function(a) { + return S(a, function(a2) { + return a2; + }) || []; + }, only: function(a) { + if (!O(a)) throw Error("React.Children.only expected to receive a single React element child."); + return a; + } }; + react_production_min.Component = E; + react_production_min.Fragment = p; + react_production_min.Profiler = r; + react_production_min.PureComponent = G; + react_production_min.StrictMode = q; + react_production_min.Suspense = w; + react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W; + react_production_min.act = X; + react_production_min.cloneElement = function(a, b, e) { + if (null === a || void 0 === a) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a + "."); + var d = C({}, a.props), c = a.key, k = a.ref, h = a._owner; + if (null != b) { + void 0 !== b.ref && (k = b.ref, h = K.current); + void 0 !== b.key && (c = "" + b.key); + if (a.type && a.type.defaultProps) var g = a.type.defaultProps; + for (f in b) J.call(b, f) && !L.hasOwnProperty(f) && (d[f] = void 0 === b[f] && void 0 !== g ? g[f] : b[f]); + } + var f = arguments.length - 2; + if (1 === f) d.children = e; + else if (1 < f) { + g = Array(f); + for (var m = 0; m < f; m++) g[m] = arguments[m + 2]; + d.children = g; + } + return { $$typeof: l, type: a.type, key: c, ref: k, props: d, _owner: h }; + }; + react_production_min.createContext = function(a) { + a = { $$typeof: u, _currentValue: a, _currentValue2: a, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null }; + a.Provider = { $$typeof: t, _context: a }; + return a.Consumer = a; + }; + react_production_min.createElement = M; + react_production_min.createFactory = function(a) { + var b = M.bind(null, a); + b.type = a; + return b; + }; + react_production_min.createRef = function() { + return { current: null }; + }; + react_production_min.forwardRef = function(a) { + return { $$typeof: v, render: a }; + }; + react_production_min.isValidElement = O; + react_production_min.lazy = function(a) { + return { $$typeof: y, _payload: { _status: -1, _result: a }, _init: T }; + }; + react_production_min.memo = function(a, b) { + return { $$typeof: x, type: a, compare: void 0 === b ? null : b }; + }; + react_production_min.startTransition = function(a) { + var b = V.transition; + V.transition = {}; + try { + a(); + } finally { + V.transition = b; + } + }; + react_production_min.unstable_act = X; + react_production_min.useCallback = function(a, b) { + return U.current.useCallback(a, b); + }; + react_production_min.useContext = function(a) { + return U.current.useContext(a); + }; + react_production_min.useDebugValue = function() { + }; + react_production_min.useDeferredValue = function(a) { + return U.current.useDeferredValue(a); + }; + react_production_min.useEffect = function(a, b) { + return U.current.useEffect(a, b); + }; + react_production_min.useId = function() { + return U.current.useId(); + }; + react_production_min.useImperativeHandle = function(a, b, e) { + return U.current.useImperativeHandle(a, b, e); + }; + react_production_min.useInsertionEffect = function(a, b) { + return U.current.useInsertionEffect(a, b); + }; + react_production_min.useLayoutEffect = function(a, b) { + return U.current.useLayoutEffect(a, b); + }; + react_production_min.useMemo = function(a, b) { + return U.current.useMemo(a, b); + }; + react_production_min.useReducer = function(a, b, e) { + return U.current.useReducer(a, b, e); + }; + react_production_min.useRef = function(a) { + return U.current.useRef(a); + }; + react_production_min.useState = function(a) { + return U.current.useState(a); + }; + react_production_min.useSyncExternalStore = function(a, b, e) { + return U.current.useSyncExternalStore(a, b, e); + }; + react_production_min.useTransition = function() { + return U.current.useTransition(); + }; + react_production_min.version = "18.3.1"; + return react_production_min; +} +var hasRequiredReact; +function requireReact() { + if (hasRequiredReact) return react.exports; + hasRequiredReact = 1; + { + react.exports = requireReact_production_min(); + } + return react.exports; +} +/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var hasRequiredReactJsxRuntime_production_min; +function requireReactJsxRuntime_production_min() { + if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min; + hasRequiredReactJsxRuntime_production_min = 1; + var f = requireReact(), k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true }; + function q(c, a, g) { + var b, d = {}, e = null, h = null; + void 0 !== g && (e = "" + g); + void 0 !== a.key && (e = "" + a.key); + void 0 !== a.ref && (h = a.ref); + for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); + if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); + return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current }; + } + reactJsxRuntime_production_min.Fragment = l; + reactJsxRuntime_production_min.jsx = q; + reactJsxRuntime_production_min.jsxs = q; + return reactJsxRuntime_production_min; +} +var hasRequiredJsxRuntime; +function requireJsxRuntime() { + if (hasRequiredJsxRuntime) return jsxRuntime.exports; + hasRequiredJsxRuntime = 1; + { + jsxRuntime.exports = requireReactJsxRuntime_production_min(); + } + return jsxRuntime.exports; +} +var jsxRuntimeExports = requireJsxRuntime(); +var reactExports = requireReact(); +const React = /* @__PURE__ */ getDefaultExportFromCjs(reactExports); +var client = {}; +var reactDom = { exports: {} }; +var reactDom_production_min = {}; +var scheduler = { exports: {} }; +var scheduler_production_min = {}; +/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var hasRequiredScheduler_production_min; +function requireScheduler_production_min() { + if (hasRequiredScheduler_production_min) return scheduler_production_min; + hasRequiredScheduler_production_min = 1; + (function(exports) { + function f(a, b) { + var c = a.length; + a.push(b); + a: for (; 0 < c; ) { + var d = c - 1 >>> 1, e = a[d]; + if (0 < g(e, b)) a[d] = b, a[c] = e, c = d; + else break a; + } + } + function h(a) { + return 0 === a.length ? null : a[0]; + } + function k(a) { + if (0 === a.length) return null; + var b = a[0], c = a.pop(); + if (c !== b) { + a[0] = c; + a: for (var d = 0, e = a.length, w = e >>> 1; d < w; ) { + var m = 2 * (d + 1) - 1, C = a[m], n = m + 1, x = a[n]; + if (0 > g(C, c)) n < e && 0 > g(x, C) ? (a[d] = x, a[n] = c, d = n) : (a[d] = C, a[m] = c, d = m); + else if (n < e && 0 > g(x, c)) a[d] = x, a[n] = c, d = n; + else break a; + } + } + return b; + } + function g(a, b) { + var c = a.sortIndex - b.sortIndex; + return 0 !== c ? c : a.id - b.id; + } + if ("object" === typeof performance && "function" === typeof performance.now) { + var l = performance; + exports.unstable_now = function() { + return l.now(); + }; + } else { + var p = Date, q = p.now(); + exports.unstable_now = function() { + return p.now() - q; + }; + } + var r = [], t = [], u = 1, v = null, y = 3, z = false, A = false, B = false, D = "function" === typeof setTimeout ? setTimeout : null, E = "function" === typeof clearTimeout ? clearTimeout : null, F = "undefined" !== typeof setImmediate ? setImmediate : null; + "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling); + function G(a) { + for (var b = h(t); null !== b; ) { + if (null === b.callback) k(t); + else if (b.startTime <= a) k(t), b.sortIndex = b.expirationTime, f(r, b); + else break; + b = h(t); + } + } + function H(a) { + B = false; + G(a); + if (!A) if (null !== h(r)) A = true, I(J); + else { + var b = h(t); + null !== b && K(H, b.startTime - a); + } + } + function J(a, b) { + A = false; + B && (B = false, E(L), L = -1); + z = true; + var c = y; + try { + G(b); + for (v = h(r); null !== v && (!(v.expirationTime > b) || a && !M()); ) { + var d = v.callback; + if ("function" === typeof d) { + v.callback = null; + y = v.priorityLevel; + var e = d(v.expirationTime <= b); + b = exports.unstable_now(); + "function" === typeof e ? v.callback = e : v === h(r) && k(r); + G(b); + } else k(r); + v = h(r); + } + if (null !== v) var w = true; + else { + var m = h(t); + null !== m && K(H, m.startTime - b); + w = false; + } + return w; + } finally { + v = null, y = c, z = false; + } + } + var N = false, O = null, L = -1, P = 5, Q = -1; + function M() { + return exports.unstable_now() - Q < P ? false : true; + } + function R() { + if (null !== O) { + var a = exports.unstable_now(); + Q = a; + var b = true; + try { + b = O(true, a); + } finally { + b ? S() : (N = false, O = null); + } + } else N = false; + } + var S; + if ("function" === typeof F) S = function() { + F(R); + }; + else if ("undefined" !== typeof MessageChannel) { + var T = new MessageChannel(), U = T.port2; + T.port1.onmessage = R; + S = function() { + U.postMessage(null); + }; + } else S = function() { + D(R, 0); + }; + function I(a) { + O = a; + N || (N = true, S()); + } + function K(a, b) { + L = D(function() { + a(exports.unstable_now()); + }, b); + } + exports.unstable_IdlePriority = 5; + exports.unstable_ImmediatePriority = 1; + exports.unstable_LowPriority = 4; + exports.unstable_NormalPriority = 3; + exports.unstable_Profiling = null; + exports.unstable_UserBlockingPriority = 2; + exports.unstable_cancelCallback = function(a) { + a.callback = null; + }; + exports.unstable_continueExecution = function() { + A || z || (A = true, I(J)); + }; + exports.unstable_forceFrameRate = function(a) { + 0 > a || 125 < a ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P = 0 < a ? Math.floor(1e3 / a) : 5; + }; + exports.unstable_getCurrentPriorityLevel = function() { + return y; + }; + exports.unstable_getFirstCallbackNode = function() { + return h(r); + }; + exports.unstable_next = function(a) { + switch (y) { + case 1: + case 2: + case 3: + var b = 3; + break; + default: + b = y; + } + var c = y; + y = b; + try { + return a(); + } finally { + y = c; + } + }; + exports.unstable_pauseExecution = function() { + }; + exports.unstable_requestPaint = function() { + }; + exports.unstable_runWithPriority = function(a, b) { + switch (a) { + case 1: + case 2: + case 3: + case 4: + case 5: + break; + default: + a = 3; + } + var c = y; + y = a; + try { + return b(); + } finally { + y = c; + } + }; + exports.unstable_scheduleCallback = function(a, b, c) { + var d = exports.unstable_now(); + "object" === typeof c && null !== c ? (c = c.delay, c = "number" === typeof c && 0 < c ? d + c : d) : c = d; + switch (a) { + case 1: + var e = -1; + break; + case 2: + e = 250; + break; + case 5: + e = 1073741823; + break; + case 4: + e = 1e4; + break; + default: + e = 5e3; + } + e = c + e; + a = { id: u++, callback: b, priorityLevel: a, startTime: c, expirationTime: e, sortIndex: -1 }; + c > d ? (a.sortIndex = c, f(t, a), null === h(r) && a === h(t) && (B ? (E(L), L = -1) : B = true, K(H, c - d))) : (a.sortIndex = e, f(r, a), A || z || (A = true, I(J))); + return a; + }; + exports.unstable_shouldYield = M; + exports.unstable_wrapCallback = function(a) { + var b = y; + return function() { + var c = y; + y = b; + try { + return a.apply(this, arguments); + } finally { + y = c; + } + }; + }; + })(scheduler_production_min); + return scheduler_production_min; +} +var hasRequiredScheduler; +function requireScheduler() { + if (hasRequiredScheduler) return scheduler.exports; + hasRequiredScheduler = 1; + { + scheduler.exports = requireScheduler_production_min(); + } + return scheduler.exports; +} +/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var hasRequiredReactDom_production_min; +function requireReactDom_production_min() { + if (hasRequiredReactDom_production_min) return reactDom_production_min; + hasRequiredReactDom_production_min = 1; + var aa = requireReact(), ca = requireScheduler(); + function p(a) { + for (var b = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, c = 1; c < arguments.length; c++) b += "&args[]=" + encodeURIComponent(arguments[c]); + return "Minified React error #" + a + "; visit " + b + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; + } + var da = /* @__PURE__ */ new Set(), ea = {}; + function fa(a, b) { + ha(a, b); + ha(a + "Capture", b); + } + function ha(a, b) { + ea[a] = b; + for (a = 0; a < b.length; a++) da.add(b[a]); + } + var ia = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), ja = Object.prototype.hasOwnProperty, ka = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, la = {}, ma = {}; + function oa(a) { + if (ja.call(ma, a)) return true; + if (ja.call(la, a)) return false; + if (ka.test(a)) return ma[a] = true; + la[a] = true; + return false; + } + function pa(a, b, c, d) { + if (null !== c && 0 === c.type) return false; + switch (typeof b) { + case "function": + case "symbol": + return true; + case "boolean": + if (d) return false; + if (null !== c) return !c.acceptsBooleans; + a = a.toLowerCase().slice(0, 5); + return "data-" !== a && "aria-" !== a; + default: + return false; + } + } + function qa(a, b, c, d) { + if (null === b || "undefined" === typeof b || pa(a, b, c, d)) return true; + if (d) return false; + if (null !== c) switch (c.type) { + case 3: + return !b; + case 4: + return false === b; + case 5: + return isNaN(b); + case 6: + return isNaN(b) || 1 > b; + } + return false; + } + function v(a, b, c, d, e, f, g) { + this.acceptsBooleans = 2 === b || 3 === b || 4 === b; + this.attributeName = d; + this.attributeNamespace = e; + this.mustUseProperty = c; + this.propertyName = a; + this.type = b; + this.sanitizeURL = f; + this.removeEmptyString = g; + } + var z = {}; + "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a) { + z[a] = new v(a, 0, false, a, null, false, false); + }); + [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a) { + var b = a[0]; + z[b] = new v(b, 1, false, a[1], null, false, false); + }); + ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a) { + z[a] = new v(a, 2, false, a.toLowerCase(), null, false, false); + }); + ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a) { + z[a] = new v(a, 2, false, a, null, false, false); + }); + "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a) { + z[a] = new v(a, 3, false, a.toLowerCase(), null, false, false); + }); + ["checked", "multiple", "muted", "selected"].forEach(function(a) { + z[a] = new v(a, 3, true, a, null, false, false); + }); + ["capture", "download"].forEach(function(a) { + z[a] = new v(a, 4, false, a, null, false, false); + }); + ["cols", "rows", "size", "span"].forEach(function(a) { + z[a] = new v(a, 6, false, a, null, false, false); + }); + ["rowSpan", "start"].forEach(function(a) { + z[a] = new v(a, 5, false, a.toLowerCase(), null, false, false); + }); + var ra = /[\-:]([a-z])/g; + function sa(a) { + return a[1].toUpperCase(); + } + "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a) { + var b = a.replace( + ra, + sa + ); + z[b] = new v(b, 1, false, a, null, false, false); + }); + "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a) { + var b = a.replace(ra, sa); + z[b] = new v(b, 1, false, a, "http://www.w3.org/1999/xlink", false, false); + }); + ["xml:base", "xml:lang", "xml:space"].forEach(function(a) { + var b = a.replace(ra, sa); + z[b] = new v(b, 1, false, a, "http://www.w3.org/XML/1998/namespace", false, false); + }); + ["tabIndex", "crossOrigin"].forEach(function(a) { + z[a] = new v(a, 1, false, a.toLowerCase(), null, false, false); + }); + z.xlinkHref = new v("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false); + ["src", "href", "action", "formAction"].forEach(function(a) { + z[a] = new v(a, 1, false, a.toLowerCase(), null, true, true); + }); + function ta(a, b, c, d) { + var e = z.hasOwnProperty(b) ? z[b] : null; + if (null !== e ? 0 !== e.type : d || !(2 < b.length) || "o" !== b[0] && "O" !== b[0] || "n" !== b[1] && "N" !== b[1]) qa(b, c, e, d) && (c = null), d || null === e ? oa(b) && (null === c ? a.removeAttribute(b) : a.setAttribute(b, "" + c)) : e.mustUseProperty ? a[e.propertyName] = null === c ? 3 === e.type ? false : "" : c : (b = e.attributeName, d = e.attributeNamespace, null === c ? a.removeAttribute(b) : (e = e.type, c = 3 === e || 4 === e && true === c ? "" : "" + c, d ? a.setAttributeNS(d, b, c) : a.setAttribute(b, c))); + } + var ua = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, va = Symbol.for("react.element"), wa = Symbol.for("react.portal"), ya = Symbol.for("react.fragment"), za = Symbol.for("react.strict_mode"), Aa = Symbol.for("react.profiler"), Ba = Symbol.for("react.provider"), Ca = Symbol.for("react.context"), Da = Symbol.for("react.forward_ref"), Ea = Symbol.for("react.suspense"), Fa = Symbol.for("react.suspense_list"), Ga = Symbol.for("react.memo"), Ha = Symbol.for("react.lazy"); + var Ia = Symbol.for("react.offscreen"); + var Ja = Symbol.iterator; + function Ka(a) { + if (null === a || "object" !== typeof a) return null; + a = Ja && a[Ja] || a["@@iterator"]; + return "function" === typeof a ? a : null; + } + var A = Object.assign, La; + function Ma(a) { + if (void 0 === La) try { + throw Error(); + } catch (c) { + var b = c.stack.trim().match(/\n( *(at )?)/); + La = b && b[1] || ""; + } + return "\n" + La + a; + } + var Na = false; + function Oa(a, b) { + if (!a || Na) return ""; + Na = true; + var c = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + try { + if (b) if (b = function() { + throw Error(); + }, Object.defineProperty(b.prototype, "props", { set: function() { + throw Error(); + } }), "object" === typeof Reflect && Reflect.construct) { + try { + Reflect.construct(b, []); + } catch (l) { + var d = l; + } + Reflect.construct(a, [], b); + } else { + try { + b.call(); + } catch (l) { + d = l; + } + a.call(b.prototype); + } + else { + try { + throw Error(); + } catch (l) { + d = l; + } + a(); + } + } catch (l) { + if (l && d && "string" === typeof l.stack) { + for (var e = l.stack.split("\n"), f = d.stack.split("\n"), g = e.length - 1, h = f.length - 1; 1 <= g && 0 <= h && e[g] !== f[h]; ) h--; + for (; 1 <= g && 0 <= h; g--, h--) if (e[g] !== f[h]) { + if (1 !== g || 1 !== h) { + do + if (g--, h--, 0 > h || e[g] !== f[h]) { + var k = "\n" + e[g].replace(" at new ", " at "); + a.displayName && k.includes("") && (k = k.replace("", a.displayName)); + return k; + } + while (1 <= g && 0 <= h); + } + break; + } + } + } finally { + Na = false, Error.prepareStackTrace = c; + } + return (a = a ? a.displayName || a.name : "") ? Ma(a) : ""; + } + function Pa(a) { + switch (a.tag) { + case 5: + return Ma(a.type); + case 16: + return Ma("Lazy"); + case 13: + return Ma("Suspense"); + case 19: + return Ma("SuspenseList"); + case 0: + case 2: + case 15: + return a = Oa(a.type, false), a; + case 11: + return a = Oa(a.type.render, false), a; + case 1: + return a = Oa(a.type, true), a; + default: + return ""; + } + } + function Qa(a) { + if (null == a) return null; + if ("function" === typeof a) return a.displayName || a.name || null; + if ("string" === typeof a) return a; + switch (a) { + case ya: + return "Fragment"; + case wa: + return "Portal"; + case Aa: + return "Profiler"; + case za: + return "StrictMode"; + case Ea: + return "Suspense"; + case Fa: + return "SuspenseList"; + } + if ("object" === typeof a) switch (a.$$typeof) { + case Ca: + return (a.displayName || "Context") + ".Consumer"; + case Ba: + return (a._context.displayName || "Context") + ".Provider"; + case Da: + var b = a.render; + a = a.displayName; + a || (a = b.displayName || b.name || "", a = "" !== a ? "ForwardRef(" + a + ")" : "ForwardRef"); + return a; + case Ga: + return b = a.displayName || null, null !== b ? b : Qa(a.type) || "Memo"; + case Ha: + b = a._payload; + a = a._init; + try { + return Qa(a(b)); + } catch (c) { + } + } + return null; + } + function Ra(a) { + var b = a.type; + switch (a.tag) { + case 24: + return "Cache"; + case 9: + return (b.displayName || "Context") + ".Consumer"; + case 10: + return (b._context.displayName || "Context") + ".Provider"; + case 18: + return "DehydratedFragment"; + case 11: + return a = b.render, a = a.displayName || a.name || "", b.displayName || ("" !== a ? "ForwardRef(" + a + ")" : "ForwardRef"); + case 7: + return "Fragment"; + case 5: + return b; + case 4: + return "Portal"; + case 3: + return "Root"; + case 6: + return "Text"; + case 16: + return Qa(b); + case 8: + return b === za ? "StrictMode" : "Mode"; + case 22: + return "Offscreen"; + case 12: + return "Profiler"; + case 21: + return "Scope"; + case 13: + return "Suspense"; + case 19: + return "SuspenseList"; + case 25: + return "TracingMarker"; + case 1: + case 0: + case 17: + case 2: + case 14: + case 15: + if ("function" === typeof b) return b.displayName || b.name || null; + if ("string" === typeof b) return b; + } + return null; + } + function Sa(a) { + switch (typeof a) { + case "boolean": + case "number": + case "string": + case "undefined": + return a; + case "object": + return a; + default: + return ""; + } + } + function Ta(a) { + var b = a.type; + return (a = a.nodeName) && "input" === a.toLowerCase() && ("checkbox" === b || "radio" === b); + } + function Ua(a) { + var b = Ta(a) ? "checked" : "value", c = Object.getOwnPropertyDescriptor(a.constructor.prototype, b), d = "" + a[b]; + if (!a.hasOwnProperty(b) && "undefined" !== typeof c && "function" === typeof c.get && "function" === typeof c.set) { + var e = c.get, f = c.set; + Object.defineProperty(a, b, { configurable: true, get: function() { + return e.call(this); + }, set: function(a2) { + d = "" + a2; + f.call(this, a2); + } }); + Object.defineProperty(a, b, { enumerable: c.enumerable }); + return { getValue: function() { + return d; + }, setValue: function(a2) { + d = "" + a2; + }, stopTracking: function() { + a._valueTracker = null; + delete a[b]; + } }; + } + } + function Va(a) { + a._valueTracker || (a._valueTracker = Ua(a)); + } + function Wa(a) { + if (!a) return false; + var b = a._valueTracker; + if (!b) return true; + var c = b.getValue(); + var d = ""; + a && (d = Ta(a) ? a.checked ? "true" : "false" : a.value); + a = d; + return a !== c ? (b.setValue(a), true) : false; + } + function Xa(a) { + a = a || ("undefined" !== typeof document ? document : void 0); + if ("undefined" === typeof a) return null; + try { + return a.activeElement || a.body; + } catch (b) { + return a.body; + } + } + function Ya(a, b) { + var c = b.checked; + return A({}, b, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: null != c ? c : a._wrapperState.initialChecked }); + } + function Za(a, b) { + var c = null == b.defaultValue ? "" : b.defaultValue, d = null != b.checked ? b.checked : b.defaultChecked; + c = Sa(null != b.value ? b.value : c); + a._wrapperState = { initialChecked: d, initialValue: c, controlled: "checkbox" === b.type || "radio" === b.type ? null != b.checked : null != b.value }; + } + function ab(a, b) { + b = b.checked; + null != b && ta(a, "checked", b, false); + } + function bb(a, b) { + ab(a, b); + var c = Sa(b.value), d = b.type; + if (null != c) if ("number" === d) { + if (0 === c && "" === a.value || a.value != c) a.value = "" + c; + } else a.value !== "" + c && (a.value = "" + c); + else if ("submit" === d || "reset" === d) { + a.removeAttribute("value"); + return; + } + b.hasOwnProperty("value") ? cb(a, b.type, c) : b.hasOwnProperty("defaultValue") && cb(a, b.type, Sa(b.defaultValue)); + null == b.checked && null != b.defaultChecked && (a.defaultChecked = !!b.defaultChecked); + } + function db(a, b, c) { + if (b.hasOwnProperty("value") || b.hasOwnProperty("defaultValue")) { + var d = b.type; + if (!("submit" !== d && "reset" !== d || void 0 !== b.value && null !== b.value)) return; + b = "" + a._wrapperState.initialValue; + c || b === a.value || (a.value = b); + a.defaultValue = b; + } + c = a.name; + "" !== c && (a.name = ""); + a.defaultChecked = !!a._wrapperState.initialChecked; + "" !== c && (a.name = c); + } + function cb(a, b, c) { + if ("number" !== b || Xa(a.ownerDocument) !== a) null == c ? a.defaultValue = "" + a._wrapperState.initialValue : a.defaultValue !== "" + c && (a.defaultValue = "" + c); + } + var eb = Array.isArray; + function fb(a, b, c, d) { + a = a.options; + if (b) { + b = {}; + for (var e = 0; e < c.length; e++) b["$" + c[e]] = true; + for (c = 0; c < a.length; c++) e = b.hasOwnProperty("$" + a[c].value), a[c].selected !== e && (a[c].selected = e), e && d && (a[c].defaultSelected = true); + } else { + c = "" + Sa(c); + b = null; + for (e = 0; e < a.length; e++) { + if (a[e].value === c) { + a[e].selected = true; + d && (a[e].defaultSelected = true); + return; + } + null !== b || a[e].disabled || (b = a[e]); + } + null !== b && (b.selected = true); + } + } + function gb(a, b) { + if (null != b.dangerouslySetInnerHTML) throw Error(p(91)); + return A({}, b, { value: void 0, defaultValue: void 0, children: "" + a._wrapperState.initialValue }); + } + function hb(a, b) { + var c = b.value; + if (null == c) { + c = b.children; + b = b.defaultValue; + if (null != c) { + if (null != b) throw Error(p(92)); + if (eb(c)) { + if (1 < c.length) throw Error(p(93)); + c = c[0]; + } + b = c; + } + null == b && (b = ""); + c = b; + } + a._wrapperState = { initialValue: Sa(c) }; + } + function ib(a, b) { + var c = Sa(b.value), d = Sa(b.defaultValue); + null != c && (c = "" + c, c !== a.value && (a.value = c), null == b.defaultValue && a.defaultValue !== c && (a.defaultValue = c)); + null != d && (a.defaultValue = "" + d); + } + function jb(a) { + var b = a.textContent; + b === a._wrapperState.initialValue && "" !== b && null !== b && (a.value = b); + } + function kb(a) { + switch (a) { + case "svg": + return "http://www.w3.org/2000/svg"; + case "math": + return "http://www.w3.org/1998/Math/MathML"; + default: + return "http://www.w3.org/1999/xhtml"; + } + } + function lb(a, b) { + return null == a || "http://www.w3.org/1999/xhtml" === a ? kb(b) : "http://www.w3.org/2000/svg" === a && "foreignObject" === b ? "http://www.w3.org/1999/xhtml" : a; + } + var mb, nb = function(a) { + return "undefined" !== typeof MSApp && MSApp.execUnsafeLocalFunction ? function(b, c, d, e) { + MSApp.execUnsafeLocalFunction(function() { + return a(b, c, d, e); + }); + } : a; + }(function(a, b) { + if ("http://www.w3.org/2000/svg" !== a.namespaceURI || "innerHTML" in a) a.innerHTML = b; + else { + mb = mb || document.createElement("div"); + mb.innerHTML = "" + b.valueOf().toString() + ""; + for (b = mb.firstChild; a.firstChild; ) a.removeChild(a.firstChild); + for (; b.firstChild; ) a.appendChild(b.firstChild); + } + }); + function ob(a, b) { + if (b) { + var c = a.firstChild; + if (c && c === a.lastChild && 3 === c.nodeType) { + c.nodeValue = b; + return; + } + } + a.textContent = b; + } + var pb = { + animationIterationCount: true, + aspectRatio: true, + borderImageOutset: true, + borderImageSlice: true, + borderImageWidth: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + columns: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + gridArea: true, + gridRow: true, + gridRowEnd: true, + gridRowSpan: true, + gridRowStart: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnSpan: true, + gridColumnStart: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeDasharray: true, + strokeDashoffset: true, + strokeMiterlimit: true, + strokeOpacity: true, + strokeWidth: true + }, qb = ["Webkit", "ms", "Moz", "O"]; + Object.keys(pb).forEach(function(a) { + qb.forEach(function(b) { + b = b + a.charAt(0).toUpperCase() + a.substring(1); + pb[b] = pb[a]; + }); + }); + function rb(a, b, c) { + return null == b || "boolean" === typeof b || "" === b ? "" : c || "number" !== typeof b || 0 === b || pb.hasOwnProperty(a) && pb[a] ? ("" + b).trim() : b + "px"; + } + function sb(a, b) { + a = a.style; + for (var c in b) if (b.hasOwnProperty(c)) { + var d = 0 === c.indexOf("--"), e = rb(c, b[c], d); + "float" === c && (c = "cssFloat"); + d ? a.setProperty(c, e) : a[c] = e; + } + } + var tb = A({ menuitem: true }, { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }); + function ub(a, b) { + if (b) { + if (tb[a] && (null != b.children || null != b.dangerouslySetInnerHTML)) throw Error(p(137, a)); + if (null != b.dangerouslySetInnerHTML) { + if (null != b.children) throw Error(p(60)); + if ("object" !== typeof b.dangerouslySetInnerHTML || !("__html" in b.dangerouslySetInnerHTML)) throw Error(p(61)); + } + if (null != b.style && "object" !== typeof b.style) throw Error(p(62)); + } + } + function vb(a, b) { + if (-1 === a.indexOf("-")) return "string" === typeof b.is; + switch (a) { + case "annotation-xml": + case "color-profile": + case "font-face": + case "font-face-src": + case "font-face-uri": + case "font-face-format": + case "font-face-name": + case "missing-glyph": + return false; + default: + return true; + } + } + var wb = null; + function xb(a) { + a = a.target || a.srcElement || window; + a.correspondingUseElement && (a = a.correspondingUseElement); + return 3 === a.nodeType ? a.parentNode : a; + } + var yb = null, zb = null, Ab = null; + function Bb(a) { + if (a = Cb(a)) { + if ("function" !== typeof yb) throw Error(p(280)); + var b = a.stateNode; + b && (b = Db(b), yb(a.stateNode, a.type, b)); + } + } + function Eb(a) { + zb ? Ab ? Ab.push(a) : Ab = [a] : zb = a; + } + function Fb() { + if (zb) { + var a = zb, b = Ab; + Ab = zb = null; + Bb(a); + if (b) for (a = 0; a < b.length; a++) Bb(b[a]); + } + } + function Gb(a, b) { + return a(b); + } + function Hb() { + } + var Ib = false; + function Jb(a, b, c) { + if (Ib) return a(b, c); + Ib = true; + try { + return Gb(a, b, c); + } finally { + if (Ib = false, null !== zb || null !== Ab) Hb(), Fb(); + } + } + function Kb(a, b) { + var c = a.stateNode; + if (null === c) return null; + var d = Db(c); + if (null === d) return null; + c = d[b]; + a: switch (b) { + case "onClick": + case "onClickCapture": + case "onDoubleClick": + case "onDoubleClickCapture": + case "onMouseDown": + case "onMouseDownCapture": + case "onMouseMove": + case "onMouseMoveCapture": + case "onMouseUp": + case "onMouseUpCapture": + case "onMouseEnter": + (d = !d.disabled) || (a = a.type, d = !("button" === a || "input" === a || "select" === a || "textarea" === a)); + a = !d; + break a; + default: + a = false; + } + if (a) return null; + if (c && "function" !== typeof c) throw Error(p(231, b, typeof c)); + return c; + } + var Lb = false; + if (ia) try { + var Mb = {}; + Object.defineProperty(Mb, "passive", { get: function() { + Lb = true; + } }); + window.addEventListener("test", Mb, Mb); + window.removeEventListener("test", Mb, Mb); + } catch (a) { + Lb = false; + } + function Nb(a, b, c, d, e, f, g, h, k) { + var l = Array.prototype.slice.call(arguments, 3); + try { + b.apply(c, l); + } catch (m) { + this.onError(m); + } + } + var Ob = false, Pb = null, Qb = false, Rb = null, Sb = { onError: function(a) { + Ob = true; + Pb = a; + } }; + function Tb(a, b, c, d, e, f, g, h, k) { + Ob = false; + Pb = null; + Nb.apply(Sb, arguments); + } + function Ub(a, b, c, d, e, f, g, h, k) { + Tb.apply(this, arguments); + if (Ob) { + if (Ob) { + var l = Pb; + Ob = false; + Pb = null; + } else throw Error(p(198)); + Qb || (Qb = true, Rb = l); + } + } + function Vb(a) { + var b = a, c = a; + if (a.alternate) for (; b.return; ) b = b.return; + else { + a = b; + do + b = a, 0 !== (b.flags & 4098) && (c = b.return), a = b.return; + while (a); + } + return 3 === b.tag ? c : null; + } + function Wb(a) { + if (13 === a.tag) { + var b = a.memoizedState; + null === b && (a = a.alternate, null !== a && (b = a.memoizedState)); + if (null !== b) return b.dehydrated; + } + return null; + } + function Xb(a) { + if (Vb(a) !== a) throw Error(p(188)); + } + function Yb(a) { + var b = a.alternate; + if (!b) { + b = Vb(a); + if (null === b) throw Error(p(188)); + return b !== a ? null : a; + } + for (var c = a, d = b; ; ) { + var e = c.return; + if (null === e) break; + var f = e.alternate; + if (null === f) { + d = e.return; + if (null !== d) { + c = d; + continue; + } + break; + } + if (e.child === f.child) { + for (f = e.child; f; ) { + if (f === c) return Xb(e), a; + if (f === d) return Xb(e), b; + f = f.sibling; + } + throw Error(p(188)); + } + if (c.return !== d.return) c = e, d = f; + else { + for (var g = false, h = e.child; h; ) { + if (h === c) { + g = true; + c = e; + d = f; + break; + } + if (h === d) { + g = true; + d = e; + c = f; + break; + } + h = h.sibling; + } + if (!g) { + for (h = f.child; h; ) { + if (h === c) { + g = true; + c = f; + d = e; + break; + } + if (h === d) { + g = true; + d = f; + c = e; + break; + } + h = h.sibling; + } + if (!g) throw Error(p(189)); + } + } + if (c.alternate !== d) throw Error(p(190)); + } + if (3 !== c.tag) throw Error(p(188)); + return c.stateNode.current === c ? a : b; + } + function Zb(a) { + a = Yb(a); + return null !== a ? $b(a) : null; + } + function $b(a) { + if (5 === a.tag || 6 === a.tag) return a; + for (a = a.child; null !== a; ) { + var b = $b(a); + if (null !== b) return b; + a = a.sibling; + } + return null; + } + var ac = ca.unstable_scheduleCallback, bc = ca.unstable_cancelCallback, cc = ca.unstable_shouldYield, dc = ca.unstable_requestPaint, B = ca.unstable_now, ec = ca.unstable_getCurrentPriorityLevel, fc = ca.unstable_ImmediatePriority, gc = ca.unstable_UserBlockingPriority, hc = ca.unstable_NormalPriority, ic = ca.unstable_LowPriority, jc = ca.unstable_IdlePriority, kc = null, lc = null; + function mc(a) { + if (lc && "function" === typeof lc.onCommitFiberRoot) try { + lc.onCommitFiberRoot(kc, a, void 0, 128 === (a.current.flags & 128)); + } catch (b) { + } + } + var oc = Math.clz32 ? Math.clz32 : nc, pc = Math.log, qc = Math.LN2; + function nc(a) { + a >>>= 0; + return 0 === a ? 32 : 31 - (pc(a) / qc | 0) | 0; + } + var rc = 64, sc = 4194304; + function tc(a) { + switch (a & -a) { + case 1: + return 1; + case 2: + return 2; + case 4: + return 4; + case 8: + return 8; + case 16: + return 16; + case 32: + return 32; + case 64: + case 128: + case 256: + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + case 16384: + case 32768: + case 65536: + case 131072: + case 262144: + case 524288: + case 1048576: + case 2097152: + return a & 4194240; + case 4194304: + case 8388608: + case 16777216: + case 33554432: + case 67108864: + return a & 130023424; + case 134217728: + return 134217728; + case 268435456: + return 268435456; + case 536870912: + return 536870912; + case 1073741824: + return 1073741824; + default: + return a; + } + } + function uc(a, b) { + var c = a.pendingLanes; + if (0 === c) return 0; + var d = 0, e = a.suspendedLanes, f = a.pingedLanes, g = c & 268435455; + if (0 !== g) { + var h = g & ~e; + 0 !== h ? d = tc(h) : (f &= g, 0 !== f && (d = tc(f))); + } else g = c & ~e, 0 !== g ? d = tc(g) : 0 !== f && (d = tc(f)); + if (0 === d) return 0; + if (0 !== b && b !== d && 0 === (b & e) && (e = d & -d, f = b & -b, e >= f || 16 === e && 0 !== (f & 4194240))) return b; + 0 !== (d & 4) && (d |= c & 16); + b = a.entangledLanes; + if (0 !== b) for (a = a.entanglements, b &= d; 0 < b; ) c = 31 - oc(b), e = 1 << c, d |= a[c], b &= ~e; + return d; + } + function vc(a, b) { + switch (a) { + case 1: + case 2: + case 4: + return b + 250; + case 8: + case 16: + case 32: + case 64: + case 128: + case 256: + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + case 16384: + case 32768: + case 65536: + case 131072: + case 262144: + case 524288: + case 1048576: + case 2097152: + return b + 5e3; + case 4194304: + case 8388608: + case 16777216: + case 33554432: + case 67108864: + return -1; + case 134217728: + case 268435456: + case 536870912: + case 1073741824: + return -1; + default: + return -1; + } + } + function wc(a, b) { + for (var c = a.suspendedLanes, d = a.pingedLanes, e = a.expirationTimes, f = a.pendingLanes; 0 < f; ) { + var g = 31 - oc(f), h = 1 << g, k = e[g]; + if (-1 === k) { + if (0 === (h & c) || 0 !== (h & d)) e[g] = vc(h, b); + } else k <= b && (a.expiredLanes |= h); + f &= ~h; + } + } + function xc(a) { + a = a.pendingLanes & -1073741825; + return 0 !== a ? a : a & 1073741824 ? 1073741824 : 0; + } + function yc() { + var a = rc; + rc <<= 1; + 0 === (rc & 4194240) && (rc = 64); + return a; + } + function zc(a) { + for (var b = [], c = 0; 31 > c; c++) b.push(a); + return b; + } + function Ac(a, b, c) { + a.pendingLanes |= b; + 536870912 !== b && (a.suspendedLanes = 0, a.pingedLanes = 0); + a = a.eventTimes; + b = 31 - oc(b); + a[b] = c; + } + function Bc(a, b) { + var c = a.pendingLanes & ~b; + a.pendingLanes = b; + a.suspendedLanes = 0; + a.pingedLanes = 0; + a.expiredLanes &= b; + a.mutableReadLanes &= b; + a.entangledLanes &= b; + b = a.entanglements; + var d = a.eventTimes; + for (a = a.expirationTimes; 0 < c; ) { + var e = 31 - oc(c), f = 1 << e; + b[e] = 0; + d[e] = -1; + a[e] = -1; + c &= ~f; + } + } + function Cc(a, b) { + var c = a.entangledLanes |= b; + for (a = a.entanglements; c; ) { + var d = 31 - oc(c), e = 1 << d; + e & b | a[d] & b && (a[d] |= b); + c &= ~e; + } + } + var C = 0; + function Dc(a) { + a &= -a; + return 1 < a ? 4 < a ? 0 !== (a & 268435455) ? 16 : 536870912 : 4 : 1; + } + var Ec, Fc, Gc, Hc, Ic, Jc = false, Kc = [], Lc = null, Mc = null, Nc = null, Oc = /* @__PURE__ */ new Map(), Pc = /* @__PURE__ */ new Map(), Qc = [], Rc = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" "); + function Sc(a, b) { + switch (a) { + case "focusin": + case "focusout": + Lc = null; + break; + case "dragenter": + case "dragleave": + Mc = null; + break; + case "mouseover": + case "mouseout": + Nc = null; + break; + case "pointerover": + case "pointerout": + Oc.delete(b.pointerId); + break; + case "gotpointercapture": + case "lostpointercapture": + Pc.delete(b.pointerId); + } + } + function Tc(a, b, c, d, e, f) { + if (null === a || a.nativeEvent !== f) return a = { blockedOn: b, domEventName: c, eventSystemFlags: d, nativeEvent: f, targetContainers: [e] }, null !== b && (b = Cb(b), null !== b && Fc(b)), a; + a.eventSystemFlags |= d; + b = a.targetContainers; + null !== e && -1 === b.indexOf(e) && b.push(e); + return a; + } + function Uc(a, b, c, d, e) { + switch (b) { + case "focusin": + return Lc = Tc(Lc, a, b, c, d, e), true; + case "dragenter": + return Mc = Tc(Mc, a, b, c, d, e), true; + case "mouseover": + return Nc = Tc(Nc, a, b, c, d, e), true; + case "pointerover": + var f = e.pointerId; + Oc.set(f, Tc(Oc.get(f) || null, a, b, c, d, e)); + return true; + case "gotpointercapture": + return f = e.pointerId, Pc.set(f, Tc(Pc.get(f) || null, a, b, c, d, e)), true; + } + return false; + } + function Vc(a) { + var b = Wc(a.target); + if (null !== b) { + var c = Vb(b); + if (null !== c) { + if (b = c.tag, 13 === b) { + if (b = Wb(c), null !== b) { + a.blockedOn = b; + Ic(a.priority, function() { + Gc(c); + }); + return; + } + } else if (3 === b && c.stateNode.current.memoizedState.isDehydrated) { + a.blockedOn = 3 === c.tag ? c.stateNode.containerInfo : null; + return; + } + } + } + a.blockedOn = null; + } + function Xc(a) { + if (null !== a.blockedOn) return false; + for (var b = a.targetContainers; 0 < b.length; ) { + var c = Yc(a.domEventName, a.eventSystemFlags, b[0], a.nativeEvent); + if (null === c) { + c = a.nativeEvent; + var d = new c.constructor(c.type, c); + wb = d; + c.target.dispatchEvent(d); + wb = null; + } else return b = Cb(c), null !== b && Fc(b), a.blockedOn = c, false; + b.shift(); + } + return true; + } + function Zc(a, b, c) { + Xc(a) && c.delete(b); + } + function $c() { + Jc = false; + null !== Lc && Xc(Lc) && (Lc = null); + null !== Mc && Xc(Mc) && (Mc = null); + null !== Nc && Xc(Nc) && (Nc = null); + Oc.forEach(Zc); + Pc.forEach(Zc); + } + function ad(a, b) { + a.blockedOn === b && (a.blockedOn = null, Jc || (Jc = true, ca.unstable_scheduleCallback(ca.unstable_NormalPriority, $c))); + } + function bd(a) { + function b(b2) { + return ad(b2, a); + } + if (0 < Kc.length) { + ad(Kc[0], a); + for (var c = 1; c < Kc.length; c++) { + var d = Kc[c]; + d.blockedOn === a && (d.blockedOn = null); + } + } + null !== Lc && ad(Lc, a); + null !== Mc && ad(Mc, a); + null !== Nc && ad(Nc, a); + Oc.forEach(b); + Pc.forEach(b); + for (c = 0; c < Qc.length; c++) d = Qc[c], d.blockedOn === a && (d.blockedOn = null); + for (; 0 < Qc.length && (c = Qc[0], null === c.blockedOn); ) Vc(c), null === c.blockedOn && Qc.shift(); + } + var cd = ua.ReactCurrentBatchConfig, dd = true; + function ed(a, b, c, d) { + var e = C, f = cd.transition; + cd.transition = null; + try { + C = 1, fd(a, b, c, d); + } finally { + C = e, cd.transition = f; + } + } + function gd(a, b, c, d) { + var e = C, f = cd.transition; + cd.transition = null; + try { + C = 4, fd(a, b, c, d); + } finally { + C = e, cd.transition = f; + } + } + function fd(a, b, c, d) { + if (dd) { + var e = Yc(a, b, c, d); + if (null === e) hd(a, b, d, id, c), Sc(a, d); + else if (Uc(e, a, b, c, d)) d.stopPropagation(); + else if (Sc(a, d), b & 4 && -1 < Rc.indexOf(a)) { + for (; null !== e; ) { + var f = Cb(e); + null !== f && Ec(f); + f = Yc(a, b, c, d); + null === f && hd(a, b, d, id, c); + if (f === e) break; + e = f; + } + null !== e && d.stopPropagation(); + } else hd(a, b, d, null, c); + } + } + var id = null; + function Yc(a, b, c, d) { + id = null; + a = xb(d); + a = Wc(a); + if (null !== a) if (b = Vb(a), null === b) a = null; + else if (c = b.tag, 13 === c) { + a = Wb(b); + if (null !== a) return a; + a = null; + } else if (3 === c) { + if (b.stateNode.current.memoizedState.isDehydrated) return 3 === b.tag ? b.stateNode.containerInfo : null; + a = null; + } else b !== a && (a = null); + id = a; + return null; + } + function jd(a) { + switch (a) { + case "cancel": + case "click": + case "close": + case "contextmenu": + case "copy": + case "cut": + case "auxclick": + case "dblclick": + case "dragend": + case "dragstart": + case "drop": + case "focusin": + case "focusout": + case "input": + case "invalid": + case "keydown": + case "keypress": + case "keyup": + case "mousedown": + case "mouseup": + case "paste": + case "pause": + case "play": + case "pointercancel": + case "pointerdown": + case "pointerup": + case "ratechange": + case "reset": + case "resize": + case "seeked": + case "submit": + case "touchcancel": + case "touchend": + case "touchstart": + case "volumechange": + case "change": + case "selectionchange": + case "textInput": + case "compositionstart": + case "compositionend": + case "compositionupdate": + case "beforeblur": + case "afterblur": + case "beforeinput": + case "blur": + case "fullscreenchange": + case "focus": + case "hashchange": + case "popstate": + case "select": + case "selectstart": + return 1; + case "drag": + case "dragenter": + case "dragexit": + case "dragleave": + case "dragover": + case "mousemove": + case "mouseout": + case "mouseover": + case "pointermove": + case "pointerout": + case "pointerover": + case "scroll": + case "toggle": + case "touchmove": + case "wheel": + case "mouseenter": + case "mouseleave": + case "pointerenter": + case "pointerleave": + return 4; + case "message": + switch (ec()) { + case fc: + return 1; + case gc: + return 4; + case hc: + case ic: + return 16; + case jc: + return 536870912; + default: + return 16; + } + default: + return 16; + } + } + var kd = null, ld = null, md = null; + function nd() { + if (md) return md; + var a, b = ld, c = b.length, d, e = "value" in kd ? kd.value : kd.textContent, f = e.length; + for (a = 0; a < c && b[a] === e[a]; a++) ; + var g = c - a; + for (d = 1; d <= g && b[c - d] === e[f - d]; d++) ; + return md = e.slice(a, 1 < d ? 1 - d : void 0); + } + function od(a) { + var b = a.keyCode; + "charCode" in a ? (a = a.charCode, 0 === a && 13 === b && (a = 13)) : a = b; + 10 === a && (a = 13); + return 32 <= a || 13 === a ? a : 0; + } + function pd() { + return true; + } + function qd() { + return false; + } + function rd(a) { + function b(b2, d, e, f, g) { + this._reactName = b2; + this._targetInst = e; + this.type = d; + this.nativeEvent = f; + this.target = g; + this.currentTarget = null; + for (var c in a) a.hasOwnProperty(c) && (b2 = a[c], this[c] = b2 ? b2(f) : f[c]); + this.isDefaultPrevented = (null != f.defaultPrevented ? f.defaultPrevented : false === f.returnValue) ? pd : qd; + this.isPropagationStopped = qd; + return this; + } + A(b.prototype, { preventDefault: function() { + this.defaultPrevented = true; + var a2 = this.nativeEvent; + a2 && (a2.preventDefault ? a2.preventDefault() : "unknown" !== typeof a2.returnValue && (a2.returnValue = false), this.isDefaultPrevented = pd); + }, stopPropagation: function() { + var a2 = this.nativeEvent; + a2 && (a2.stopPropagation ? a2.stopPropagation() : "unknown" !== typeof a2.cancelBubble && (a2.cancelBubble = true), this.isPropagationStopped = pd); + }, persist: function() { + }, isPersistent: pd }); + return b; + } + var sd = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a) { + return a.timeStamp || Date.now(); + }, defaultPrevented: 0, isTrusted: 0 }, td = rd(sd), ud = A({}, sd, { view: 0, detail: 0 }), vd = rd(ud), wd, xd, yd, Ad = A({}, ud, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd, button: 0, buttons: 0, relatedTarget: function(a) { + return void 0 === a.relatedTarget ? a.fromElement === a.srcElement ? a.toElement : a.fromElement : a.relatedTarget; + }, movementX: function(a) { + if ("movementX" in a) return a.movementX; + a !== yd && (yd && "mousemove" === a.type ? (wd = a.screenX - yd.screenX, xd = a.screenY - yd.screenY) : xd = wd = 0, yd = a); + return wd; + }, movementY: function(a) { + return "movementY" in a ? a.movementY : xd; + } }), Bd = rd(Ad), Cd = A({}, Ad, { dataTransfer: 0 }), Dd = rd(Cd), Ed = A({}, ud, { relatedTarget: 0 }), Fd = rd(Ed), Gd = A({}, sd, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }), Hd = rd(Gd), Id = A({}, sd, { clipboardData: function(a) { + return "clipboardData" in a ? a.clipboardData : window.clipboardData; + } }), Jd = rd(Id), Kd = A({}, sd, { data: 0 }), Ld = rd(Kd), Md = { + Esc: "Escape", + Spacebar: " ", + Left: "ArrowLeft", + Up: "ArrowUp", + Right: "ArrowRight", + Down: "ArrowDown", + Del: "Delete", + Win: "OS", + Menu: "ContextMenu", + Apps: "ContextMenu", + Scroll: "ScrollLock", + MozPrintableKey: "Unidentified" + }, Nd = { + 8: "Backspace", + 9: "Tab", + 12: "Clear", + 13: "Enter", + 16: "Shift", + 17: "Control", + 18: "Alt", + 19: "Pause", + 20: "CapsLock", + 27: "Escape", + 32: " ", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "ArrowLeft", + 38: "ArrowUp", + 39: "ArrowRight", + 40: "ArrowDown", + 45: "Insert", + 46: "Delete", + 112: "F1", + 113: "F2", + 114: "F3", + 115: "F4", + 116: "F5", + 117: "F6", + 118: "F7", + 119: "F8", + 120: "F9", + 121: "F10", + 122: "F11", + 123: "F12", + 144: "NumLock", + 145: "ScrollLock", + 224: "Meta" + }, Od = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" }; + function Pd(a) { + var b = this.nativeEvent; + return b.getModifierState ? b.getModifierState(a) : (a = Od[a]) ? !!b[a] : false; + } + function zd() { + return Pd; + } + var Qd = A({}, ud, { key: function(a) { + if (a.key) { + var b = Md[a.key] || a.key; + if ("Unidentified" !== b) return b; + } + return "keypress" === a.type ? (a = od(a), 13 === a ? "Enter" : String.fromCharCode(a)) : "keydown" === a.type || "keyup" === a.type ? Nd[a.keyCode] || "Unidentified" : ""; + }, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd, charCode: function(a) { + return "keypress" === a.type ? od(a) : 0; + }, keyCode: function(a) { + return "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0; + }, which: function(a) { + return "keypress" === a.type ? od(a) : "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0; + } }), Rd = rd(Qd), Sd = A({}, Ad, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }), Td = rd(Sd), Ud = A({}, ud, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd }), Vd = rd(Ud), Wd = A({}, sd, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }), Xd = rd(Wd), Yd = A({}, Ad, { + deltaX: function(a) { + return "deltaX" in a ? a.deltaX : "wheelDeltaX" in a ? -a.wheelDeltaX : 0; + }, + deltaY: function(a) { + return "deltaY" in a ? a.deltaY : "wheelDeltaY" in a ? -a.wheelDeltaY : "wheelDelta" in a ? -a.wheelDelta : 0; + }, + deltaZ: 0, + deltaMode: 0 + }), Zd = rd(Yd), $d = [9, 13, 27, 32], ae = ia && "CompositionEvent" in window, be = null; + ia && "documentMode" in document && (be = document.documentMode); + var ce = ia && "TextEvent" in window && !be, de = ia && (!ae || be && 8 < be && 11 >= be), ee = String.fromCharCode(32), fe = false; + function ge(a, b) { + switch (a) { + case "keyup": + return -1 !== $d.indexOf(b.keyCode); + case "keydown": + return 229 !== b.keyCode; + case "keypress": + case "mousedown": + case "focusout": + return true; + default: + return false; + } + } + function he(a) { + a = a.detail; + return "object" === typeof a && "data" in a ? a.data : null; + } + var ie = false; + function je(a, b) { + switch (a) { + case "compositionend": + return he(b); + case "keypress": + if (32 !== b.which) return null; + fe = true; + return ee; + case "textInput": + return a = b.data, a === ee && fe ? null : a; + default: + return null; + } + } + function ke(a, b) { + if (ie) return "compositionend" === a || !ae && ge(a, b) ? (a = nd(), md = ld = kd = null, ie = false, a) : null; + switch (a) { + case "paste": + return null; + case "keypress": + if (!(b.ctrlKey || b.altKey || b.metaKey) || b.ctrlKey && b.altKey) { + if (b.char && 1 < b.char.length) return b.char; + if (b.which) return String.fromCharCode(b.which); + } + return null; + case "compositionend": + return de && "ko" !== b.locale ? null : b.data; + default: + return null; + } + } + var le = { color: true, date: true, datetime: true, "datetime-local": true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true }; + function me(a) { + var b = a && a.nodeName && a.nodeName.toLowerCase(); + return "input" === b ? !!le[a.type] : "textarea" === b ? true : false; + } + function ne(a, b, c, d) { + Eb(d); + b = oe(b, "onChange"); + 0 < b.length && (c = new td("onChange", "change", null, c, d), a.push({ event: c, listeners: b })); + } + var pe = null, qe = null; + function re(a) { + se(a, 0); + } + function te(a) { + var b = ue(a); + if (Wa(b)) return a; + } + function ve(a, b) { + if ("change" === a) return b; + } + var we = false; + if (ia) { + var xe; + if (ia) { + var ye = "oninput" in document; + if (!ye) { + var ze = document.createElement("div"); + ze.setAttribute("oninput", "return;"); + ye = "function" === typeof ze.oninput; + } + xe = ye; + } else xe = false; + we = xe && (!document.documentMode || 9 < document.documentMode); + } + function Ae() { + pe && (pe.detachEvent("onpropertychange", Be), qe = pe = null); + } + function Be(a) { + if ("value" === a.propertyName && te(qe)) { + var b = []; + ne(b, qe, a, xb(a)); + Jb(re, b); + } + } + function Ce(a, b, c) { + "focusin" === a ? (Ae(), pe = b, qe = c, pe.attachEvent("onpropertychange", Be)) : "focusout" === a && Ae(); + } + function De(a) { + if ("selectionchange" === a || "keyup" === a || "keydown" === a) return te(qe); + } + function Ee(a, b) { + if ("click" === a) return te(b); + } + function Fe(a, b) { + if ("input" === a || "change" === a) return te(b); + } + function Ge(a, b) { + return a === b && (0 !== a || 1 / a === 1 / b) || a !== a && b !== b; + } + var He = "function" === typeof Object.is ? Object.is : Ge; + function Ie(a, b) { + if (He(a, b)) return true; + if ("object" !== typeof a || null === a || "object" !== typeof b || null === b) return false; + var c = Object.keys(a), d = Object.keys(b); + if (c.length !== d.length) return false; + for (d = 0; d < c.length; d++) { + var e = c[d]; + if (!ja.call(b, e) || !He(a[e], b[e])) return false; + } + return true; + } + function Je(a) { + for (; a && a.firstChild; ) a = a.firstChild; + return a; + } + function Ke(a, b) { + var c = Je(a); + a = 0; + for (var d; c; ) { + if (3 === c.nodeType) { + d = a + c.textContent.length; + if (a <= b && d >= b) return { node: c, offset: b - a }; + a = d; + } + a: { + for (; c; ) { + if (c.nextSibling) { + c = c.nextSibling; + break a; + } + c = c.parentNode; + } + c = void 0; + } + c = Je(c); + } + } + function Le(a, b) { + return a && b ? a === b ? true : a && 3 === a.nodeType ? false : b && 3 === b.nodeType ? Le(a, b.parentNode) : "contains" in a ? a.contains(b) : a.compareDocumentPosition ? !!(a.compareDocumentPosition(b) & 16) : false : false; + } + function Me() { + for (var a = window, b = Xa(); b instanceof a.HTMLIFrameElement; ) { + try { + var c = "string" === typeof b.contentWindow.location.href; + } catch (d) { + c = false; + } + if (c) a = b.contentWindow; + else break; + b = Xa(a.document); + } + return b; + } + function Ne(a) { + var b = a && a.nodeName && a.nodeName.toLowerCase(); + return b && ("input" === b && ("text" === a.type || "search" === a.type || "tel" === a.type || "url" === a.type || "password" === a.type) || "textarea" === b || "true" === a.contentEditable); + } + function Oe(a) { + var b = Me(), c = a.focusedElem, d = a.selectionRange; + if (b !== c && c && c.ownerDocument && Le(c.ownerDocument.documentElement, c)) { + if (null !== d && Ne(c)) { + if (b = d.start, a = d.end, void 0 === a && (a = b), "selectionStart" in c) c.selectionStart = b, c.selectionEnd = Math.min(a, c.value.length); + else if (a = (b = c.ownerDocument || document) && b.defaultView || window, a.getSelection) { + a = a.getSelection(); + var e = c.textContent.length, f = Math.min(d.start, e); + d = void 0 === d.end ? f : Math.min(d.end, e); + !a.extend && f > d && (e = d, d = f, f = e); + e = Ke(c, f); + var g = Ke( + c, + d + ); + e && g && (1 !== a.rangeCount || a.anchorNode !== e.node || a.anchorOffset !== e.offset || a.focusNode !== g.node || a.focusOffset !== g.offset) && (b = b.createRange(), b.setStart(e.node, e.offset), a.removeAllRanges(), f > d ? (a.addRange(b), a.extend(g.node, g.offset)) : (b.setEnd(g.node, g.offset), a.addRange(b))); + } + } + b = []; + for (a = c; a = a.parentNode; ) 1 === a.nodeType && b.push({ element: a, left: a.scrollLeft, top: a.scrollTop }); + "function" === typeof c.focus && c.focus(); + for (c = 0; c < b.length; c++) a = b[c], a.element.scrollLeft = a.left, a.element.scrollTop = a.top; + } + } + var Pe = ia && "documentMode" in document && 11 >= document.documentMode, Qe = null, Re = null, Se = null, Te = false; + function Ue(a, b, c) { + var d = c.window === c ? c.document : 9 === c.nodeType ? c : c.ownerDocument; + Te || null == Qe || Qe !== Xa(d) || (d = Qe, "selectionStart" in d && Ne(d) ? d = { start: d.selectionStart, end: d.selectionEnd } : (d = (d.ownerDocument && d.ownerDocument.defaultView || window).getSelection(), d = { anchorNode: d.anchorNode, anchorOffset: d.anchorOffset, focusNode: d.focusNode, focusOffset: d.focusOffset }), Se && Ie(Se, d) || (Se = d, d = oe(Re, "onSelect"), 0 < d.length && (b = new td("onSelect", "select", null, b, c), a.push({ event: b, listeners: d }), b.target = Qe))); + } + function Ve(a, b) { + var c = {}; + c[a.toLowerCase()] = b.toLowerCase(); + c["Webkit" + a] = "webkit" + b; + c["Moz" + a] = "moz" + b; + return c; + } + var We = { animationend: Ve("Animation", "AnimationEnd"), animationiteration: Ve("Animation", "AnimationIteration"), animationstart: Ve("Animation", "AnimationStart"), transitionend: Ve("Transition", "TransitionEnd") }, Xe = {}, Ye = {}; + ia && (Ye = document.createElement("div").style, "AnimationEvent" in window || (delete We.animationend.animation, delete We.animationiteration.animation, delete We.animationstart.animation), "TransitionEvent" in window || delete We.transitionend.transition); + function Ze(a) { + if (Xe[a]) return Xe[a]; + if (!We[a]) return a; + var b = We[a], c; + for (c in b) if (b.hasOwnProperty(c) && c in Ye) return Xe[a] = b[c]; + return a; + } + var $e = Ze("animationend"), af = Ze("animationiteration"), bf = Ze("animationstart"), cf = Ze("transitionend"), df = /* @__PURE__ */ new Map(), ef = "abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" "); + function ff(a, b) { + df.set(a, b); + fa(b, [a]); + } + for (var gf = 0; gf < ef.length; gf++) { + var hf = ef[gf], jf = hf.toLowerCase(), kf = hf[0].toUpperCase() + hf.slice(1); + ff(jf, "on" + kf); + } + ff($e, "onAnimationEnd"); + ff(af, "onAnimationIteration"); + ff(bf, "onAnimationStart"); + ff("dblclick", "onDoubleClick"); + ff("focusin", "onFocus"); + ff("focusout", "onBlur"); + ff(cf, "onTransitionEnd"); + ha("onMouseEnter", ["mouseout", "mouseover"]); + ha("onMouseLeave", ["mouseout", "mouseover"]); + ha("onPointerEnter", ["pointerout", "pointerover"]); + ha("onPointerLeave", ["pointerout", "pointerover"]); + fa("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" ")); + fa("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")); + fa("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]); + fa("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" ")); + fa("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" ")); + fa("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" ")); + var lf = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "), mf = new Set("cancel close invalid load scroll toggle".split(" ").concat(lf)); + function nf(a, b, c) { + var d = a.type || "unknown-event"; + a.currentTarget = c; + Ub(d, b, void 0, a); + a.currentTarget = null; + } + function se(a, b) { + b = 0 !== (b & 4); + for (var c = 0; c < a.length; c++) { + var d = a[c], e = d.event; + d = d.listeners; + a: { + var f = void 0; + if (b) for (var g = d.length - 1; 0 <= g; g--) { + var h = d[g], k = h.instance, l = h.currentTarget; + h = h.listener; + if (k !== f && e.isPropagationStopped()) break a; + nf(e, h, l); + f = k; + } + else for (g = 0; g < d.length; g++) { + h = d[g]; + k = h.instance; + l = h.currentTarget; + h = h.listener; + if (k !== f && e.isPropagationStopped()) break a; + nf(e, h, l); + f = k; + } + } + } + if (Qb) throw a = Rb, Qb = false, Rb = null, a; + } + function D(a, b) { + var c = b[of]; + void 0 === c && (c = b[of] = /* @__PURE__ */ new Set()); + var d = a + "__bubble"; + c.has(d) || (pf(b, a, 2, false), c.add(d)); + } + function qf(a, b, c) { + var d = 0; + b && (d |= 4); + pf(c, a, d, b); + } + var rf = "_reactListening" + Math.random().toString(36).slice(2); + function sf(a) { + if (!a[rf]) { + a[rf] = true; + da.forEach(function(b2) { + "selectionchange" !== b2 && (mf.has(b2) || qf(b2, false, a), qf(b2, true, a)); + }); + var b = 9 === a.nodeType ? a : a.ownerDocument; + null === b || b[rf] || (b[rf] = true, qf("selectionchange", false, b)); + } + } + function pf(a, b, c, d) { + switch (jd(b)) { + case 1: + var e = ed; + break; + case 4: + e = gd; + break; + default: + e = fd; + } + c = e.bind(null, b, c, a); + e = void 0; + !Lb || "touchstart" !== b && "touchmove" !== b && "wheel" !== b || (e = true); + d ? void 0 !== e ? a.addEventListener(b, c, { capture: true, passive: e }) : a.addEventListener(b, c, true) : void 0 !== e ? a.addEventListener(b, c, { passive: e }) : a.addEventListener(b, c, false); + } + function hd(a, b, c, d, e) { + var f = d; + if (0 === (b & 1) && 0 === (b & 2) && null !== d) a: for (; ; ) { + if (null === d) return; + var g = d.tag; + if (3 === g || 4 === g) { + var h = d.stateNode.containerInfo; + if (h === e || 8 === h.nodeType && h.parentNode === e) break; + if (4 === g) for (g = d.return; null !== g; ) { + var k = g.tag; + if (3 === k || 4 === k) { + if (k = g.stateNode.containerInfo, k === e || 8 === k.nodeType && k.parentNode === e) return; + } + g = g.return; + } + for (; null !== h; ) { + g = Wc(h); + if (null === g) return; + k = g.tag; + if (5 === k || 6 === k) { + d = f = g; + continue a; + } + h = h.parentNode; + } + } + d = d.return; + } + Jb(function() { + var d2 = f, e2 = xb(c), g2 = []; + a: { + var h2 = df.get(a); + if (void 0 !== h2) { + var k2 = td, n = a; + switch (a) { + case "keypress": + if (0 === od(c)) break a; + case "keydown": + case "keyup": + k2 = Rd; + break; + case "focusin": + n = "focus"; + k2 = Fd; + break; + case "focusout": + n = "blur"; + k2 = Fd; + break; + case "beforeblur": + case "afterblur": + k2 = Fd; + break; + case "click": + if (2 === c.button) break a; + case "auxclick": + case "dblclick": + case "mousedown": + case "mousemove": + case "mouseup": + case "mouseout": + case "mouseover": + case "contextmenu": + k2 = Bd; + break; + case "drag": + case "dragend": + case "dragenter": + case "dragexit": + case "dragleave": + case "dragover": + case "dragstart": + case "drop": + k2 = Dd; + break; + case "touchcancel": + case "touchend": + case "touchmove": + case "touchstart": + k2 = Vd; + break; + case $e: + case af: + case bf: + k2 = Hd; + break; + case cf: + k2 = Xd; + break; + case "scroll": + k2 = vd; + break; + case "wheel": + k2 = Zd; + break; + case "copy": + case "cut": + case "paste": + k2 = Jd; + break; + case "gotpointercapture": + case "lostpointercapture": + case "pointercancel": + case "pointerdown": + case "pointermove": + case "pointerout": + case "pointerover": + case "pointerup": + k2 = Td; + } + var t = 0 !== (b & 4), J = !t && "scroll" === a, x = t ? null !== h2 ? h2 + "Capture" : null : h2; + t = []; + for (var w = d2, u; null !== w; ) { + u = w; + var F = u.stateNode; + 5 === u.tag && null !== F && (u = F, null !== x && (F = Kb(w, x), null != F && t.push(tf(w, F, u)))); + if (J) break; + w = w.return; + } + 0 < t.length && (h2 = new k2(h2, n, null, c, e2), g2.push({ event: h2, listeners: t })); + } + } + if (0 === (b & 7)) { + a: { + h2 = "mouseover" === a || "pointerover" === a; + k2 = "mouseout" === a || "pointerout" === a; + if (h2 && c !== wb && (n = c.relatedTarget || c.fromElement) && (Wc(n) || n[uf])) break a; + if (k2 || h2) { + h2 = e2.window === e2 ? e2 : (h2 = e2.ownerDocument) ? h2.defaultView || h2.parentWindow : window; + if (k2) { + if (n = c.relatedTarget || c.toElement, k2 = d2, n = n ? Wc(n) : null, null !== n && (J = Vb(n), n !== J || 5 !== n.tag && 6 !== n.tag)) n = null; + } else k2 = null, n = d2; + if (k2 !== n) { + t = Bd; + F = "onMouseLeave"; + x = "onMouseEnter"; + w = "mouse"; + if ("pointerout" === a || "pointerover" === a) t = Td, F = "onPointerLeave", x = "onPointerEnter", w = "pointer"; + J = null == k2 ? h2 : ue(k2); + u = null == n ? h2 : ue(n); + h2 = new t(F, w + "leave", k2, c, e2); + h2.target = J; + h2.relatedTarget = u; + F = null; + Wc(e2) === d2 && (t = new t(x, w + "enter", n, c, e2), t.target = u, t.relatedTarget = J, F = t); + J = F; + if (k2 && n) b: { + t = k2; + x = n; + w = 0; + for (u = t; u; u = vf(u)) w++; + u = 0; + for (F = x; F; F = vf(F)) u++; + for (; 0 < w - u; ) t = vf(t), w--; + for (; 0 < u - w; ) x = vf(x), u--; + for (; w--; ) { + if (t === x || null !== x && t === x.alternate) break b; + t = vf(t); + x = vf(x); + } + t = null; + } + else t = null; + null !== k2 && wf(g2, h2, k2, t, false); + null !== n && null !== J && wf(g2, J, n, t, true); + } + } + } + a: { + h2 = d2 ? ue(d2) : window; + k2 = h2.nodeName && h2.nodeName.toLowerCase(); + if ("select" === k2 || "input" === k2 && "file" === h2.type) var na = ve; + else if (me(h2)) if (we) na = Fe; + else { + na = De; + var xa = Ce; + } + else (k2 = h2.nodeName) && "input" === k2.toLowerCase() && ("checkbox" === h2.type || "radio" === h2.type) && (na = Ee); + if (na && (na = na(a, d2))) { + ne(g2, na, c, e2); + break a; + } + xa && xa(a, h2, d2); + "focusout" === a && (xa = h2._wrapperState) && xa.controlled && "number" === h2.type && cb(h2, "number", h2.value); + } + xa = d2 ? ue(d2) : window; + switch (a) { + case "focusin": + if (me(xa) || "true" === xa.contentEditable) Qe = xa, Re = d2, Se = null; + break; + case "focusout": + Se = Re = Qe = null; + break; + case "mousedown": + Te = true; + break; + case "contextmenu": + case "mouseup": + case "dragend": + Te = false; + Ue(g2, c, e2); + break; + case "selectionchange": + if (Pe) break; + case "keydown": + case "keyup": + Ue(g2, c, e2); + } + var $a; + if (ae) b: { + switch (a) { + case "compositionstart": + var ba = "onCompositionStart"; + break b; + case "compositionend": + ba = "onCompositionEnd"; + break b; + case "compositionupdate": + ba = "onCompositionUpdate"; + break b; + } + ba = void 0; + } + else ie ? ge(a, c) && (ba = "onCompositionEnd") : "keydown" === a && 229 === c.keyCode && (ba = "onCompositionStart"); + ba && (de && "ko" !== c.locale && (ie || "onCompositionStart" !== ba ? "onCompositionEnd" === ba && ie && ($a = nd()) : (kd = e2, ld = "value" in kd ? kd.value : kd.textContent, ie = true)), xa = oe(d2, ba), 0 < xa.length && (ba = new Ld(ba, a, null, c, e2), g2.push({ event: ba, listeners: xa }), $a ? ba.data = $a : ($a = he(c), null !== $a && (ba.data = $a)))); + if ($a = ce ? je(a, c) : ke(a, c)) d2 = oe(d2, "onBeforeInput"), 0 < d2.length && (e2 = new Ld("onBeforeInput", "beforeinput", null, c, e2), g2.push({ event: e2, listeners: d2 }), e2.data = $a); + } + se(g2, b); + }); + } + function tf(a, b, c) { + return { instance: a, listener: b, currentTarget: c }; + } + function oe(a, b) { + for (var c = b + "Capture", d = []; null !== a; ) { + var e = a, f = e.stateNode; + 5 === e.tag && null !== f && (e = f, f = Kb(a, c), null != f && d.unshift(tf(a, f, e)), f = Kb(a, b), null != f && d.push(tf(a, f, e))); + a = a.return; + } + return d; + } + function vf(a) { + if (null === a) return null; + do + a = a.return; + while (a && 5 !== a.tag); + return a ? a : null; + } + function wf(a, b, c, d, e) { + for (var f = b._reactName, g = []; null !== c && c !== d; ) { + var h = c, k = h.alternate, l = h.stateNode; + if (null !== k && k === d) break; + 5 === h.tag && null !== l && (h = l, e ? (k = Kb(c, f), null != k && g.unshift(tf(c, k, h))) : e || (k = Kb(c, f), null != k && g.push(tf(c, k, h)))); + c = c.return; + } + 0 !== g.length && a.push({ event: b, listeners: g }); + } + var xf = /\r\n?/g, yf = /\u0000|\uFFFD/g; + function zf(a) { + return ("string" === typeof a ? a : "" + a).replace(xf, "\n").replace(yf, ""); + } + function Af(a, b, c) { + b = zf(b); + if (zf(a) !== b && c) throw Error(p(425)); + } + function Bf() { + } + var Cf = null, Df = null; + function Ef(a, b) { + return "textarea" === a || "noscript" === a || "string" === typeof b.children || "number" === typeof b.children || "object" === typeof b.dangerouslySetInnerHTML && null !== b.dangerouslySetInnerHTML && null != b.dangerouslySetInnerHTML.__html; + } + var Ff = "function" === typeof setTimeout ? setTimeout : void 0, Gf = "function" === typeof clearTimeout ? clearTimeout : void 0, Hf = "function" === typeof Promise ? Promise : void 0, Jf = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof Hf ? function(a) { + return Hf.resolve(null).then(a).catch(If); + } : Ff; + function If(a) { + setTimeout(function() { + throw a; + }); + } + function Kf(a, b) { + var c = b, d = 0; + do { + var e = c.nextSibling; + a.removeChild(c); + if (e && 8 === e.nodeType) if (c = e.data, "/$" === c) { + if (0 === d) { + a.removeChild(e); + bd(b); + return; + } + d--; + } else "$" !== c && "$?" !== c && "$!" !== c || d++; + c = e; + } while (c); + bd(b); + } + function Lf(a) { + for (; null != a; a = a.nextSibling) { + var b = a.nodeType; + if (1 === b || 3 === b) break; + if (8 === b) { + b = a.data; + if ("$" === b || "$!" === b || "$?" === b) break; + if ("/$" === b) return null; + } + } + return a; + } + function Mf(a) { + a = a.previousSibling; + for (var b = 0; a; ) { + if (8 === a.nodeType) { + var c = a.data; + if ("$" === c || "$!" === c || "$?" === c) { + if (0 === b) return a; + b--; + } else "/$" === c && b++; + } + a = a.previousSibling; + } + return null; + } + var Nf = Math.random().toString(36).slice(2), Of = "__reactFiber$" + Nf, Pf = "__reactProps$" + Nf, uf = "__reactContainer$" + Nf, of = "__reactEvents$" + Nf, Qf = "__reactListeners$" + Nf, Rf = "__reactHandles$" + Nf; + function Wc(a) { + var b = a[Of]; + if (b) return b; + for (var c = a.parentNode; c; ) { + if (b = c[uf] || c[Of]) { + c = b.alternate; + if (null !== b.child || null !== c && null !== c.child) for (a = Mf(a); null !== a; ) { + if (c = a[Of]) return c; + a = Mf(a); + } + return b; + } + a = c; + c = a.parentNode; + } + return null; + } + function Cb(a) { + a = a[Of] || a[uf]; + return !a || 5 !== a.tag && 6 !== a.tag && 13 !== a.tag && 3 !== a.tag ? null : a; + } + function ue(a) { + if (5 === a.tag || 6 === a.tag) return a.stateNode; + throw Error(p(33)); + } + function Db(a) { + return a[Pf] || null; + } + var Sf = [], Tf = -1; + function Uf(a) { + return { current: a }; + } + function E(a) { + 0 > Tf || (a.current = Sf[Tf], Sf[Tf] = null, Tf--); + } + function G(a, b) { + Tf++; + Sf[Tf] = a.current; + a.current = b; + } + var Vf = {}, H = Uf(Vf), Wf = Uf(false), Xf = Vf; + function Yf(a, b) { + var c = a.type.contextTypes; + if (!c) return Vf; + var d = a.stateNode; + if (d && d.__reactInternalMemoizedUnmaskedChildContext === b) return d.__reactInternalMemoizedMaskedChildContext; + var e = {}, f; + for (f in c) e[f] = b[f]; + d && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = b, a.__reactInternalMemoizedMaskedChildContext = e); + return e; + } + function Zf(a) { + a = a.childContextTypes; + return null !== a && void 0 !== a; + } + function $f() { + E(Wf); + E(H); + } + function ag(a, b, c) { + if (H.current !== Vf) throw Error(p(168)); + G(H, b); + G(Wf, c); + } + function bg(a, b, c) { + var d = a.stateNode; + b = b.childContextTypes; + if ("function" !== typeof d.getChildContext) return c; + d = d.getChildContext(); + for (var e in d) if (!(e in b)) throw Error(p(108, Ra(a) || "Unknown", e)); + return A({}, c, d); + } + function cg(a) { + a = (a = a.stateNode) && a.__reactInternalMemoizedMergedChildContext || Vf; + Xf = H.current; + G(H, a); + G(Wf, Wf.current); + return true; + } + function dg(a, b, c) { + var d = a.stateNode; + if (!d) throw Error(p(169)); + c ? (a = bg(a, b, Xf), d.__reactInternalMemoizedMergedChildContext = a, E(Wf), E(H), G(H, a)) : E(Wf); + G(Wf, c); + } + var eg = null, fg = false, gg = false; + function hg(a) { + null === eg ? eg = [a] : eg.push(a); + } + function ig(a) { + fg = true; + hg(a); + } + function jg() { + if (!gg && null !== eg) { + gg = true; + var a = 0, b = C; + try { + var c = eg; + for (C = 1; a < c.length; a++) { + var d = c[a]; + do + d = d(true); + while (null !== d); + } + eg = null; + fg = false; + } catch (e) { + throw null !== eg && (eg = eg.slice(a + 1)), ac(fc, jg), e; + } finally { + C = b, gg = false; + } + } + return null; + } + var kg = [], lg = 0, mg = null, ng = 0, og = [], pg = 0, qg = null, rg = 1, sg = ""; + function tg(a, b) { + kg[lg++] = ng; + kg[lg++] = mg; + mg = a; + ng = b; + } + function ug(a, b, c) { + og[pg++] = rg; + og[pg++] = sg; + og[pg++] = qg; + qg = a; + var d = rg; + a = sg; + var e = 32 - oc(d) - 1; + d &= ~(1 << e); + c += 1; + var f = 32 - oc(b) + e; + if (30 < f) { + var g = e - e % 5; + f = (d & (1 << g) - 1).toString(32); + d >>= g; + e -= g; + rg = 1 << 32 - oc(b) + e | c << e | d; + sg = f + a; + } else rg = 1 << f | c << e | d, sg = a; + } + function vg(a) { + null !== a.return && (tg(a, 1), ug(a, 1, 0)); + } + function wg(a) { + for (; a === mg; ) mg = kg[--lg], kg[lg] = null, ng = kg[--lg], kg[lg] = null; + for (; a === qg; ) qg = og[--pg], og[pg] = null, sg = og[--pg], og[pg] = null, rg = og[--pg], og[pg] = null; + } + var xg = null, yg = null, I = false, zg = null; + function Ag(a, b) { + var c = Bg(5, null, null, 0); + c.elementType = "DELETED"; + c.stateNode = b; + c.return = a; + b = a.deletions; + null === b ? (a.deletions = [c], a.flags |= 16) : b.push(c); + } + function Cg(a, b) { + switch (a.tag) { + case 5: + var c = a.type; + b = 1 !== b.nodeType || c.toLowerCase() !== b.nodeName.toLowerCase() ? null : b; + return null !== b ? (a.stateNode = b, xg = a, yg = Lf(b.firstChild), true) : false; + case 6: + return b = "" === a.pendingProps || 3 !== b.nodeType ? null : b, null !== b ? (a.stateNode = b, xg = a, yg = null, true) : false; + case 13: + return b = 8 !== b.nodeType ? null : b, null !== b ? (c = null !== qg ? { id: rg, overflow: sg } : null, a.memoizedState = { dehydrated: b, treeContext: c, retryLane: 1073741824 }, c = Bg(18, null, null, 0), c.stateNode = b, c.return = a, a.child = c, xg = a, yg = null, true) : false; + default: + return false; + } + } + function Dg(a) { + return 0 !== (a.mode & 1) && 0 === (a.flags & 128); + } + function Eg(a) { + if (I) { + var b = yg; + if (b) { + var c = b; + if (!Cg(a, b)) { + if (Dg(a)) throw Error(p(418)); + b = Lf(c.nextSibling); + var d = xg; + b && Cg(a, b) ? Ag(d, c) : (a.flags = a.flags & -4097 | 2, I = false, xg = a); + } + } else { + if (Dg(a)) throw Error(p(418)); + a.flags = a.flags & -4097 | 2; + I = false; + xg = a; + } + } + } + function Fg(a) { + for (a = a.return; null !== a && 5 !== a.tag && 3 !== a.tag && 13 !== a.tag; ) a = a.return; + xg = a; + } + function Gg(a) { + if (a !== xg) return false; + if (!I) return Fg(a), I = true, false; + var b; + (b = 3 !== a.tag) && !(b = 5 !== a.tag) && (b = a.type, b = "head" !== b && "body" !== b && !Ef(a.type, a.memoizedProps)); + if (b && (b = yg)) { + if (Dg(a)) throw Hg(), Error(p(418)); + for (; b; ) Ag(a, b), b = Lf(b.nextSibling); + } + Fg(a); + if (13 === a.tag) { + a = a.memoizedState; + a = null !== a ? a.dehydrated : null; + if (!a) throw Error(p(317)); + a: { + a = a.nextSibling; + for (b = 0; a; ) { + if (8 === a.nodeType) { + var c = a.data; + if ("/$" === c) { + if (0 === b) { + yg = Lf(a.nextSibling); + break a; + } + b--; + } else "$" !== c && "$!" !== c && "$?" !== c || b++; + } + a = a.nextSibling; + } + yg = null; + } + } else yg = xg ? Lf(a.stateNode.nextSibling) : null; + return true; + } + function Hg() { + for (var a = yg; a; ) a = Lf(a.nextSibling); + } + function Ig() { + yg = xg = null; + I = false; + } + function Jg(a) { + null === zg ? zg = [a] : zg.push(a); + } + var Kg = ua.ReactCurrentBatchConfig; + function Lg(a, b, c) { + a = c.ref; + if (null !== a && "function" !== typeof a && "object" !== typeof a) { + if (c._owner) { + c = c._owner; + if (c) { + if (1 !== c.tag) throw Error(p(309)); + var d = c.stateNode; + } + if (!d) throw Error(p(147, a)); + var e = d, f = "" + a; + if (null !== b && null !== b.ref && "function" === typeof b.ref && b.ref._stringRef === f) return b.ref; + b = function(a2) { + var b2 = e.refs; + null === a2 ? delete b2[f] : b2[f] = a2; + }; + b._stringRef = f; + return b; + } + if ("string" !== typeof a) throw Error(p(284)); + if (!c._owner) throw Error(p(290, a)); + } + return a; + } + function Mg(a, b) { + a = Object.prototype.toString.call(b); + throw Error(p(31, "[object Object]" === a ? "object with keys {" + Object.keys(b).join(", ") + "}" : a)); + } + function Ng(a) { + var b = a._init; + return b(a._payload); + } + function Og(a) { + function b(b2, c2) { + if (a) { + var d2 = b2.deletions; + null === d2 ? (b2.deletions = [c2], b2.flags |= 16) : d2.push(c2); + } + } + function c(c2, d2) { + if (!a) return null; + for (; null !== d2; ) b(c2, d2), d2 = d2.sibling; + return null; + } + function d(a2, b2) { + for (a2 = /* @__PURE__ */ new Map(); null !== b2; ) null !== b2.key ? a2.set(b2.key, b2) : a2.set(b2.index, b2), b2 = b2.sibling; + return a2; + } + function e(a2, b2) { + a2 = Pg(a2, b2); + a2.index = 0; + a2.sibling = null; + return a2; + } + function f(b2, c2, d2) { + b2.index = d2; + if (!a) return b2.flags |= 1048576, c2; + d2 = b2.alternate; + if (null !== d2) return d2 = d2.index, d2 < c2 ? (b2.flags |= 2, c2) : d2; + b2.flags |= 2; + return c2; + } + function g(b2) { + a && null === b2.alternate && (b2.flags |= 2); + return b2; + } + function h(a2, b2, c2, d2) { + if (null === b2 || 6 !== b2.tag) return b2 = Qg(c2, a2.mode, d2), b2.return = a2, b2; + b2 = e(b2, c2); + b2.return = a2; + return b2; + } + function k(a2, b2, c2, d2) { + var f2 = c2.type; + if (f2 === ya) return m(a2, b2, c2.props.children, d2, c2.key); + if (null !== b2 && (b2.elementType === f2 || "object" === typeof f2 && null !== f2 && f2.$$typeof === Ha && Ng(f2) === b2.type)) return d2 = e(b2, c2.props), d2.ref = Lg(a2, b2, c2), d2.return = a2, d2; + d2 = Rg(c2.type, c2.key, c2.props, null, a2.mode, d2); + d2.ref = Lg(a2, b2, c2); + d2.return = a2; + return d2; + } + function l(a2, b2, c2, d2) { + if (null === b2 || 4 !== b2.tag || b2.stateNode.containerInfo !== c2.containerInfo || b2.stateNode.implementation !== c2.implementation) return b2 = Sg(c2, a2.mode, d2), b2.return = a2, b2; + b2 = e(b2, c2.children || []); + b2.return = a2; + return b2; + } + function m(a2, b2, c2, d2, f2) { + if (null === b2 || 7 !== b2.tag) return b2 = Tg(c2, a2.mode, d2, f2), b2.return = a2, b2; + b2 = e(b2, c2); + b2.return = a2; + return b2; + } + function q(a2, b2, c2) { + if ("string" === typeof b2 && "" !== b2 || "number" === typeof b2) return b2 = Qg("" + b2, a2.mode, c2), b2.return = a2, b2; + if ("object" === typeof b2 && null !== b2) { + switch (b2.$$typeof) { + case va: + return c2 = Rg(b2.type, b2.key, b2.props, null, a2.mode, c2), c2.ref = Lg(a2, null, b2), c2.return = a2, c2; + case wa: + return b2 = Sg(b2, a2.mode, c2), b2.return = a2, b2; + case Ha: + var d2 = b2._init; + return q(a2, d2(b2._payload), c2); + } + if (eb(b2) || Ka(b2)) return b2 = Tg(b2, a2.mode, c2, null), b2.return = a2, b2; + Mg(a2, b2); + } + return null; + } + function r(a2, b2, c2, d2) { + var e2 = null !== b2 ? b2.key : null; + if ("string" === typeof c2 && "" !== c2 || "number" === typeof c2) return null !== e2 ? null : h(a2, b2, "" + c2, d2); + if ("object" === typeof c2 && null !== c2) { + switch (c2.$$typeof) { + case va: + return c2.key === e2 ? k(a2, b2, c2, d2) : null; + case wa: + return c2.key === e2 ? l(a2, b2, c2, d2) : null; + case Ha: + return e2 = c2._init, r( + a2, + b2, + e2(c2._payload), + d2 + ); + } + if (eb(c2) || Ka(c2)) return null !== e2 ? null : m(a2, b2, c2, d2, null); + Mg(a2, c2); + } + return null; + } + function y(a2, b2, c2, d2, e2) { + if ("string" === typeof d2 && "" !== d2 || "number" === typeof d2) return a2 = a2.get(c2) || null, h(b2, a2, "" + d2, e2); + if ("object" === typeof d2 && null !== d2) { + switch (d2.$$typeof) { + case va: + return a2 = a2.get(null === d2.key ? c2 : d2.key) || null, k(b2, a2, d2, e2); + case wa: + return a2 = a2.get(null === d2.key ? c2 : d2.key) || null, l(b2, a2, d2, e2); + case Ha: + var f2 = d2._init; + return y(a2, b2, c2, f2(d2._payload), e2); + } + if (eb(d2) || Ka(d2)) return a2 = a2.get(c2) || null, m(b2, a2, d2, e2, null); + Mg(b2, d2); + } + return null; + } + function n(e2, g2, h2, k2) { + for (var l2 = null, m2 = null, u = g2, w = g2 = 0, x = null; null !== u && w < h2.length; w++) { + u.index > w ? (x = u, u = null) : x = u.sibling; + var n2 = r(e2, u, h2[w], k2); + if (null === n2) { + null === u && (u = x); + break; + } + a && u && null === n2.alternate && b(e2, u); + g2 = f(n2, g2, w); + null === m2 ? l2 = n2 : m2.sibling = n2; + m2 = n2; + u = x; + } + if (w === h2.length) return c(e2, u), I && tg(e2, w), l2; + if (null === u) { + for (; w < h2.length; w++) u = q(e2, h2[w], k2), null !== u && (g2 = f(u, g2, w), null === m2 ? l2 = u : m2.sibling = u, m2 = u); + I && tg(e2, w); + return l2; + } + for (u = d(e2, u); w < h2.length; w++) x = y(u, e2, w, h2[w], k2), null !== x && (a && null !== x.alternate && u.delete(null === x.key ? w : x.key), g2 = f(x, g2, w), null === m2 ? l2 = x : m2.sibling = x, m2 = x); + a && u.forEach(function(a2) { + return b(e2, a2); + }); + I && tg(e2, w); + return l2; + } + function t(e2, g2, h2, k2) { + var l2 = Ka(h2); + if ("function" !== typeof l2) throw Error(p(150)); + h2 = l2.call(h2); + if (null == h2) throw Error(p(151)); + for (var u = l2 = null, m2 = g2, w = g2 = 0, x = null, n2 = h2.next(); null !== m2 && !n2.done; w++, n2 = h2.next()) { + m2.index > w ? (x = m2, m2 = null) : x = m2.sibling; + var t2 = r(e2, m2, n2.value, k2); + if (null === t2) { + null === m2 && (m2 = x); + break; + } + a && m2 && null === t2.alternate && b(e2, m2); + g2 = f(t2, g2, w); + null === u ? l2 = t2 : u.sibling = t2; + u = t2; + m2 = x; + } + if (n2.done) return c( + e2, + m2 + ), I && tg(e2, w), l2; + if (null === m2) { + for (; !n2.done; w++, n2 = h2.next()) n2 = q(e2, n2.value, k2), null !== n2 && (g2 = f(n2, g2, w), null === u ? l2 = n2 : u.sibling = n2, u = n2); + I && tg(e2, w); + return l2; + } + for (m2 = d(e2, m2); !n2.done; w++, n2 = h2.next()) n2 = y(m2, e2, w, n2.value, k2), null !== n2 && (a && null !== n2.alternate && m2.delete(null === n2.key ? w : n2.key), g2 = f(n2, g2, w), null === u ? l2 = n2 : u.sibling = n2, u = n2); + a && m2.forEach(function(a2) { + return b(e2, a2); + }); + I && tg(e2, w); + return l2; + } + function J(a2, d2, f2, h2) { + "object" === typeof f2 && null !== f2 && f2.type === ya && null === f2.key && (f2 = f2.props.children); + if ("object" === typeof f2 && null !== f2) { + switch (f2.$$typeof) { + case va: + a: { + for (var k2 = f2.key, l2 = d2; null !== l2; ) { + if (l2.key === k2) { + k2 = f2.type; + if (k2 === ya) { + if (7 === l2.tag) { + c(a2, l2.sibling); + d2 = e(l2, f2.props.children); + d2.return = a2; + a2 = d2; + break a; + } + } else if (l2.elementType === k2 || "object" === typeof k2 && null !== k2 && k2.$$typeof === Ha && Ng(k2) === l2.type) { + c(a2, l2.sibling); + d2 = e(l2, f2.props); + d2.ref = Lg(a2, l2, f2); + d2.return = a2; + a2 = d2; + break a; + } + c(a2, l2); + break; + } else b(a2, l2); + l2 = l2.sibling; + } + f2.type === ya ? (d2 = Tg(f2.props.children, a2.mode, h2, f2.key), d2.return = a2, a2 = d2) : (h2 = Rg(f2.type, f2.key, f2.props, null, a2.mode, h2), h2.ref = Lg(a2, d2, f2), h2.return = a2, a2 = h2); + } + return g(a2); + case wa: + a: { + for (l2 = f2.key; null !== d2; ) { + if (d2.key === l2) if (4 === d2.tag && d2.stateNode.containerInfo === f2.containerInfo && d2.stateNode.implementation === f2.implementation) { + c(a2, d2.sibling); + d2 = e(d2, f2.children || []); + d2.return = a2; + a2 = d2; + break a; + } else { + c(a2, d2); + break; + } + else b(a2, d2); + d2 = d2.sibling; + } + d2 = Sg(f2, a2.mode, h2); + d2.return = a2; + a2 = d2; + } + return g(a2); + case Ha: + return l2 = f2._init, J(a2, d2, l2(f2._payload), h2); + } + if (eb(f2)) return n(a2, d2, f2, h2); + if (Ka(f2)) return t(a2, d2, f2, h2); + Mg(a2, f2); + } + return "string" === typeof f2 && "" !== f2 || "number" === typeof f2 ? (f2 = "" + f2, null !== d2 && 6 === d2.tag ? (c(a2, d2.sibling), d2 = e(d2, f2), d2.return = a2, a2 = d2) : (c(a2, d2), d2 = Qg(f2, a2.mode, h2), d2.return = a2, a2 = d2), g(a2)) : c(a2, d2); + } + return J; + } + var Ug = Og(true), Vg = Og(false), Wg = Uf(null), Xg = null, Yg = null, Zg = null; + function $g() { + Zg = Yg = Xg = null; + } + function ah(a) { + var b = Wg.current; + E(Wg); + a._currentValue = b; + } + function bh(a, b, c) { + for (; null !== a; ) { + var d = a.alternate; + (a.childLanes & b) !== b ? (a.childLanes |= b, null !== d && (d.childLanes |= b)) : null !== d && (d.childLanes & b) !== b && (d.childLanes |= b); + if (a === c) break; + a = a.return; + } + } + function ch(a, b) { + Xg = a; + Zg = Yg = null; + a = a.dependencies; + null !== a && null !== a.firstContext && (0 !== (a.lanes & b) && (dh = true), a.firstContext = null); + } + function eh(a) { + var b = a._currentValue; + if (Zg !== a) if (a = { context: a, memoizedValue: b, next: null }, null === Yg) { + if (null === Xg) throw Error(p(308)); + Yg = a; + Xg.dependencies = { lanes: 0, firstContext: a }; + } else Yg = Yg.next = a; + return b; + } + var fh = null; + function gh(a) { + null === fh ? fh = [a] : fh.push(a); + } + function hh(a, b, c, d) { + var e = b.interleaved; + null === e ? (c.next = c, gh(b)) : (c.next = e.next, e.next = c); + b.interleaved = c; + return ih(a, d); + } + function ih(a, b) { + a.lanes |= b; + var c = a.alternate; + null !== c && (c.lanes |= b); + c = a; + for (a = a.return; null !== a; ) a.childLanes |= b, c = a.alternate, null !== c && (c.childLanes |= b), c = a, a = a.return; + return 3 === c.tag ? c.stateNode : null; + } + var jh = false; + function kh(a) { + a.updateQueue = { baseState: a.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null }; + } + function lh(a, b) { + a = a.updateQueue; + b.updateQueue === a && (b.updateQueue = { baseState: a.baseState, firstBaseUpdate: a.firstBaseUpdate, lastBaseUpdate: a.lastBaseUpdate, shared: a.shared, effects: a.effects }); + } + function mh(a, b) { + return { eventTime: a, lane: b, tag: 0, payload: null, callback: null, next: null }; + } + function nh(a, b, c) { + var d = a.updateQueue; + if (null === d) return null; + d = d.shared; + if (0 !== (K & 2)) { + var e = d.pending; + null === e ? b.next = b : (b.next = e.next, e.next = b); + d.pending = b; + return ih(a, c); + } + e = d.interleaved; + null === e ? (b.next = b, gh(d)) : (b.next = e.next, e.next = b); + d.interleaved = b; + return ih(a, c); + } + function oh(a, b, c) { + b = b.updateQueue; + if (null !== b && (b = b.shared, 0 !== (c & 4194240))) { + var d = b.lanes; + d &= a.pendingLanes; + c |= d; + b.lanes = c; + Cc(a, c); + } + } + function ph(a, b) { + var c = a.updateQueue, d = a.alternate; + if (null !== d && (d = d.updateQueue, c === d)) { + var e = null, f = null; + c = c.firstBaseUpdate; + if (null !== c) { + do { + var g = { eventTime: c.eventTime, lane: c.lane, tag: c.tag, payload: c.payload, callback: c.callback, next: null }; + null === f ? e = f = g : f = f.next = g; + c = c.next; + } while (null !== c); + null === f ? e = f = b : f = f.next = b; + } else e = f = b; + c = { baseState: d.baseState, firstBaseUpdate: e, lastBaseUpdate: f, shared: d.shared, effects: d.effects }; + a.updateQueue = c; + return; + } + a = c.lastBaseUpdate; + null === a ? c.firstBaseUpdate = b : a.next = b; + c.lastBaseUpdate = b; + } + function qh(a, b, c, d) { + var e = a.updateQueue; + jh = false; + var f = e.firstBaseUpdate, g = e.lastBaseUpdate, h = e.shared.pending; + if (null !== h) { + e.shared.pending = null; + var k = h, l = k.next; + k.next = null; + null === g ? f = l : g.next = l; + g = k; + var m = a.alternate; + null !== m && (m = m.updateQueue, h = m.lastBaseUpdate, h !== g && (null === h ? m.firstBaseUpdate = l : h.next = l, m.lastBaseUpdate = k)); + } + if (null !== f) { + var q = e.baseState; + g = 0; + m = l = k = null; + h = f; + do { + var r = h.lane, y = h.eventTime; + if ((d & r) === r) { + null !== m && (m = m.next = { + eventTime: y, + lane: 0, + tag: h.tag, + payload: h.payload, + callback: h.callback, + next: null + }); + a: { + var n = a, t = h; + r = b; + y = c; + switch (t.tag) { + case 1: + n = t.payload; + if ("function" === typeof n) { + q = n.call(y, q, r); + break a; + } + q = n; + break a; + case 3: + n.flags = n.flags & -65537 | 128; + case 0: + n = t.payload; + r = "function" === typeof n ? n.call(y, q, r) : n; + if (null === r || void 0 === r) break a; + q = A({}, q, r); + break a; + case 2: + jh = true; + } + } + null !== h.callback && 0 !== h.lane && (a.flags |= 64, r = e.effects, null === r ? e.effects = [h] : r.push(h)); + } else y = { eventTime: y, lane: r, tag: h.tag, payload: h.payload, callback: h.callback, next: null }, null === m ? (l = m = y, k = q) : m = m.next = y, g |= r; + h = h.next; + if (null === h) if (h = e.shared.pending, null === h) break; + else r = h, h = r.next, r.next = null, e.lastBaseUpdate = r, e.shared.pending = null; + } while (1); + null === m && (k = q); + e.baseState = k; + e.firstBaseUpdate = l; + e.lastBaseUpdate = m; + b = e.shared.interleaved; + if (null !== b) { + e = b; + do + g |= e.lane, e = e.next; + while (e !== b); + } else null === f && (e.shared.lanes = 0); + rh |= g; + a.lanes = g; + a.memoizedState = q; + } + } + function sh(a, b, c) { + a = b.effects; + b.effects = null; + if (null !== a) for (b = 0; b < a.length; b++) { + var d = a[b], e = d.callback; + if (null !== e) { + d.callback = null; + d = c; + if ("function" !== typeof e) throw Error(p(191, e)); + e.call(d); + } + } + } + var th = {}, uh = Uf(th), vh = Uf(th), wh = Uf(th); + function xh(a) { + if (a === th) throw Error(p(174)); + return a; + } + function yh(a, b) { + G(wh, b); + G(vh, a); + G(uh, th); + a = b.nodeType; + switch (a) { + case 9: + case 11: + b = (b = b.documentElement) ? b.namespaceURI : lb(null, ""); + break; + default: + a = 8 === a ? b.parentNode : b, b = a.namespaceURI || null, a = a.tagName, b = lb(b, a); + } + E(uh); + G(uh, b); + } + function zh() { + E(uh); + E(vh); + E(wh); + } + function Ah(a) { + xh(wh.current); + var b = xh(uh.current); + var c = lb(b, a.type); + b !== c && (G(vh, a), G(uh, c)); + } + function Bh(a) { + vh.current === a && (E(uh), E(vh)); + } + var L = Uf(0); + function Ch(a) { + for (var b = a; null !== b; ) { + if (13 === b.tag) { + var c = b.memoizedState; + if (null !== c && (c = c.dehydrated, null === c || "$?" === c.data || "$!" === c.data)) return b; + } else if (19 === b.tag && void 0 !== b.memoizedProps.revealOrder) { + if (0 !== (b.flags & 128)) return b; + } else if (null !== b.child) { + b.child.return = b; + b = b.child; + continue; + } + if (b === a) break; + for (; null === b.sibling; ) { + if (null === b.return || b.return === a) return null; + b = b.return; + } + b.sibling.return = b.return; + b = b.sibling; + } + return null; + } + var Dh = []; + function Eh() { + for (var a = 0; a < Dh.length; a++) Dh[a]._workInProgressVersionPrimary = null; + Dh.length = 0; + } + var Fh = ua.ReactCurrentDispatcher, Gh = ua.ReactCurrentBatchConfig, Hh = 0, M = null, N = null, O = null, Ih = false, Jh = false, Kh = 0, Lh = 0; + function P() { + throw Error(p(321)); + } + function Mh(a, b) { + if (null === b) return false; + for (var c = 0; c < b.length && c < a.length; c++) if (!He(a[c], b[c])) return false; + return true; + } + function Nh(a, b, c, d, e, f) { + Hh = f; + M = b; + b.memoizedState = null; + b.updateQueue = null; + b.lanes = 0; + Fh.current = null === a || null === a.memoizedState ? Oh : Ph; + a = c(d, e); + if (Jh) { + f = 0; + do { + Jh = false; + Kh = 0; + if (25 <= f) throw Error(p(301)); + f += 1; + O = N = null; + b.updateQueue = null; + Fh.current = Qh; + a = c(d, e); + } while (Jh); + } + Fh.current = Rh; + b = null !== N && null !== N.next; + Hh = 0; + O = N = M = null; + Ih = false; + if (b) throw Error(p(300)); + return a; + } + function Sh() { + var a = 0 !== Kh; + Kh = 0; + return a; + } + function Th() { + var a = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null }; + null === O ? M.memoizedState = O = a : O = O.next = a; + return O; + } + function Uh() { + if (null === N) { + var a = M.alternate; + a = null !== a ? a.memoizedState : null; + } else a = N.next; + var b = null === O ? M.memoizedState : O.next; + if (null !== b) O = b, N = a; + else { + if (null === a) throw Error(p(310)); + N = a; + a = { memoizedState: N.memoizedState, baseState: N.baseState, baseQueue: N.baseQueue, queue: N.queue, next: null }; + null === O ? M.memoizedState = O = a : O = O.next = a; + } + return O; + } + function Vh(a, b) { + return "function" === typeof b ? b(a) : b; + } + function Wh(a) { + var b = Uh(), c = b.queue; + if (null === c) throw Error(p(311)); + c.lastRenderedReducer = a; + var d = N, e = d.baseQueue, f = c.pending; + if (null !== f) { + if (null !== e) { + var g = e.next; + e.next = f.next; + f.next = g; + } + d.baseQueue = e = f; + c.pending = null; + } + if (null !== e) { + f = e.next; + d = d.baseState; + var h = g = null, k = null, l = f; + do { + var m = l.lane; + if ((Hh & m) === m) null !== k && (k = k.next = { lane: 0, action: l.action, hasEagerState: l.hasEagerState, eagerState: l.eagerState, next: null }), d = l.hasEagerState ? l.eagerState : a(d, l.action); + else { + var q = { + lane: m, + action: l.action, + hasEagerState: l.hasEagerState, + eagerState: l.eagerState, + next: null + }; + null === k ? (h = k = q, g = d) : k = k.next = q; + M.lanes |= m; + rh |= m; + } + l = l.next; + } while (null !== l && l !== f); + null === k ? g = d : k.next = h; + He(d, b.memoizedState) || (dh = true); + b.memoizedState = d; + b.baseState = g; + b.baseQueue = k; + c.lastRenderedState = d; + } + a = c.interleaved; + if (null !== a) { + e = a; + do + f = e.lane, M.lanes |= f, rh |= f, e = e.next; + while (e !== a); + } else null === e && (c.lanes = 0); + return [b.memoizedState, c.dispatch]; + } + function Xh(a) { + var b = Uh(), c = b.queue; + if (null === c) throw Error(p(311)); + c.lastRenderedReducer = a; + var d = c.dispatch, e = c.pending, f = b.memoizedState; + if (null !== e) { + c.pending = null; + var g = e = e.next; + do + f = a(f, g.action), g = g.next; + while (g !== e); + He(f, b.memoizedState) || (dh = true); + b.memoizedState = f; + null === b.baseQueue && (b.baseState = f); + c.lastRenderedState = f; + } + return [f, d]; + } + function Yh() { + } + function Zh(a, b) { + var c = M, d = Uh(), e = b(), f = !He(d.memoizedState, e); + f && (d.memoizedState = e, dh = true); + d = d.queue; + $h(ai.bind(null, c, d, a), [a]); + if (d.getSnapshot !== b || f || null !== O && O.memoizedState.tag & 1) { + c.flags |= 2048; + bi(9, ci.bind(null, c, d, e, b), void 0, null); + if (null === Q) throw Error(p(349)); + 0 !== (Hh & 30) || di(c, b, e); + } + return e; + } + function di(a, b, c) { + a.flags |= 16384; + a = { getSnapshot: b, value: c }; + b = M.updateQueue; + null === b ? (b = { lastEffect: null, stores: null }, M.updateQueue = b, b.stores = [a]) : (c = b.stores, null === c ? b.stores = [a] : c.push(a)); + } + function ci(a, b, c, d) { + b.value = c; + b.getSnapshot = d; + ei(b) && fi(a); + } + function ai(a, b, c) { + return c(function() { + ei(b) && fi(a); + }); + } + function ei(a) { + var b = a.getSnapshot; + a = a.value; + try { + var c = b(); + return !He(a, c); + } catch (d) { + return true; + } + } + function fi(a) { + var b = ih(a, 1); + null !== b && gi(b, a, 1, -1); + } + function hi(a) { + var b = Th(); + "function" === typeof a && (a = a()); + b.memoizedState = b.baseState = a; + a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Vh, lastRenderedState: a }; + b.queue = a; + a = a.dispatch = ii.bind(null, M, a); + return [b.memoizedState, a]; + } + function bi(a, b, c, d) { + a = { tag: a, create: b, destroy: c, deps: d, next: null }; + b = M.updateQueue; + null === b ? (b = { lastEffect: null, stores: null }, M.updateQueue = b, b.lastEffect = a.next = a) : (c = b.lastEffect, null === c ? b.lastEffect = a.next = a : (d = c.next, c.next = a, a.next = d, b.lastEffect = a)); + return a; + } + function ji() { + return Uh().memoizedState; + } + function ki(a, b, c, d) { + var e = Th(); + M.flags |= a; + e.memoizedState = bi(1 | b, c, void 0, void 0 === d ? null : d); + } + function li(a, b, c, d) { + var e = Uh(); + d = void 0 === d ? null : d; + var f = void 0; + if (null !== N) { + var g = N.memoizedState; + f = g.destroy; + if (null !== d && Mh(d, g.deps)) { + e.memoizedState = bi(b, c, f, d); + return; + } + } + M.flags |= a; + e.memoizedState = bi(1 | b, c, f, d); + } + function mi(a, b) { + return ki(8390656, 8, a, b); + } + function $h(a, b) { + return li(2048, 8, a, b); + } + function ni(a, b) { + return li(4, 2, a, b); + } + function oi(a, b) { + return li(4, 4, a, b); + } + function pi(a, b) { + if ("function" === typeof b) return a = a(), b(a), function() { + b(null); + }; + if (null !== b && void 0 !== b) return a = a(), b.current = a, function() { + b.current = null; + }; + } + function qi(a, b, c) { + c = null !== c && void 0 !== c ? c.concat([a]) : null; + return li(4, 4, pi.bind(null, b, a), c); + } + function ri() { + } + function si(a, b) { + var c = Uh(); + b = void 0 === b ? null : b; + var d = c.memoizedState; + if (null !== d && null !== b && Mh(b, d[1])) return d[0]; + c.memoizedState = [a, b]; + return a; + } + function ti(a, b) { + var c = Uh(); + b = void 0 === b ? null : b; + var d = c.memoizedState; + if (null !== d && null !== b && Mh(b, d[1])) return d[0]; + a = a(); + c.memoizedState = [a, b]; + return a; + } + function ui(a, b, c) { + if (0 === (Hh & 21)) return a.baseState && (a.baseState = false, dh = true), a.memoizedState = c; + He(c, b) || (c = yc(), M.lanes |= c, rh |= c, a.baseState = true); + return b; + } + function vi(a, b) { + var c = C; + C = 0 !== c && 4 > c ? c : 4; + a(true); + var d = Gh.transition; + Gh.transition = {}; + try { + a(false), b(); + } finally { + C = c, Gh.transition = d; + } + } + function wi() { + return Uh().memoizedState; + } + function xi(a, b, c) { + var d = yi(a); + c = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null }; + if (zi(a)) Ai(b, c); + else if (c = hh(a, b, c, d), null !== c) { + var e = R(); + gi(c, a, d, e); + Bi(c, b, d); + } + } + function ii(a, b, c) { + var d = yi(a), e = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null }; + if (zi(a)) Ai(b, e); + else { + var f = a.alternate; + if (0 === a.lanes && (null === f || 0 === f.lanes) && (f = b.lastRenderedReducer, null !== f)) try { + var g = b.lastRenderedState, h = f(g, c); + e.hasEagerState = true; + e.eagerState = h; + if (He(h, g)) { + var k = b.interleaved; + null === k ? (e.next = e, gh(b)) : (e.next = k.next, k.next = e); + b.interleaved = e; + return; + } + } catch (l) { + } finally { + } + c = hh(a, b, e, d); + null !== c && (e = R(), gi(c, a, d, e), Bi(c, b, d)); + } + } + function zi(a) { + var b = a.alternate; + return a === M || null !== b && b === M; + } + function Ai(a, b) { + Jh = Ih = true; + var c = a.pending; + null === c ? b.next = b : (b.next = c.next, c.next = b); + a.pending = b; + } + function Bi(a, b, c) { + if (0 !== (c & 4194240)) { + var d = b.lanes; + d &= a.pendingLanes; + c |= d; + b.lanes = c; + Cc(a, c); + } + } + var Rh = { readContext: eh, useCallback: P, useContext: P, useEffect: P, useImperativeHandle: P, useInsertionEffect: P, useLayoutEffect: P, useMemo: P, useReducer: P, useRef: P, useState: P, useDebugValue: P, useDeferredValue: P, useTransition: P, useMutableSource: P, useSyncExternalStore: P, useId: P, unstable_isNewReconciler: false }, Oh = { readContext: eh, useCallback: function(a, b) { + Th().memoizedState = [a, void 0 === b ? null : b]; + return a; + }, useContext: eh, useEffect: mi, useImperativeHandle: function(a, b, c) { + c = null !== c && void 0 !== c ? c.concat([a]) : null; + return ki( + 4194308, + 4, + pi.bind(null, b, a), + c + ); + }, useLayoutEffect: function(a, b) { + return ki(4194308, 4, a, b); + }, useInsertionEffect: function(a, b) { + return ki(4, 2, a, b); + }, useMemo: function(a, b) { + var c = Th(); + b = void 0 === b ? null : b; + a = a(); + c.memoizedState = [a, b]; + return a; + }, useReducer: function(a, b, c) { + var d = Th(); + b = void 0 !== c ? c(b) : b; + d.memoizedState = d.baseState = b; + a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a, lastRenderedState: b }; + d.queue = a; + a = a.dispatch = xi.bind(null, M, a); + return [d.memoizedState, a]; + }, useRef: function(a) { + var b = Th(); + a = { current: a }; + return b.memoizedState = a; + }, useState: hi, useDebugValue: ri, useDeferredValue: function(a) { + return Th().memoizedState = a; + }, useTransition: function() { + var a = hi(false), b = a[0]; + a = vi.bind(null, a[1]); + Th().memoizedState = a; + return [b, a]; + }, useMutableSource: function() { + }, useSyncExternalStore: function(a, b, c) { + var d = M, e = Th(); + if (I) { + if (void 0 === c) throw Error(p(407)); + c = c(); + } else { + c = b(); + if (null === Q) throw Error(p(349)); + 0 !== (Hh & 30) || di(d, b, c); + } + e.memoizedState = c; + var f = { value: c, getSnapshot: b }; + e.queue = f; + mi(ai.bind( + null, + d, + f, + a + ), [a]); + d.flags |= 2048; + bi(9, ci.bind(null, d, f, c, b), void 0, null); + return c; + }, useId: function() { + var a = Th(), b = Q.identifierPrefix; + if (I) { + var c = sg; + var d = rg; + c = (d & ~(1 << 32 - oc(d) - 1)).toString(32) + c; + b = ":" + b + "R" + c; + c = Kh++; + 0 < c && (b += "H" + c.toString(32)); + b += ":"; + } else c = Lh++, b = ":" + b + "r" + c.toString(32) + ":"; + return a.memoizedState = b; + }, unstable_isNewReconciler: false }, Ph = { + readContext: eh, + useCallback: si, + useContext: eh, + useEffect: $h, + useImperativeHandle: qi, + useInsertionEffect: ni, + useLayoutEffect: oi, + useMemo: ti, + useReducer: Wh, + useRef: ji, + useState: function() { + return Wh(Vh); + }, + useDebugValue: ri, + useDeferredValue: function(a) { + var b = Uh(); + return ui(b, N.memoizedState, a); + }, + useTransition: function() { + var a = Wh(Vh)[0], b = Uh().memoizedState; + return [a, b]; + }, + useMutableSource: Yh, + useSyncExternalStore: Zh, + useId: wi, + unstable_isNewReconciler: false + }, Qh = { readContext: eh, useCallback: si, useContext: eh, useEffect: $h, useImperativeHandle: qi, useInsertionEffect: ni, useLayoutEffect: oi, useMemo: ti, useReducer: Xh, useRef: ji, useState: function() { + return Xh(Vh); + }, useDebugValue: ri, useDeferredValue: function(a) { + var b = Uh(); + return null === N ? b.memoizedState = a : ui(b, N.memoizedState, a); + }, useTransition: function() { + var a = Xh(Vh)[0], b = Uh().memoizedState; + return [a, b]; + }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi, unstable_isNewReconciler: false }; + function Ci(a, b) { + if (a && a.defaultProps) { + b = A({}, b); + a = a.defaultProps; + for (var c in a) void 0 === b[c] && (b[c] = a[c]); + return b; + } + return b; + } + function Di(a, b, c, d) { + b = a.memoizedState; + c = c(d, b); + c = null === c || void 0 === c ? b : A({}, b, c); + a.memoizedState = c; + 0 === a.lanes && (a.updateQueue.baseState = c); + } + var Ei = { isMounted: function(a) { + return (a = a._reactInternals) ? Vb(a) === a : false; + }, enqueueSetState: function(a, b, c) { + a = a._reactInternals; + var d = R(), e = yi(a), f = mh(d, e); + f.payload = b; + void 0 !== c && null !== c && (f.callback = c); + b = nh(a, f, e); + null !== b && (gi(b, a, e, d), oh(b, a, e)); + }, enqueueReplaceState: function(a, b, c) { + a = a._reactInternals; + var d = R(), e = yi(a), f = mh(d, e); + f.tag = 1; + f.payload = b; + void 0 !== c && null !== c && (f.callback = c); + b = nh(a, f, e); + null !== b && (gi(b, a, e, d), oh(b, a, e)); + }, enqueueForceUpdate: function(a, b) { + a = a._reactInternals; + var c = R(), d = yi(a), e = mh(c, d); + e.tag = 2; + void 0 !== b && null !== b && (e.callback = b); + b = nh(a, e, d); + null !== b && (gi(b, a, d, c), oh(b, a, d)); + } }; + function Fi(a, b, c, d, e, f, g) { + a = a.stateNode; + return "function" === typeof a.shouldComponentUpdate ? a.shouldComponentUpdate(d, f, g) : b.prototype && b.prototype.isPureReactComponent ? !Ie(c, d) || !Ie(e, f) : true; + } + function Gi(a, b, c) { + var d = false, e = Vf; + var f = b.contextType; + "object" === typeof f && null !== f ? f = eh(f) : (e = Zf(b) ? Xf : H.current, d = b.contextTypes, f = (d = null !== d && void 0 !== d) ? Yf(a, e) : Vf); + b = new b(c, f); + a.memoizedState = null !== b.state && void 0 !== b.state ? b.state : null; + b.updater = Ei; + a.stateNode = b; + b._reactInternals = a; + d && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = e, a.__reactInternalMemoizedMaskedChildContext = f); + return b; + } + function Hi(a, b, c, d) { + a = b.state; + "function" === typeof b.componentWillReceiveProps && b.componentWillReceiveProps(c, d); + "function" === typeof b.UNSAFE_componentWillReceiveProps && b.UNSAFE_componentWillReceiveProps(c, d); + b.state !== a && Ei.enqueueReplaceState(b, b.state, null); + } + function Ii(a, b, c, d) { + var e = a.stateNode; + e.props = c; + e.state = a.memoizedState; + e.refs = {}; + kh(a); + var f = b.contextType; + "object" === typeof f && null !== f ? e.context = eh(f) : (f = Zf(b) ? Xf : H.current, e.context = Yf(a, f)); + e.state = a.memoizedState; + f = b.getDerivedStateFromProps; + "function" === typeof f && (Di(a, b, f, c), e.state = a.memoizedState); + "function" === typeof b.getDerivedStateFromProps || "function" === typeof e.getSnapshotBeforeUpdate || "function" !== typeof e.UNSAFE_componentWillMount && "function" !== typeof e.componentWillMount || (b = e.state, "function" === typeof e.componentWillMount && e.componentWillMount(), "function" === typeof e.UNSAFE_componentWillMount && e.UNSAFE_componentWillMount(), b !== e.state && Ei.enqueueReplaceState(e, e.state, null), qh(a, c, e, d), e.state = a.memoizedState); + "function" === typeof e.componentDidMount && (a.flags |= 4194308); + } + function Ji(a, b) { + try { + var c = "", d = b; + do + c += Pa(d), d = d.return; + while (d); + var e = c; + } catch (f) { + e = "\nError generating stack: " + f.message + "\n" + f.stack; + } + return { value: a, source: b, stack: e, digest: null }; + } + function Ki(a, b, c) { + return { value: a, source: null, stack: null != c ? c : null, digest: null != b ? b : null }; + } + function Li(a, b) { + try { + console.error(b.value); + } catch (c) { + setTimeout(function() { + throw c; + }); + } + } + var Mi = "function" === typeof WeakMap ? WeakMap : Map; + function Ni(a, b, c) { + c = mh(-1, c); + c.tag = 3; + c.payload = { element: null }; + var d = b.value; + c.callback = function() { + Oi || (Oi = true, Pi = d); + Li(a, b); + }; + return c; + } + function Qi(a, b, c) { + c = mh(-1, c); + c.tag = 3; + var d = a.type.getDerivedStateFromError; + if ("function" === typeof d) { + var e = b.value; + c.payload = function() { + return d(e); + }; + c.callback = function() { + Li(a, b); + }; + } + var f = a.stateNode; + null !== f && "function" === typeof f.componentDidCatch && (c.callback = function() { + Li(a, b); + "function" !== typeof d && (null === Ri ? Ri = /* @__PURE__ */ new Set([this]) : Ri.add(this)); + var c2 = b.stack; + this.componentDidCatch(b.value, { componentStack: null !== c2 ? c2 : "" }); + }); + return c; + } + function Si(a, b, c) { + var d = a.pingCache; + if (null === d) { + d = a.pingCache = new Mi(); + var e = /* @__PURE__ */ new Set(); + d.set(b, e); + } else e = d.get(b), void 0 === e && (e = /* @__PURE__ */ new Set(), d.set(b, e)); + e.has(c) || (e.add(c), a = Ti.bind(null, a, b, c), b.then(a, a)); + } + function Ui(a) { + do { + var b; + if (b = 13 === a.tag) b = a.memoizedState, b = null !== b ? null !== b.dehydrated ? true : false : true; + if (b) return a; + a = a.return; + } while (null !== a); + return null; + } + function Vi(a, b, c, d, e) { + if (0 === (a.mode & 1)) return a === b ? a.flags |= 65536 : (a.flags |= 128, c.flags |= 131072, c.flags &= -52805, 1 === c.tag && (null === c.alternate ? c.tag = 17 : (b = mh(-1, 1), b.tag = 2, nh(c, b, 1))), c.lanes |= 1), a; + a.flags |= 65536; + a.lanes = e; + return a; + } + var Wi = ua.ReactCurrentOwner, dh = false; + function Xi(a, b, c, d) { + b.child = null === a ? Vg(b, null, c, d) : Ug(b, a.child, c, d); + } + function Yi(a, b, c, d, e) { + c = c.render; + var f = b.ref; + ch(b, e); + d = Nh(a, b, c, d, f, e); + c = Sh(); + if (null !== a && !dh) return b.updateQueue = a.updateQueue, b.flags &= -2053, a.lanes &= ~e, Zi(a, b, e); + I && c && vg(b); + b.flags |= 1; + Xi(a, b, d, e); + return b.child; + } + function $i(a, b, c, d, e) { + if (null === a) { + var f = c.type; + if ("function" === typeof f && !aj(f) && void 0 === f.defaultProps && null === c.compare && void 0 === c.defaultProps) return b.tag = 15, b.type = f, bj(a, b, f, d, e); + a = Rg(c.type, null, d, b, b.mode, e); + a.ref = b.ref; + a.return = b; + return b.child = a; + } + f = a.child; + if (0 === (a.lanes & e)) { + var g = f.memoizedProps; + c = c.compare; + c = null !== c ? c : Ie; + if (c(g, d) && a.ref === b.ref) return Zi(a, b, e); + } + b.flags |= 1; + a = Pg(f, d); + a.ref = b.ref; + a.return = b; + return b.child = a; + } + function bj(a, b, c, d, e) { + if (null !== a) { + var f = a.memoizedProps; + if (Ie(f, d) && a.ref === b.ref) if (dh = false, b.pendingProps = d = f, 0 !== (a.lanes & e)) 0 !== (a.flags & 131072) && (dh = true); + else return b.lanes = a.lanes, Zi(a, b, e); + } + return cj(a, b, c, d, e); + } + function dj(a, b, c) { + var d = b.pendingProps, e = d.children, f = null !== a ? a.memoizedState : null; + if ("hidden" === d.mode) if (0 === (b.mode & 1)) b.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }, G(ej, fj), fj |= c; + else { + if (0 === (c & 1073741824)) return a = null !== f ? f.baseLanes | c : c, b.lanes = b.childLanes = 1073741824, b.memoizedState = { baseLanes: a, cachePool: null, transitions: null }, b.updateQueue = null, G(ej, fj), fj |= a, null; + b.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }; + d = null !== f ? f.baseLanes : c; + G(ej, fj); + fj |= d; + } + else null !== f ? (d = f.baseLanes | c, b.memoizedState = null) : d = c, G(ej, fj), fj |= d; + Xi(a, b, e, c); + return b.child; + } + function gj(a, b) { + var c = b.ref; + if (null === a && null !== c || null !== a && a.ref !== c) b.flags |= 512, b.flags |= 2097152; + } + function cj(a, b, c, d, e) { + var f = Zf(c) ? Xf : H.current; + f = Yf(b, f); + ch(b, e); + c = Nh(a, b, c, d, f, e); + d = Sh(); + if (null !== a && !dh) return b.updateQueue = a.updateQueue, b.flags &= -2053, a.lanes &= ~e, Zi(a, b, e); + I && d && vg(b); + b.flags |= 1; + Xi(a, b, c, e); + return b.child; + } + function hj(a, b, c, d, e) { + if (Zf(c)) { + var f = true; + cg(b); + } else f = false; + ch(b, e); + if (null === b.stateNode) ij(a, b), Gi(b, c, d), Ii(b, c, d, e), d = true; + else if (null === a) { + var g = b.stateNode, h = b.memoizedProps; + g.props = h; + var k = g.context, l = c.contextType; + "object" === typeof l && null !== l ? l = eh(l) : (l = Zf(c) ? Xf : H.current, l = Yf(b, l)); + var m = c.getDerivedStateFromProps, q = "function" === typeof m || "function" === typeof g.getSnapshotBeforeUpdate; + q || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h !== d || k !== l) && Hi(b, g, d, l); + jh = false; + var r = b.memoizedState; + g.state = r; + qh(b, d, g, e); + k = b.memoizedState; + h !== d || r !== k || Wf.current || jh ? ("function" === typeof m && (Di(b, c, m, d), k = b.memoizedState), (h = jh || Fi(b, c, h, d, r, k, l)) ? (q || "function" !== typeof g.UNSAFE_componentWillMount && "function" !== typeof g.componentWillMount || ("function" === typeof g.componentWillMount && g.componentWillMount(), "function" === typeof g.UNSAFE_componentWillMount && g.UNSAFE_componentWillMount()), "function" === typeof g.componentDidMount && (b.flags |= 4194308)) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), b.memoizedProps = d, b.memoizedState = k), g.props = d, g.state = k, g.context = l, d = h) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), d = false); + } else { + g = b.stateNode; + lh(a, b); + h = b.memoizedProps; + l = b.type === b.elementType ? h : Ci(b.type, h); + g.props = l; + q = b.pendingProps; + r = g.context; + k = c.contextType; + "object" === typeof k && null !== k ? k = eh(k) : (k = Zf(c) ? Xf : H.current, k = Yf(b, k)); + var y = c.getDerivedStateFromProps; + (m = "function" === typeof y || "function" === typeof g.getSnapshotBeforeUpdate) || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h !== q || r !== k) && Hi(b, g, d, k); + jh = false; + r = b.memoizedState; + g.state = r; + qh(b, d, g, e); + var n = b.memoizedState; + h !== q || r !== n || Wf.current || jh ? ("function" === typeof y && (Di(b, c, y, d), n = b.memoizedState), (l = jh || Fi(b, c, l, d, r, n, k) || false) ? (m || "function" !== typeof g.UNSAFE_componentWillUpdate && "function" !== typeof g.componentWillUpdate || ("function" === typeof g.componentWillUpdate && g.componentWillUpdate(d, n, k), "function" === typeof g.UNSAFE_componentWillUpdate && g.UNSAFE_componentWillUpdate(d, n, k)), "function" === typeof g.componentDidUpdate && (b.flags |= 4), "function" === typeof g.getSnapshotBeforeUpdate && (b.flags |= 1024)) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 1024), b.memoizedProps = d, b.memoizedState = n), g.props = d, g.state = n, g.context = k, d = l) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 1024), d = false); + } + return jj(a, b, c, d, f, e); + } + function jj(a, b, c, d, e, f) { + gj(a, b); + var g = 0 !== (b.flags & 128); + if (!d && !g) return e && dg(b, c, false), Zi(a, b, f); + d = b.stateNode; + Wi.current = b; + var h = g && "function" !== typeof c.getDerivedStateFromError ? null : d.render(); + b.flags |= 1; + null !== a && g ? (b.child = Ug(b, a.child, null, f), b.child = Ug(b, null, h, f)) : Xi(a, b, h, f); + b.memoizedState = d.state; + e && dg(b, c, true); + return b.child; + } + function kj(a) { + var b = a.stateNode; + b.pendingContext ? ag(a, b.pendingContext, b.pendingContext !== b.context) : b.context && ag(a, b.context, false); + yh(a, b.containerInfo); + } + function lj(a, b, c, d, e) { + Ig(); + Jg(e); + b.flags |= 256; + Xi(a, b, c, d); + return b.child; + } + var mj = { dehydrated: null, treeContext: null, retryLane: 0 }; + function nj(a) { + return { baseLanes: a, cachePool: null, transitions: null }; + } + function oj(a, b, c) { + var d = b.pendingProps, e = L.current, f = false, g = 0 !== (b.flags & 128), h; + (h = g) || (h = null !== a && null === a.memoizedState ? false : 0 !== (e & 2)); + if (h) f = true, b.flags &= -129; + else if (null === a || null !== a.memoizedState) e |= 1; + G(L, e & 1); + if (null === a) { + Eg(b); + a = b.memoizedState; + if (null !== a && (a = a.dehydrated, null !== a)) return 0 === (b.mode & 1) ? b.lanes = 1 : "$!" === a.data ? b.lanes = 8 : b.lanes = 1073741824, null; + g = d.children; + a = d.fallback; + return f ? (d = b.mode, f = b.child, g = { mode: "hidden", children: g }, 0 === (d & 1) && null !== f ? (f.childLanes = 0, f.pendingProps = g) : f = pj(g, d, 0, null), a = Tg(a, d, c, null), f.return = b, a.return = b, f.sibling = a, b.child = f, b.child.memoizedState = nj(c), b.memoizedState = mj, a) : qj(b, g); + } + e = a.memoizedState; + if (null !== e && (h = e.dehydrated, null !== h)) return rj(a, b, g, d, h, e, c); + if (f) { + f = d.fallback; + g = b.mode; + e = a.child; + h = e.sibling; + var k = { mode: "hidden", children: d.children }; + 0 === (g & 1) && b.child !== e ? (d = b.child, d.childLanes = 0, d.pendingProps = k, b.deletions = null) : (d = Pg(e, k), d.subtreeFlags = e.subtreeFlags & 14680064); + null !== h ? f = Pg(h, f) : (f = Tg(f, g, c, null), f.flags |= 2); + f.return = b; + d.return = b; + d.sibling = f; + b.child = d; + d = f; + f = b.child; + g = a.child.memoizedState; + g = null === g ? nj(c) : { baseLanes: g.baseLanes | c, cachePool: null, transitions: g.transitions }; + f.memoizedState = g; + f.childLanes = a.childLanes & ~c; + b.memoizedState = mj; + return d; + } + f = a.child; + a = f.sibling; + d = Pg(f, { mode: "visible", children: d.children }); + 0 === (b.mode & 1) && (d.lanes = c); + d.return = b; + d.sibling = null; + null !== a && (c = b.deletions, null === c ? (b.deletions = [a], b.flags |= 16) : c.push(a)); + b.child = d; + b.memoizedState = null; + return d; + } + function qj(a, b) { + b = pj({ mode: "visible", children: b }, a.mode, 0, null); + b.return = a; + return a.child = b; + } + function sj(a, b, c, d) { + null !== d && Jg(d); + Ug(b, a.child, null, c); + a = qj(b, b.pendingProps.children); + a.flags |= 2; + b.memoizedState = null; + return a; + } + function rj(a, b, c, d, e, f, g) { + if (c) { + if (b.flags & 256) return b.flags &= -257, d = Ki(Error(p(422))), sj(a, b, g, d); + if (null !== b.memoizedState) return b.child = a.child, b.flags |= 128, null; + f = d.fallback; + e = b.mode; + d = pj({ mode: "visible", children: d.children }, e, 0, null); + f = Tg(f, e, g, null); + f.flags |= 2; + d.return = b; + f.return = b; + d.sibling = f; + b.child = d; + 0 !== (b.mode & 1) && Ug(b, a.child, null, g); + b.child.memoizedState = nj(g); + b.memoizedState = mj; + return f; + } + if (0 === (b.mode & 1)) return sj(a, b, g, null); + if ("$!" === e.data) { + d = e.nextSibling && e.nextSibling.dataset; + if (d) var h = d.dgst; + d = h; + f = Error(p(419)); + d = Ki(f, d, void 0); + return sj(a, b, g, d); + } + h = 0 !== (g & a.childLanes); + if (dh || h) { + d = Q; + if (null !== d) { + switch (g & -g) { + case 4: + e = 2; + break; + case 16: + e = 8; + break; + case 64: + case 128: + case 256: + case 512: + case 1024: + case 2048: + case 4096: + case 8192: + case 16384: + case 32768: + case 65536: + case 131072: + case 262144: + case 524288: + case 1048576: + case 2097152: + case 4194304: + case 8388608: + case 16777216: + case 33554432: + case 67108864: + e = 32; + break; + case 536870912: + e = 268435456; + break; + default: + e = 0; + } + e = 0 !== (e & (d.suspendedLanes | g)) ? 0 : e; + 0 !== e && e !== f.retryLane && (f.retryLane = e, ih(a, e), gi(d, a, e, -1)); + } + tj(); + d = Ki(Error(p(421))); + return sj(a, b, g, d); + } + if ("$?" === e.data) return b.flags |= 128, b.child = a.child, b = uj.bind(null, a), e._reactRetry = b, null; + a = f.treeContext; + yg = Lf(e.nextSibling); + xg = b; + I = true; + zg = null; + null !== a && (og[pg++] = rg, og[pg++] = sg, og[pg++] = qg, rg = a.id, sg = a.overflow, qg = b); + b = qj(b, d.children); + b.flags |= 4096; + return b; + } + function vj(a, b, c) { + a.lanes |= b; + var d = a.alternate; + null !== d && (d.lanes |= b); + bh(a.return, b, c); + } + function wj(a, b, c, d, e) { + var f = a.memoizedState; + null === f ? a.memoizedState = { isBackwards: b, rendering: null, renderingStartTime: 0, last: d, tail: c, tailMode: e } : (f.isBackwards = b, f.rendering = null, f.renderingStartTime = 0, f.last = d, f.tail = c, f.tailMode = e); + } + function xj(a, b, c) { + var d = b.pendingProps, e = d.revealOrder, f = d.tail; + Xi(a, b, d.children, c); + d = L.current; + if (0 !== (d & 2)) d = d & 1 | 2, b.flags |= 128; + else { + if (null !== a && 0 !== (a.flags & 128)) a: for (a = b.child; null !== a; ) { + if (13 === a.tag) null !== a.memoizedState && vj(a, c, b); + else if (19 === a.tag) vj(a, c, b); + else if (null !== a.child) { + a.child.return = a; + a = a.child; + continue; + } + if (a === b) break a; + for (; null === a.sibling; ) { + if (null === a.return || a.return === b) break a; + a = a.return; + } + a.sibling.return = a.return; + a = a.sibling; + } + d &= 1; + } + G(L, d); + if (0 === (b.mode & 1)) b.memoizedState = null; + else switch (e) { + case "forwards": + c = b.child; + for (e = null; null !== c; ) a = c.alternate, null !== a && null === Ch(a) && (e = c), c = c.sibling; + c = e; + null === c ? (e = b.child, b.child = null) : (e = c.sibling, c.sibling = null); + wj(b, false, e, c, f); + break; + case "backwards": + c = null; + e = b.child; + for (b.child = null; null !== e; ) { + a = e.alternate; + if (null !== a && null === Ch(a)) { + b.child = e; + break; + } + a = e.sibling; + e.sibling = c; + c = e; + e = a; + } + wj(b, true, c, null, f); + break; + case "together": + wj(b, false, null, null, void 0); + break; + default: + b.memoizedState = null; + } + return b.child; + } + function ij(a, b) { + 0 === (b.mode & 1) && null !== a && (a.alternate = null, b.alternate = null, b.flags |= 2); + } + function Zi(a, b, c) { + null !== a && (b.dependencies = a.dependencies); + rh |= b.lanes; + if (0 === (c & b.childLanes)) return null; + if (null !== a && b.child !== a.child) throw Error(p(153)); + if (null !== b.child) { + a = b.child; + c = Pg(a, a.pendingProps); + b.child = c; + for (c.return = b; null !== a.sibling; ) a = a.sibling, c = c.sibling = Pg(a, a.pendingProps), c.return = b; + c.sibling = null; + } + return b.child; + } + function yj(a, b, c) { + switch (b.tag) { + case 3: + kj(b); + Ig(); + break; + case 5: + Ah(b); + break; + case 1: + Zf(b.type) && cg(b); + break; + case 4: + yh(b, b.stateNode.containerInfo); + break; + case 10: + var d = b.type._context, e = b.memoizedProps.value; + G(Wg, d._currentValue); + d._currentValue = e; + break; + case 13: + d = b.memoizedState; + if (null !== d) { + if (null !== d.dehydrated) return G(L, L.current & 1), b.flags |= 128, null; + if (0 !== (c & b.child.childLanes)) return oj(a, b, c); + G(L, L.current & 1); + a = Zi(a, b, c); + return null !== a ? a.sibling : null; + } + G(L, L.current & 1); + break; + case 19: + d = 0 !== (c & b.childLanes); + if (0 !== (a.flags & 128)) { + if (d) return xj(a, b, c); + b.flags |= 128; + } + e = b.memoizedState; + null !== e && (e.rendering = null, e.tail = null, e.lastEffect = null); + G(L, L.current); + if (d) break; + else return null; + case 22: + case 23: + return b.lanes = 0, dj(a, b, c); + } + return Zi(a, b, c); + } + var zj, Aj, Bj, Cj; + zj = function(a, b) { + for (var c = b.child; null !== c; ) { + if (5 === c.tag || 6 === c.tag) a.appendChild(c.stateNode); + else if (4 !== c.tag && null !== c.child) { + c.child.return = c; + c = c.child; + continue; + } + if (c === b) break; + for (; null === c.sibling; ) { + if (null === c.return || c.return === b) return; + c = c.return; + } + c.sibling.return = c.return; + c = c.sibling; + } + }; + Aj = function() { + }; + Bj = function(a, b, c, d) { + var e = a.memoizedProps; + if (e !== d) { + a = b.stateNode; + xh(uh.current); + var f = null; + switch (c) { + case "input": + e = Ya(a, e); + d = Ya(a, d); + f = []; + break; + case "select": + e = A({}, e, { value: void 0 }); + d = A({}, d, { value: void 0 }); + f = []; + break; + case "textarea": + e = gb(a, e); + d = gb(a, d); + f = []; + break; + default: + "function" !== typeof e.onClick && "function" === typeof d.onClick && (a.onclick = Bf); + } + ub(c, d); + var g; + c = null; + for (l in e) if (!d.hasOwnProperty(l) && e.hasOwnProperty(l) && null != e[l]) if ("style" === l) { + var h = e[l]; + for (g in h) h.hasOwnProperty(g) && (c || (c = {}), c[g] = ""); + } else "dangerouslySetInnerHTML" !== l && "children" !== l && "suppressContentEditableWarning" !== l && "suppressHydrationWarning" !== l && "autoFocus" !== l && (ea.hasOwnProperty(l) ? f || (f = []) : (f = f || []).push(l, null)); + for (l in d) { + var k = d[l]; + h = null != e ? e[l] : void 0; + if (d.hasOwnProperty(l) && k !== h && (null != k || null != h)) if ("style" === l) if (h) { + for (g in h) !h.hasOwnProperty(g) || k && k.hasOwnProperty(g) || (c || (c = {}), c[g] = ""); + for (g in k) k.hasOwnProperty(g) && h[g] !== k[g] && (c || (c = {}), c[g] = k[g]); + } else c || (f || (f = []), f.push( + l, + c + )), c = k; + else "dangerouslySetInnerHTML" === l ? (k = k ? k.__html : void 0, h = h ? h.__html : void 0, null != k && h !== k && (f = f || []).push(l, k)) : "children" === l ? "string" !== typeof k && "number" !== typeof k || (f = f || []).push(l, "" + k) : "suppressContentEditableWarning" !== l && "suppressHydrationWarning" !== l && (ea.hasOwnProperty(l) ? (null != k && "onScroll" === l && D("scroll", a), f || h === k || (f = [])) : (f = f || []).push(l, k)); + } + c && (f = f || []).push("style", c); + var l = f; + if (b.updateQueue = l) b.flags |= 4; + } + }; + Cj = function(a, b, c, d) { + c !== d && (b.flags |= 4); + }; + function Dj(a, b) { + if (!I) switch (a.tailMode) { + case "hidden": + b = a.tail; + for (var c = null; null !== b; ) null !== b.alternate && (c = b), b = b.sibling; + null === c ? a.tail = null : c.sibling = null; + break; + case "collapsed": + c = a.tail; + for (var d = null; null !== c; ) null !== c.alternate && (d = c), c = c.sibling; + null === d ? b || null === a.tail ? a.tail = null : a.tail.sibling = null : d.sibling = null; + } + } + function S(a) { + var b = null !== a.alternate && a.alternate.child === a.child, c = 0, d = 0; + if (b) for (var e = a.child; null !== e; ) c |= e.lanes | e.childLanes, d |= e.subtreeFlags & 14680064, d |= e.flags & 14680064, e.return = a, e = e.sibling; + else for (e = a.child; null !== e; ) c |= e.lanes | e.childLanes, d |= e.subtreeFlags, d |= e.flags, e.return = a, e = e.sibling; + a.subtreeFlags |= d; + a.childLanes = c; + return b; + } + function Ej(a, b, c) { + var d = b.pendingProps; + wg(b); + switch (b.tag) { + case 2: + case 16: + case 15: + case 0: + case 11: + case 7: + case 8: + case 12: + case 9: + case 14: + return S(b), null; + case 1: + return Zf(b.type) && $f(), S(b), null; + case 3: + d = b.stateNode; + zh(); + E(Wf); + E(H); + Eh(); + d.pendingContext && (d.context = d.pendingContext, d.pendingContext = null); + if (null === a || null === a.child) Gg(b) ? b.flags |= 4 : null === a || a.memoizedState.isDehydrated && 0 === (b.flags & 256) || (b.flags |= 1024, null !== zg && (Fj(zg), zg = null)); + Aj(a, b); + S(b); + return null; + case 5: + Bh(b); + var e = xh(wh.current); + c = b.type; + if (null !== a && null != b.stateNode) Bj(a, b, c, d, e), a.ref !== b.ref && (b.flags |= 512, b.flags |= 2097152); + else { + if (!d) { + if (null === b.stateNode) throw Error(p(166)); + S(b); + return null; + } + a = xh(uh.current); + if (Gg(b)) { + d = b.stateNode; + c = b.type; + var f = b.memoizedProps; + d[Of] = b; + d[Pf] = f; + a = 0 !== (b.mode & 1); + switch (c) { + case "dialog": + D("cancel", d); + D("close", d); + break; + case "iframe": + case "object": + case "embed": + D("load", d); + break; + case "video": + case "audio": + for (e = 0; e < lf.length; e++) D(lf[e], d); + break; + case "source": + D("error", d); + break; + case "img": + case "image": + case "link": + D( + "error", + d + ); + D("load", d); + break; + case "details": + D("toggle", d); + break; + case "input": + Za(d, f); + D("invalid", d); + break; + case "select": + d._wrapperState = { wasMultiple: !!f.multiple }; + D("invalid", d); + break; + case "textarea": + hb(d, f), D("invalid", d); + } + ub(c, f); + e = null; + for (var g in f) if (f.hasOwnProperty(g)) { + var h = f[g]; + "children" === g ? "string" === typeof h ? d.textContent !== h && (true !== f.suppressHydrationWarning && Af(d.textContent, h, a), e = ["children", h]) : "number" === typeof h && d.textContent !== "" + h && (true !== f.suppressHydrationWarning && Af( + d.textContent, + h, + a + ), e = ["children", "" + h]) : ea.hasOwnProperty(g) && null != h && "onScroll" === g && D("scroll", d); + } + switch (c) { + case "input": + Va(d); + db(d, f, true); + break; + case "textarea": + Va(d); + jb(d); + break; + case "select": + case "option": + break; + default: + "function" === typeof f.onClick && (d.onclick = Bf); + } + d = e; + b.updateQueue = d; + null !== d && (b.flags |= 4); + } else { + g = 9 === e.nodeType ? e : e.ownerDocument; + "http://www.w3.org/1999/xhtml" === a && (a = kb(c)); + "http://www.w3.org/1999/xhtml" === a ? "script" === c ? (a = g.createElement("div"), a.innerHTML = " + + + + + + +
+ + diff --git a/extension/edge-share-crx/index.js b/extension/edge-share-crx/index.js new file mode 100644 index 0000000..b4e9929 --- /dev/null +++ b/extension/edge-share-crx/index.js @@ -0,0 +1,10229 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["codeMirrorModule.js","form.js","settings.js","form.css","codeMirrorModule.css"])))=>i.map(i=>d[i]); +import { R as React, j as jsxRuntimeExports, r as reactExports, P as PreferencesForm, c as clientExports } from "./form.js"; +import { d as defaultSettings, l as loadSettings, a as addSettingsChangedListener, r as removeSettingsChangedListener } from "./settings.js"; +function useMeasure() { + const ref = React.useRef(null); + const [measure, setMeasure] = React.useState(new DOMRect(0, 0, 10, 10)); + React.useLayoutEffect(() => { + const target = ref.current; + if (!target) + return; + const bounds = target.getBoundingClientRect(); + setMeasure(new DOMRect(0, 0, bounds.width, bounds.height)); + const resizeObserver = new ResizeObserver((entries) => { + const entry = entries[entries.length - 1]; + if (entry && entry.contentRect) + setMeasure(entry.contentRect); + }); + resizeObserver.observe(target); + return () => resizeObserver.disconnect(); + }, [ref]); + return [measure, ref]; +} +function msToString(ms) { + if (ms < 0 || !isFinite(ms)) + return "-"; + if (ms === 0) + return "0"; + if (ms < 1e3) + return ms.toFixed(0) + "ms"; + const seconds = ms / 1e3; + if (seconds < 60) + return seconds.toFixed(1) + "s"; + const minutes = seconds / 60; + if (minutes < 60) + return minutes.toFixed(1) + "m"; + const hours = minutes / 60; + if (hours < 24) + return hours.toFixed(1) + "h"; + const days = hours / 24; + return days.toFixed(1) + "d"; +} +function copy(text) { + const textArea = document.createElement("textarea"); + textArea.style.position = "absolute"; + textArea.style.zIndex = "-1000"; + textArea.value = text; + document.body.appendChild(textArea); + textArea.select(); + document.execCommand("copy"); + textArea.remove(); +} +function useSetting(name, defaultValue) { + if (name) + defaultValue = settings.getObject(name, defaultValue); + const [value, setValue] = React.useState(defaultValue); + const setValueWrapper = React.useCallback((value2) => { + if (name) + settings.setObject(name, value2); + else + setValue(value2); + }, [name, setValue]); + React.useEffect(() => { + if (name) { + const onStoreChange = () => setValue(settings.getObject(name, defaultValue)); + settings.onChangeEmitter.addEventListener(name, onStoreChange); + return () => settings.onChangeEmitter.removeEventListener(name, onStoreChange); + } + }, [defaultValue, name]); + return [value, setValueWrapper]; +} +class Settings { + constructor() { + this.onChangeEmitter = new EventTarget(); + } + getString(name, defaultValue) { + return localStorage[name] || defaultValue; + } + setString(name, value) { + var _a; + localStorage[name] = value; + this.onChangeEmitter.dispatchEvent(new Event(name)); + (_a = window.saveSettings) == null ? void 0 : _a.call(window); + } + getObject(name, defaultValue) { + if (!localStorage[name]) + return defaultValue; + try { + return JSON.parse(localStorage[name]); + } catch { + return defaultValue; + } + } + setObject(name, value) { + var _a; + localStorage[name] = JSON.stringify(value); + this.onChangeEmitter.dispatchEvent(new Event(name)); + (_a = window.saveSettings) == null ? void 0 : _a.call(window); + } +} +const settings = new Settings(); +function clsx(...classes) { + return classes.filter(Boolean).join(" "); +} +const kControlCodesRe = "\\u0000-\\u0020\\u007f-\\u009f"; +const kWebLinkRe = new RegExp("(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|www\\.)[^\\s" + kControlCodesRe + '"]{2,}[^\\s' + kControlCodesRe + `"')}\\],:;.!?]`, "ug"); +function applyTheme() { + if (document.playwrightThemeInitialized) + return; + document.playwrightThemeInitialized = true; + document.defaultView.addEventListener("focus", (event) => { + if (event.target.document.nodeType === Node.DOCUMENT_NODE) + document.body.classList.remove("inactive"); + }, false); + document.defaultView.addEventListener("blur", (event) => { + document.body.classList.add("inactive"); + }, false); + const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)"); + const defaultTheme = prefersDarkScheme.matches ? "dark-mode" : "light-mode"; + const currentTheme2 = settings.getString("theme", defaultTheme); + if (currentTheme2 === "dark-mode") + document.body.classList.add("dark-mode"); +} +const listeners = /* @__PURE__ */ new Set(); +function toggleTheme() { + const oldTheme = currentTheme(); + const newTheme = oldTheme === "dark-mode" ? "light-mode" : "dark-mode"; + if (oldTheme) + document.body.classList.remove(oldTheme); + document.body.classList.add(newTheme); + settings.setString("theme", newTheme); + for (const listener of listeners) + listener(newTheme); +} +function currentTheme() { + return document.body.classList.contains("dark-mode") ? "dark-mode" : "light-mode"; +} +const Toolbar = ({ + noShadow, + children, + noMinHeight, + className, + sidebarBackground, + onClick +}) => { + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx("toolbar", noShadow && "no-shadow", noMinHeight && "no-min-height", className, sidebarBackground && "toolbar-sidebar-background"), onClick, children }); +}; +const ToolbarButton = reactExports.forwardRef(function ToolbarButton2({ + children, + title = "", + icon, + disabled = false, + toggled = false, + onClick = () => { + }, + style, + testId, + className, + ariaLabel +}, ref) { + return /* @__PURE__ */ jsxRuntimeExports.jsxs( + "button", + { + ref, + className: clsx(className, "toolbar-button", icon, toggled && "toggled"), + onMouseDown: preventDefault, + onClick, + onDoubleClick: preventDefault, + title, + disabled: !!disabled, + style, + "data-testid": testId, + "aria-label": ariaLabel || title, + children: [ + icon && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `codicon codicon-${icon}`, style: children ? { marginRight: 5 } : {} }), + children + ] + } + ); +}); +const ToolbarSeparator = ({ + style +}) => { + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "toolbar-separator", style }); +}; +const preventDefault = (e) => { + e.stopPropagation(); + e.preventDefault(); +}; +const Dialog = ({ isOpen, onClose, title, children }) => { + if (!isOpen) + return null; + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "dialog-overlay", role: "dialog", "aria-label": title, onClick: onClose, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "dialog-box", onClick: (e) => e.stopPropagation(), children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "dialog-header", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: title }), + /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "dialog-close", onClick: onClose, children: "×" }) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "dialog-content", children }) + ] }) }); +}; +const scriptRel = "modulepreload"; +const assetsURL = function(dep) { + return "/" + dep; +}; +const seen = {}; +const __vitePreload = function preload(baseModule, deps, importerUrl) { + let promise = Promise.resolve(); + if (deps && deps.length > 0) { + let allSettled2 = function(promises) { + return Promise.all( + promises.map( + (p) => Promise.resolve(p).then( + (value) => ({ status: "fulfilled", value }), + (reason) => ({ status: "rejected", reason }) + ) + ) + ); + }; + document.getElementsByTagName("link"); + const cspNonceMeta = document.querySelector( + "meta[property=csp-nonce]" + ); + const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce")); + promise = allSettled2( + deps.map((dep) => { + dep = assetsURL(dep); + if (dep in seen) return; + seen[dep] = true; + const isCss = dep.endsWith(".css"); + const cssSelector = isCss ? '[rel="stylesheet"]' : ""; + if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) { + return; + } + const link = document.createElement("link"); + link.rel = isCss ? "stylesheet" : scriptRel; + if (!isCss) { + link.as = "script"; + } + link.crossOrigin = ""; + link.href = dep; + if (cspNonce) { + link.setAttribute("nonce", cspNonce); + } + document.head.appendChild(link); + if (isCss) { + return new Promise((res, rej) => { + link.addEventListener("load", res); + link.addEventListener( + "error", + () => rej(new Error(`Unable to preload CSS for ${dep}`)) + ); + }); + } + }) + ); + } + function handlePreloadError(err) { + const e = new Event("vite:preloadError", { + cancelable: true + }); + e.payload = err; + window.dispatchEvent(e); + if (!e.defaultPrevented) { + throw err; + } + } + return promise.then((res) => { + for (const item of res || []) { + if (item.status !== "rejected") continue; + handlePreloadError(item.reason); + } + return baseModule().catch(handlePreloadError); + }); +}; +function ansi2html(text, defaultColors) { + const regex = /(\x1b\[(\d+(;\d+)*)m)|([^\x1b]+)/g; + const tokens = []; + let match; + let style = {}; + let reverse = false; + let fg = defaultColors == null ? void 0 : defaultColors.fg; + let bg = defaultColors == null ? void 0 : defaultColors.bg; + while ((match = regex.exec(text)) !== null) { + const [, , codeStr, , text2] = match; + if (codeStr) { + const code = +codeStr; + switch (code) { + case 0: + style = {}; + break; + case 1: + style["font-weight"] = "bold"; + break; + case 2: + style["opacity"] = "0.8"; + break; + case 3: + style["font-style"] = "italic"; + break; + case 4: + style["text-decoration"] = "underline"; + break; + case 7: + reverse = true; + break; + case 8: + style.display = "none"; + break; + case 9: + style["text-decoration"] = "line-through"; + break; + case 22: + delete style["font-weight"]; + delete style["font-style"]; + delete style["opacity"]; + delete style["text-decoration"]; + break; + case 23: + delete style["font-weight"]; + delete style["font-style"]; + delete style["opacity"]; + break; + case 24: + delete style["text-decoration"]; + break; + case 27: + reverse = false; + break; + case 30: + case 31: + case 32: + case 33: + case 34: + case 35: + case 36: + case 37: + fg = ansiColors[code - 30]; + break; + case 39: + fg = defaultColors == null ? void 0 : defaultColors.fg; + break; + case 40: + case 41: + case 42: + case 43: + case 44: + case 45: + case 46: + case 47: + bg = ansiColors[code - 40]; + break; + case 49: + bg = defaultColors == null ? void 0 : defaultColors.bg; + break; + case 53: + style["text-decoration"] = "overline"; + break; + case 90: + case 91: + case 92: + case 93: + case 94: + case 95: + case 96: + case 97: + fg = brightAnsiColors[code - 90]; + break; + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + bg = brightAnsiColors[code - 100]; + break; + } + } else if (text2) { + const styleCopy = { ...style }; + const color = reverse ? bg : fg; + if (color !== void 0) + styleCopy["color"] = color; + const backgroundColor = reverse ? fg : bg; + if (backgroundColor !== void 0) + styleCopy["background-color"] = backgroundColor; + tokens.push(`${escapeHTML(text2)}`); + } + } + return tokens.join(""); +} +const ansiColors = { + 0: "var(--vscode-terminal-ansiBlack)", + 1: "var(--vscode-terminal-ansiRed)", + 2: "var(--vscode-terminal-ansiGreen)", + 3: "var(--vscode-terminal-ansiYellow)", + 4: "var(--vscode-terminal-ansiBlue)", + 5: "var(--vscode-terminal-ansiMagenta)", + 6: "var(--vscode-terminal-ansiCyan)", + 7: "var(--vscode-terminal-ansiWhite)" +}; +const brightAnsiColors = { + 0: "var(--vscode-terminal-ansiBrightBlack)", + 1: "var(--vscode-terminal-ansiBrightRed)", + 2: "var(--vscode-terminal-ansiBrightGreen)", + 3: "var(--vscode-terminal-ansiBrightYellow)", + 4: "var(--vscode-terminal-ansiBrightBlue)", + 5: "var(--vscode-terminal-ansiBrightMagenta)", + 6: "var(--vscode-terminal-ansiBrightCyan)", + 7: "var(--vscode-terminal-ansiBrightWhite)" +}; +function escapeHTML(text) { + return text.replace(/[&"<>]/g, (c) => ({ "&": "&", '"': """, "<": "<", ">": ">" })[c]); +} +function styleBody(style) { + return Object.entries(style).map(([name, value]) => `${name}: ${value}`).join("; "); +} +const CodeMirrorWrapper = ({ + text, + language, + mimeType, + linkify, + readOnly, + highlight, + revealLine, + lineNumbers, + isFocused, + focusOnChange, + wrapLines, + onChange, + onCursorActivity, + dataTestId, + placeholder +}) => { + const [measure, codemirrorElement] = useMeasure(); + const [modulePromise] = reactExports.useState(__vitePreload(() => import("./codeMirrorModule.js"), true ? __vite__mapDeps([0,1,2,3,4]) : void 0).then((m) => m.default)); + const codemirrorRef = reactExports.useRef(null); + const [codemirror, setCodemirror] = reactExports.useState(); + reactExports.useEffect(() => { + (async () => { + var _a, _b; + const CodeMirror = await modulePromise; + defineCustomMode(CodeMirror); + const element = codemirrorElement.current; + if (!element) + return; + const mode = languageToMode(language) || mimeTypeToMode(mimeType) || (linkify ? "text/linkified" : ""); + if (codemirrorRef.current && mode === codemirrorRef.current.cm.getOption("mode") && !!readOnly === codemirrorRef.current.cm.getOption("readOnly") && lineNumbers === codemirrorRef.current.cm.getOption("lineNumbers") && wrapLines === codemirrorRef.current.cm.getOption("lineWrapping") && placeholder === codemirrorRef.current.cm.getOption("placeholder")) { + return; + } + (_b = (_a = codemirrorRef.current) == null ? void 0 : _a.cm) == null ? void 0 : _b.getWrapperElement().remove(); + const cm = CodeMirror(element, { + value: "", + mode, + readOnly: !!readOnly, + lineNumbers, + lineWrapping: wrapLines, + placeholder + }); + codemirrorRef.current = { cm }; + if (isFocused) + cm.focus(); + setCodemirror(cm); + return cm; + })(); + }, [modulePromise, codemirror, codemirrorElement, language, mimeType, linkify, lineNumbers, wrapLines, readOnly, isFocused, placeholder]); + reactExports.useEffect(() => { + if (codemirrorRef.current) + codemirrorRef.current.cm.setSize(measure.width, measure.height); + }, [measure]); + reactExports.useLayoutEffect(() => { + var _a; + if (!codemirror) + return; + let valueChanged = false; + if (codemirror.getValue() !== text) { + codemirror.setValue(text); + valueChanged = true; + if (focusOnChange) { + codemirror.execCommand("selectAll"); + codemirror.focus(); + } + } + if (valueChanged || JSON.stringify(highlight) !== JSON.stringify(codemirrorRef.current.highlight)) { + for (const h of codemirrorRef.current.highlight || []) + codemirror.removeLineClass(h.line - 1, "wrap"); + for (const h of highlight || []) + codemirror.addLineClass(h.line - 1, "wrap", `source-line-${h.type}`); + for (const w of codemirrorRef.current.widgets || []) + codemirror.removeLineWidget(w); + for (const m of codemirrorRef.current.markers || []) + m.clear(); + const widgets = []; + const markers = []; + for (const h of highlight || []) { + if (h.type !== "subtle-error" && h.type !== "error") + continue; + const line = (_a = codemirrorRef.current) == null ? void 0 : _a.cm.getLine(h.line - 1); + if (line) { + const attributes = {}; + attributes["title"] = h.message || ""; + markers.push(codemirror.markText( + { line: h.line - 1, ch: 0 }, + { line: h.line - 1, ch: h.column || line.length }, + { className: "source-line-error-underline", attributes } + )); + } + if (h.type === "error") { + const errorWidgetElement = document.createElement("div"); + errorWidgetElement.innerHTML = ansi2html(h.message || ""); + errorWidgetElement.className = "source-line-error-widget"; + widgets.push(codemirror.addLineWidget(h.line, errorWidgetElement, { above: true, coverGutter: false })); + } + } + codemirrorRef.current.highlight = highlight; + codemirrorRef.current.widgets = widgets; + codemirrorRef.current.markers = markers; + } + if (typeof revealLine === "number" && codemirrorRef.current.cm.lineCount() >= revealLine) + codemirror.scrollIntoView({ line: Math.max(0, revealLine - 1), ch: 0 }, 50); + let changeListener; + if (onChange) { + changeListener = () => onChange(codemirror.getValue()); + codemirror.on("change", changeListener); + } + let cursorActivityListener; + if (onCursorActivity) { + cursorActivityListener = () => { + if (codemirrorRef.current.cm.hasFocus()) + onCursorActivity(codemirrorRef.current.cm.getCursor()); + }; + codemirror.on("cursorActivity", cursorActivityListener); + } + return () => { + if (changeListener) + codemirror.off("change", changeListener); + if (cursorActivityListener) + codemirror.off("cursorActivity", cursorActivityListener); + }; + }, [codemirror, text, highlight, revealLine, focusOnChange, onChange, onCursorActivity]); + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-testid": dataTestId, className: "cm-wrapper", ref: codemirrorElement, onClick: onCodeMirrorClick }); +}; +function onCodeMirrorClick(event) { + var _a; + if (!(event.target instanceof HTMLElement)) + return; + let url; + if (event.target.classList.contains("cm-linkified")) { + url = event.target.textContent; + } else if (event.target.classList.contains("cm-link") && ((_a = event.target.nextElementSibling) == null ? void 0 : _a.classList.contains("cm-url"))) { + url = event.target.nextElementSibling.textContent.slice(1, -1); + } + if (url) { + event.preventDefault(); + event.stopPropagation(); + window.open(url, "_blank"); + } +} +let customModeDefined = false; +function defineCustomMode(cm) { + if (customModeDefined) + return; + customModeDefined = true; + cm.defineSimpleMode("text/linkified", { + start: [ + { regex: kWebLinkRe, token: "linkified" } + ] + }); +} +function mimeTypeToMode(mimeType) { + if (!mimeType) + return; + if (mimeType.includes("javascript") || mimeType.includes("json")) + return "javascript"; + if (mimeType.includes("python")) + return "python"; + if (mimeType.includes("csharp")) + return "text/x-csharp"; + if (mimeType.includes("java")) + return "text/x-java"; + if (mimeType.includes("markdown")) + return "markdown"; + if (mimeType.includes("html") || mimeType.includes("svg")) + return "htmlmixed"; + if (mimeType.includes("css")) + return "css"; +} +function languageToMode(language) { + if (!language) + return; + return { + javascript: "javascript", + jsonl: "javascript", + python: "python", + csharp: "text/x-csharp", + java: "text/x-java", + markdown: "markdown", + html: "htmlmixed", + css: "css", + yaml: "yaml" + }[language]; +} +const kMinSize = 50; +const SplitView = ({ + sidebarSize, + sidebarHidden = false, + sidebarIsFirst = false, + orientation = "vertical", + minSidebarSize = kMinSize, + settingName, + sidebar, + main +}) => { + const defaultSize = Math.max(minSidebarSize, sidebarSize) * window.devicePixelRatio; + const [hSize, setHSize] = useSetting(settingName ? settingName + "." + orientation + ":size" : void 0, defaultSize); + const [vSize, setVSize] = useSetting(settingName ? settingName + "." + orientation + ":size" : void 0, defaultSize); + const [resizing, setResizing] = reactExports.useState(null); + const [measure, ref] = useMeasure(); + let size; + if (orientation === "vertical") { + size = vSize / window.devicePixelRatio; + if (measure && measure.height < size) + size = measure.height - 10; + } else { + size = hSize / window.devicePixelRatio; + if (measure && measure.width < size) + size = measure.width - 10; + } + document.body.style.userSelect = resizing ? "none" : "inherit"; + let resizerStyle = {}; + if (orientation === "vertical") { + if (sidebarIsFirst) + resizerStyle = { top: resizing ? 0 : size - 4, bottom: resizing ? 0 : void 0, height: resizing ? "initial" : 8 }; + else + resizerStyle = { bottom: resizing ? 0 : size - 4, top: resizing ? 0 : void 0, height: resizing ? "initial" : 8 }; + } else { + if (sidebarIsFirst) + resizerStyle = { left: resizing ? 0 : size - 4, right: resizing ? 0 : void 0, width: resizing ? "initial" : 8 }; + else + resizerStyle = { right: resizing ? 0 : size - 4, left: resizing ? 0 : void 0, width: resizing ? "initial" : 8 }; + } + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("split-view", orientation, sidebarIsFirst && "sidebar-first"), ref, children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "split-view-main", children: main }), + !sidebarHidden && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { flexBasis: size }, className: "split-view-sidebar", children: sidebar }), + !sidebarHidden && /* @__PURE__ */ jsxRuntimeExports.jsx( + "div", + { + style: resizerStyle, + className: "split-view-resizer", + onMouseDown: (event) => setResizing({ offset: orientation === "vertical" ? event.clientY : event.clientX, size }), + onMouseUp: () => setResizing(null), + onMouseMove: (event) => { + if (!event.buttons) { + setResizing(null); + } else if (resizing) { + const offset = orientation === "vertical" ? event.clientY : event.clientX; + const delta = offset - resizing.offset; + const newSize = sidebarIsFirst ? resizing.size + delta : resizing.size - delta; + const splitView = event.target.parentElement; + const rect = splitView.getBoundingClientRect(); + const size2 = Math.min(Math.max(minSidebarSize, newSize), (orientation === "vertical" ? rect.height : rect.width) - minSidebarSize); + if (orientation === "vertical") + setVSize(size2 * window.devicePixelRatio); + else + setHSize(size2 * window.devicePixelRatio); + } + } + } + ) + ] }); +}; +const TabbedPane = ({ tabs, selectedTab, setSelectedTab, leftToolbar, rightToolbar, dataTestId, mode }) => { + const id = reactExports.useId(); + if (!selectedTab) + selectedTab = tabs[0].id; + if (!mode) + mode = "default"; + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "tabbed-pane", "data-testid": dataTestId, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "vbox", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs(Toolbar, { children: [ + leftToolbar && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { flex: "none", display: "flex", margin: "0 4px", alignItems: "center" }, children: [ + ...leftToolbar + ] }), + mode === "default" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { flex: "auto", display: "flex", height: "100%", overflow: "hidden" }, role: "tablist", children: [ + ...tabs.map((tab) => /* @__PURE__ */ jsxRuntimeExports.jsx( + TabbedPaneTab, + { + id: tab.id, + ariaControls: `${id}-${tab.id}`, + title: tab.title, + count: tab.count, + errorCount: tab.errorCount, + selected: selectedTab === tab.id, + onSelect: setSelectedTab + }, + tab.id + )) + ] }), + mode === "select" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { flex: "auto", display: "flex", height: "100%", overflow: "hidden" }, role: "tablist", children: /* @__PURE__ */ jsxRuntimeExports.jsx("select", { style: { width: "100%", background: "none", cursor: "pointer" }, value: selectedTab, onChange: (e) => { + setSelectedTab == null ? void 0 : setSelectedTab(tabs[e.currentTarget.selectedIndex].id); + }, children: tabs.map((tab) => { + let suffix = ""; + if (tab.count) + suffix = ` (${tab.count})`; + if (tab.errorCount) + suffix = ` (${tab.errorCount})`; + return /* @__PURE__ */ jsxRuntimeExports.jsxs("option", { value: tab.id, role: "tab", "aria-controls": `${id}-${tab.id}`, children: [ + tab.title, + suffix + ] }, tab.id); + }) }) }), + rightToolbar && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { flex: "none", display: "flex", alignItems: "center" }, children: [ + ...rightToolbar + ] }) + ] }), + tabs.map((tab) => { + const className = "tab-content tab-" + tab.id; + if (tab.component) + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: `${id}-${tab.id}`, role: "tabpanel", "aria-label": tab.title, className, style: { display: selectedTab === tab.id ? "inherit" : "none" }, children: tab.component }, tab.id); + if (selectedTab === tab.id) + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: `${id}-${tab.id}`, role: "tabpanel", "aria-label": tab.title, className, children: tab.render() }, tab.id); + }) + ] }) }); +}; +const TabbedPaneTab = ({ id, title, count, errorCount, selected, onSelect, ariaControls }) => { + return /* @__PURE__ */ jsxRuntimeExports.jsxs( + "div", + { + className: clsx("tabbed-pane-tab", selected && "selected"), + onClick: () => onSelect == null ? void 0 : onSelect(id), + role: "tab", + title, + "aria-controls": ariaControls, + children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "tabbed-pane-tab-label", children: title }), + !!count && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "tabbed-pane-tab-counter", children: count }), + !!errorCount && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "tabbed-pane-tab-counter error", children: errorCount }) + ] + } + ); +}; +const SourceChooser = ({ sources, fileId, setFileId }) => { + return /* @__PURE__ */ jsxRuntimeExports.jsx("select", { className: "source-chooser", hidden: !sources.length, title: "Source chooser", value: fileId, onChange: (event) => { + setFileId(event.target.selectedOptions[0].value); + }, children: renderSourceOptions(sources) }); +}; +function renderSourceOptions(sources) { + const transformTitle = (title) => title.replace(/.*[/\\]([^/\\]+)/, "$1"); + const renderOption = (source) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: source.id, children: transformTitle(source.label) }, source.id); + const sourcesByGroups = /* @__PURE__ */ new Map(); + for (const source of sources) { + let list = sourcesByGroups.get(source.group || "Debugger"); + if (!list) { + list = []; + sourcesByGroups.set(source.group || "Debugger", list); + } + list.push(source); + } + return [...sourcesByGroups.entries()].map(([group, sources2]) => /* @__PURE__ */ jsxRuntimeExports.jsx("optgroup", { label: group, children: sources2.filter((s) => (s.group || "Debugger") === group).map((source) => renderOption(source)) }, group)); +} +function emptySource() { + return { + id: "default", + isRecorded: false, + text: "", + language: "javascript", + label: "", + highlight: [] + }; +} +const between = function(num, first, last) { + return num >= first && num <= last; +}; +function digit(code) { + return between(code, 48, 57); +} +function hexdigit(code) { + return digit(code) || between(code, 65, 70) || between(code, 97, 102); +} +function uppercaseletter(code) { + return between(code, 65, 90); +} +function lowercaseletter(code) { + return between(code, 97, 122); +} +function letter(code) { + return uppercaseletter(code) || lowercaseletter(code); +} +function nonascii(code) { + return code >= 128; +} +function namestartchar(code) { + return letter(code) || nonascii(code) || code === 95; +} +function namechar(code) { + return namestartchar(code) || digit(code) || code === 45; +} +function nonprintable(code) { + return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127; +} +function newline(code) { + return code === 10; +} +function whitespace(code) { + return newline(code) || code === 9 || code === 32; +} +const maximumallowedcodepoint = 1114111; +class InvalidCharacterError extends Error { + constructor(message) { + super(message); + this.name = "InvalidCharacterError"; + } +} +function preprocess(str) { + const codepoints = []; + for (let i = 0; i < str.length; i++) { + let code = str.charCodeAt(i); + if (code === 13 && str.charCodeAt(i + 1) === 10) { + code = 10; + i++; + } + if (code === 13 || code === 12) + code = 10; + if (code === 0) + code = 65533; + if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) { + const lead = code - 55296; + const trail = str.charCodeAt(i + 1) - 56320; + code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail; + i++; + } + codepoints.push(code); + } + return codepoints; +} +function stringFromCode(code) { + if (code <= 65535) + return String.fromCharCode(code); + code -= Math.pow(2, 16); + const lead = Math.floor(code / Math.pow(2, 10)) + 55296; + const trail = code % Math.pow(2, 10) + 56320; + return String.fromCharCode(lead) + String.fromCharCode(trail); +} +function tokenize(str1) { + const str = preprocess(str1); + let i = -1; + const tokens = []; + let code; + const codepoint = function(i2) { + if (i2 >= str.length) + return -1; + return str[i2]; + }; + const next = function(num) { + if (num === void 0) + num = 1; + if (num > 3) + throw "Spec Error: no more than three codepoints of lookahead."; + return codepoint(i + num); + }; + const consume = function(num) { + if (num === void 0) + num = 1; + i += num; + code = codepoint(i); + return true; + }; + const reconsume = function() { + i -= 1; + return true; + }; + const eof = function(codepoint2) { + if (codepoint2 === void 0) + codepoint2 = code; + return codepoint2 === -1; + }; + const consumeAToken = function() { + consumeComments(); + consume(); + if (whitespace(code)) { + while (whitespace(next())) + consume(); + return new WhitespaceToken(); + } else if (code === 34) { + return consumeAStringToken(); + } else if (code === 35) { + if (namechar(next()) || areAValidEscape(next(1), next(2))) { + const token = new HashToken(""); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + token.type = "id"; + token.value = consumeAName(); + return token; + } else { + return new DelimToken(code); + } + } else if (code === 36) { + if (next() === 61) { + consume(); + return new SuffixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 39) { + return consumeAStringToken(); + } else if (code === 40) { + return new OpenParenToken(); + } else if (code === 41) { + return new CloseParenToken(); + } else if (code === 42) { + if (next() === 61) { + consume(); + return new SubstringMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 43) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code === 44) { + return new CommaToken(); + } else if (code === 45) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else if (next(1) === 45 && next(2) === 62) { + consume(2); + return new CDCToken(); + } else if (startsWithAnIdentifier()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + return new DelimToken(code); + } + } else if (code === 46) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code === 58) { + return new ColonToken(); + } else if (code === 59) { + return new SemicolonToken(); + } else if (code === 60) { + if (next(1) === 33 && next(2) === 45 && next(3) === 45) { + consume(3); + return new CDOToken(); + } else { + return new DelimToken(code); + } + } else if (code === 64) { + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + return new AtKeywordToken(consumeAName()); + else + return new DelimToken(code); + } else if (code === 91) { + return new OpenSquareToken(); + } else if (code === 92) { + if (startsWithAValidEscape()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + return new DelimToken(code); + } + } else if (code === 93) { + return new CloseSquareToken(); + } else if (code === 94) { + if (next() === 61) { + consume(); + return new PrefixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 123) { + return new OpenCurlyToken(); + } else if (code === 124) { + if (next() === 61) { + consume(); + return new DashMatchToken(); + } else if (next() === 124) { + consume(); + return new ColumnToken(); + } else { + return new DelimToken(code); + } + } else if (code === 125) { + return new CloseCurlyToken(); + } else if (code === 126) { + if (next() === 61) { + consume(); + return new IncludeMatchToken(); + } else { + return new DelimToken(code); + } + } else if (digit(code)) { + reconsume(); + return consumeANumericToken(); + } else if (namestartchar(code)) { + reconsume(); + return consumeAnIdentlikeToken(); + } else if (eof()) { + return new EOFToken(); + } else { + return new DelimToken(code); + } + }; + const consumeComments = function() { + while (next(1) === 47 && next(2) === 42) { + consume(2); + while (true) { + consume(); + if (code === 42 && next() === 47) { + consume(); + break; + } else if (eof()) { + return; + } + } + } + }; + const consumeANumericToken = function() { + const num = consumeANumber(); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) { + const token = new DimensionToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + token.unit = consumeAName(); + return token; + } else if (next() === 37) { + consume(); + const token = new PercentageToken(); + token.value = num.value; + token.repr = num.repr; + return token; + } else { + const token = new NumberToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + return token; + } + }; + const consumeAnIdentlikeToken = function() { + const str2 = consumeAName(); + if (str2.toLowerCase() === "url" && next() === 40) { + consume(); + while (whitespace(next(1)) && whitespace(next(2))) + consume(); + if (next() === 34 || next() === 39) + return new FunctionToken(str2); + else if (whitespace(next()) && (next(2) === 34 || next(2) === 39)) + return new FunctionToken(str2); + else + return consumeAURLToken(); + } else if (next() === 40) { + consume(); + return new FunctionToken(str2); + } else { + return new IdentToken(str2); + } + }; + const consumeAStringToken = function(endingCodePoint) { + if (endingCodePoint === void 0) + endingCodePoint = code; + let string2 = ""; + while (consume()) { + if (code === endingCodePoint || eof()) { + return new StringToken(string2); + } else if (newline(code)) { + reconsume(); + return new BadStringToken(); + } else if (code === 92) { + if (eof(next())) + ; + else if (newline(next())) + consume(); + else + string2 += stringFromCode(consumeEscape()); + } else { + string2 += stringFromCode(code); + } + } + throw new Error("Internal error"); + }; + const consumeAURLToken = function() { + const token = new URLToken(""); + while (whitespace(next())) + consume(); + if (eof(next())) + return token; + while (consume()) { + if (code === 41 || eof()) { + return token; + } else if (whitespace(code)) { + while (whitespace(next())) + consume(); + if (next() === 41 || eof(next())) { + consume(); + return token; + } else { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } else if (code === 92) { + if (startsWithAValidEscape()) { + token.value += stringFromCode(consumeEscape()); + } else { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else { + token.value += stringFromCode(code); + } + } + throw new Error("Internal error"); + }; + const consumeEscape = function() { + consume(); + if (hexdigit(code)) { + const digits = [code]; + for (let total = 0; total < 5; total++) { + if (hexdigit(next())) { + consume(); + digits.push(code); + } else { + break; + } + } + if (whitespace(next())) + consume(); + let value = parseInt(digits.map(function(x) { + return String.fromCharCode(x); + }).join(""), 16); + if (value > maximumallowedcodepoint) + value = 65533; + return value; + } else if (eof()) { + return 65533; + } else { + return code; + } + }; + const areAValidEscape = function(c1, c2) { + if (c1 !== 92) + return false; + if (newline(c2)) + return false; + return true; + }; + const startsWithAValidEscape = function() { + return areAValidEscape(code, next()); + }; + const wouldStartAnIdentifier = function(c1, c2, c3) { + if (c1 === 45) + return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3); + else if (namestartchar(c1)) + return true; + else if (c1 === 92) + return areAValidEscape(c1, c2); + else + return false; + }; + const startsWithAnIdentifier = function() { + return wouldStartAnIdentifier(code, next(1), next(2)); + }; + const wouldStartANumber = function(c1, c2, c3) { + if (c1 === 43 || c1 === 45) { + if (digit(c2)) + return true; + if (c2 === 46 && digit(c3)) + return true; + return false; + } else if (c1 === 46) { + if (digit(c2)) + return true; + return false; + } else if (digit(c1)) { + return true; + } else { + return false; + } + }; + const startsWithANumber = function() { + return wouldStartANumber(code, next(1), next(2)); + }; + const consumeAName = function() { + let result = ""; + while (consume()) { + if (namechar(code)) { + result += stringFromCode(code); + } else if (startsWithAValidEscape()) { + result += stringFromCode(consumeEscape()); + } else { + reconsume(); + return result; + } + } + throw new Error("Internal parse error"); + }; + const consumeANumber = function() { + let repr = ""; + let type = "integer"; + if (next() === 43 || next() === 45) { + consume(); + repr += stringFromCode(code); + } + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + if (next(1) === 46 && digit(next(2))) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + const c1 = next(1), c2 = next(2), c3 = next(3); + if ((c1 === 69 || c1 === 101) && digit(c2)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + const value = convertAStringToANumber(repr); + return { type, value, repr }; + }; + const convertAStringToANumber = function(string2) { + return +string2; + }; + const consumeTheRemnantsOfABadURL = function() { + while (consume()) { + if (code === 41 || eof()) { + return; + } else if (startsWithAValidEscape()) { + consumeEscape(); + } else ; + } + }; + let iterationCount = 0; + while (!eof(next())) { + tokens.push(consumeAToken()); + iterationCount++; + if (iterationCount > str.length * 2) + throw new Error("I'm infinite-looping!"); + } + return tokens; +} +class CSSParserToken { + constructor() { + this.tokenType = ""; + } + toJSON() { + return { token: this.tokenType }; + } + toString() { + return this.tokenType; + } + toSource() { + return "" + this; + } +} +class BadStringToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "BADSTRING"; + } +} +class BadURLToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "BADURL"; + } +} +class WhitespaceToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "WHITESPACE"; + } + toString() { + return "WS"; + } + toSource() { + return " "; + } +} +class CDOToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "CDO"; + } + toSource() { + return ""; + } +} +class ColonToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ":"; + } +} +class SemicolonToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ";"; + } +} +class CommaToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ","; + } +} +class GroupingToken extends CSSParserToken { + constructor() { + super(...arguments); + this.value = ""; + this.mirror = ""; + } +} +class OpenCurlyToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "{"; + this.value = "{"; + this.mirror = "}"; + } +} +class CloseCurlyToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "}"; + this.value = "}"; + this.mirror = "{"; + } +} +class OpenSquareToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "["; + this.value = "["; + this.mirror = "]"; + } +} +class CloseSquareToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "]"; + this.value = "]"; + this.mirror = "["; + } +} +class OpenParenToken extends GroupingToken { + constructor() { + super(); + this.tokenType = "("; + this.value = "("; + this.mirror = ")"; + } +} +class CloseParenToken extends GroupingToken { + constructor() { + super(); + this.tokenType = ")"; + this.value = ")"; + this.mirror = "("; + } +} +class IncludeMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "~="; + } +} +class DashMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "|="; + } +} +class PrefixMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "^="; + } +} +class SuffixMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "$="; + } +} +class SubstringMatchToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "*="; + } +} +class ColumnToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "||"; + } +} +class EOFToken extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "EOF"; + } + toSource() { + return ""; + } +} +class DelimToken extends CSSParserToken { + constructor(code) { + super(); + this.tokenType = "DELIM"; + this.value = ""; + this.value = stringFromCode(code); + } + toString() { + return "DELIM(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + return json; + } + toSource() { + if (this.value === "\\") + return "\\\n"; + else + return this.value; + } +} +class StringValuedToken extends CSSParserToken { + constructor() { + super(...arguments); + this.value = ""; + } + ASCIIMatch(str) { + return this.value.toLowerCase() === str.toLowerCase(); + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + return json; + } +} +class IdentToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "IDENT"; + this.value = val; + } + toString() { + return "IDENT(" + this.value + ")"; + } + toSource() { + return escapeIdent(this.value); + } +} +class FunctionToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "FUNCTION"; + this.value = val; + this.mirror = ")"; + } + toString() { + return "FUNCTION(" + this.value + ")"; + } + toSource() { + return escapeIdent(this.value) + "("; + } +} +class AtKeywordToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "AT-KEYWORD"; + this.value = val; + } + toString() { + return "AT(" + this.value + ")"; + } + toSource() { + return "@" + escapeIdent(this.value); + } +} +class HashToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "HASH"; + this.value = val; + this.type = "unrestricted"; + } + toString() { + return "HASH(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.type = this.type; + return json; + } + toSource() { + if (this.type === "id") + return "#" + escapeIdent(this.value); + else + return "#" + escapeHash(this.value); + } +} +class StringToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "STRING"; + this.value = val; + } + toString() { + return '"' + escapeString(this.value) + '"'; + } +} +class URLToken extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "URL"; + this.value = val; + } + toString() { + return "URL(" + this.value + ")"; + } + toSource() { + return 'url("' + escapeString(this.value) + '")'; + } +} +class NumberToken extends CSSParserToken { + constructor() { + super(); + this.tokenType = "NUMBER"; + this.type = "integer"; + this.repr = ""; + } + toString() { + if (this.type === "integer") + return "INT(" + this.value + ")"; + return "NUMBER(" + this.value + ")"; + } + toJSON() { + const json = super.toJSON(); + json.value = this.value; + json.type = this.type; + json.repr = this.repr; + return json; + } + toSource() { + return this.repr; + } +} +class PercentageToken extends CSSParserToken { + constructor() { + super(); + this.tokenType = "PERCENTAGE"; + this.repr = ""; + } + toString() { + return "PERCENTAGE(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.repr = this.repr; + return json; + } + toSource() { + return this.repr + "%"; + } +} +class DimensionToken extends CSSParserToken { + constructor() { + super(); + this.tokenType = "DIMENSION"; + this.type = "integer"; + this.repr = ""; + this.unit = ""; + } + toString() { + return "DIM(" + this.value + "," + this.unit + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.type = this.type; + json.repr = this.repr; + json.unit = this.unit; + return json; + } + toSource() { + const source = this.repr; + let unit = escapeIdent(this.unit); + if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) { + unit = "\\65 " + unit.slice(1, unit.length); + } + return source + unit; + } +} +function escapeIdent(string2) { + string2 = "" + string2; + let result = ""; + const firstcode = string2.charCodeAt(0); + for (let i = 0; i < string2.length; i++) { + const code = string2.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45) + result += "\\" + code.toString(16) + " "; + else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122)) + result += string2[i]; + else + result += "\\" + string2[i]; + } + return result; +} +function escapeHash(string2) { + string2 = "" + string2; + let result = ""; + for (let i = 0; i < string2.length; i++) { + const code = string2.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122)) + result += string2[i]; + else + result += "\\" + code.toString(16) + " "; + } + return result; +} +function escapeString(string2) { + string2 = "" + string2; + let result = ""; + for (let i = 0; i < string2.length; i++) { + const code = string2.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (between(code, 1, 31) || code === 127) + result += "\\" + code.toString(16) + " "; + else if (code === 34 || code === 92) + result += "\\" + string2[i]; + else + result += string2[i]; + } + return result; +} +class InvalidSelectorError extends Error { +} +function parseCSS(selector, customNames) { + let tokens; + try { + tokens = tokenize(selector); + if (!(tokens[tokens.length - 1] instanceof EOFToken)) + tokens.push(new EOFToken()); + } catch (e) { + const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`; + const index = (e.stack || "").indexOf(e.message); + if (index !== -1) + e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length); + e.message = newMessage; + throw e; + } + const unsupportedToken = tokens.find((token) => { + return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings. + // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz } + // Or this way :xpath( {complex-xpath-goes-here("hello")} ) + token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings? + token instanceof URLToken || token instanceof PercentageToken; + }); + if (unsupportedToken) + throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + let pos = 0; + const names = /* @__PURE__ */ new Set(); + function unexpected() { + return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + } + function skipWhitespace() { + while (tokens[pos] instanceof WhitespaceToken) + pos++; + } + function isIdent(p = pos) { + return tokens[p] instanceof IdentToken; + } + function isString(p = pos) { + return tokens[p] instanceof StringToken; + } + function isNumber(p = pos) { + return tokens[p] instanceof NumberToken; + } + function isComma(p = pos) { + return tokens[p] instanceof CommaToken; + } + function isOpenParen(p = pos) { + return tokens[p] instanceof OpenParenToken; + } + function isCloseParen(p = pos) { + return tokens[p] instanceof CloseParenToken; + } + function isFunction(p = pos) { + return tokens[p] instanceof FunctionToken; + } + function isStar(p = pos) { + return tokens[p] instanceof DelimToken && tokens[p].value === "*"; + } + function isEOF(p = pos) { + return tokens[p] instanceof EOFToken; + } + function isClauseCombinator(p = pos) { + return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value); + } + function isSelectorClauseEnd(p = pos) { + return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken; + } + function consumeFunctionArguments() { + const result2 = [consumeArgument()]; + while (true) { + skipWhitespace(); + if (!isComma()) + break; + pos++; + result2.push(consumeArgument()); + } + return result2; + } + function consumeArgument() { + skipWhitespace(); + if (isNumber()) + return tokens[pos++].value; + if (isString()) + return tokens[pos++].value; + return consumeComplexSelector(); + } + function consumeComplexSelector() { + const result2 = { simples: [] }; + skipWhitespace(); + if (isClauseCombinator()) { + result2.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" }); + } else { + result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" }); + } + while (true) { + skipWhitespace(); + if (isClauseCombinator()) { + result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value; + skipWhitespace(); + } else if (isSelectorClauseEnd()) { + break; + } + result2.simples.push({ combinator: "", selector: consumeSimpleSelector() }); + } + return result2; + } + function consumeSimpleSelector() { + let rawCSSString = ""; + const functions = []; + while (!isSelectorClauseEnd()) { + if (isIdent() || isStar()) { + rawCSSString += tokens[pos++].toSource(); + } else if (tokens[pos] instanceof HashToken) { + rawCSSString += tokens[pos++].toSource(); + } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") { + pos++; + if (isIdent()) + rawCSSString += "." + tokens[pos++].toSource(); + else + throw unexpected(); + } else if (tokens[pos] instanceof ColonToken) { + pos++; + if (isIdent()) { + if (!customNames.has(tokens[pos].value.toLowerCase())) { + rawCSSString += ":" + tokens[pos++].toSource(); + } else { + const name = tokens[pos++].value.toLowerCase(); + functions.push({ name, args: [] }); + names.add(name); + } + } else if (isFunction()) { + const name = tokens[pos++].value.toLowerCase(); + if (!customNames.has(name)) { + rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`; + } else { + functions.push({ name, args: consumeFunctionArguments() }); + names.add(name); + } + skipWhitespace(); + if (!isCloseParen()) + throw unexpected(); + pos++; + } else { + throw unexpected(); + } + } else if (tokens[pos] instanceof OpenSquareToken) { + rawCSSString += "["; + pos++; + while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF()) + rawCSSString += tokens[pos++].toSource(); + if (!(tokens[pos] instanceof CloseSquareToken)) + throw unexpected(); + rawCSSString += "]"; + pos++; + } else { + throw unexpected(); + } + } + if (!rawCSSString && !functions.length) + throw unexpected(); + return { css: rawCSSString || void 0, functions }; + } + function consumeBuiltinFunctionArguments() { + let s = ""; + let balance = 1; + while (!isEOF()) { + if (isOpenParen() || isFunction()) + balance++; + if (isCloseParen()) + balance--; + if (!balance) + break; + s += tokens[pos++].toSource(); + } + return s; + } + const result = consumeFunctionArguments(); + if (!isEOF()) + throw unexpected(); + if (result.some((arg) => typeof arg !== "object" || !("simples" in arg))) + throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + return { selector: result, names: Array.from(names) }; +} +const kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]); +const kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]); +const customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]); +function parseSelector(selector) { + const parsedStrings = parseSelectorString(selector); + const parts = []; + for (const part of parsedStrings.parts) { + if (part.name === "css" || part.name === "css:light") { + if (part.name === "css:light") + part.body = ":light(" + part.body + ")"; + const parsedCSS = parseCSS(part.body, customCSSNames); + parts.push({ + name: "css", + body: parsedCSS.selector, + source: part.body + }); + continue; + } + if (kNestedSelectorNames.has(part.name)) { + let innerSelector; + let distance; + try { + const unescaped = JSON.parse("[" + part.body + "]"); + if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string") + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + innerSelector = unescaped[0]; + if (unescaped.length === 2) { + if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name)) + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + distance = unescaped[1]; + } + } catch (e) { + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + } + const nested = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } }; + const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame"); + const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1; + if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), parts.slice(0, lastFrameIndex + 1))) + nested.body.parsed.parts.splice(0, lastFrameIndex + 1); + parts.push(nested); + continue; + } + parts.push({ ...part, source: part.body }); + } + if (kNestedSelectorNames.has(parts[0].name)) + throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`); + return { + capture: parsedStrings.capture, + parts + }; +} +function selectorPartsEqual(list1, list2) { + return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 }); +} +function stringifySelector(selector, forceEngineName) { + if (typeof selector === "string") + return selector; + return selector.parts.map((p, i) => { + let includeEngine = true; + if (!forceEngineName && i !== selector.capture) { + if (p.name === "css") + includeEngine = false; + else if (p.name === "xpath" && p.source.startsWith("//") || p.source.startsWith("..")) + includeEngine = false; + } + const prefix = includeEngine ? p.name + "=" : ""; + return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`; + }).join(" >> "); +} +function parseSelectorString(selector) { + let index = 0; + let quote; + let start = 0; + const result = { parts: [] }; + const append = () => { + const part = selector.substring(start, index).trim(); + const eqIndex = part.indexOf("="); + let name; + let body; + if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) { + name = part.substring(0, eqIndex).trim(); + body = part.substring(eqIndex + 1); + } else if (part.length > 1 && part[0] === '"' && part[part.length - 1] === '"') { + name = "text"; + body = part; + } else if (part.length > 1 && part[0] === "'" && part[part.length - 1] === "'") { + name = "text"; + body = part; + } else if (/^\(*\/\//.test(part) || part.startsWith("..")) { + name = "xpath"; + body = part; + } else { + name = "css"; + body = part; + } + let capture = false; + if (name[0] === "*") { + capture = true; + name = name.substring(1); + } + result.parts.push({ name, body }); + if (capture) { + if (result.capture !== void 0) + throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`); + result.capture = result.parts.length - 1; + } + }; + if (!selector.includes(">>")) { + index = selector.length; + append(); + return result; + } + const shouldIgnoreTextSelectorQuote = () => { + const prefix = selector.substring(start, index); + const match = prefix.match(/^\s*text\s*=(.*)$/); + return !!match && !!match[1]; + }; + while (index < selector.length) { + const c = selector[index]; + if (c === "\\" && index + 1 < selector.length) { + index += 2; + } else if (c === quote) { + quote = void 0; + index++; + } else if (!quote && (c === '"' || c === "'" || c === "`") && !shouldIgnoreTextSelectorQuote()) { + quote = c; + index++; + } else if (!quote && c === ">" && selector[index + 1] === ">") { + append(); + index += 2; + start = index; + } else { + index++; + } + } + append(); + return result; +} +function parseAttributeSelector(selector, allowUnquotedStrings) { + let wp = 0; + let EOL = selector.length === 0; + const next = () => selector[wp] || ""; + const eat1 = () => { + const result2 = next(); + ++wp; + EOL = wp >= selector.length; + return result2; + }; + const syntaxError = (stage) => { + if (EOL) + throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \`${selector}\``); + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : "")); + }; + function skipSpaces() { + while (!EOL && /\s/.test(next())) + eat1(); + } + function isCSSNameChar(char) { + return char >= "€" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-"; + } + function readIdentifier() { + let result2 = ""; + skipSpaces(); + while (!EOL && isCSSNameChar(next())) + result2 += eat1(); + return result2; + } + function readQuotedString(quote) { + let result2 = eat1(); + if (result2 !== quote) + syntaxError("parsing quoted string"); + while (!EOL && next() !== quote) { + if (next() === "\\") + eat1(); + result2 += eat1(); + } + if (next() !== quote) + syntaxError("parsing quoted string"); + result2 += eat1(); + return result2; + } + function readRegularExpression() { + if (eat1() !== "/") + syntaxError("parsing regular expression"); + let source = ""; + let inClass = false; + while (!EOL) { + if (next() === "\\") { + source += eat1(); + if (EOL) + syntaxError("parsing regular expression"); + } else if (inClass && next() === "]") { + inClass = false; + } else if (!inClass && next() === "[") { + inClass = true; + } else if (!inClass && next() === "/") { + break; + } + source += eat1(); + } + if (eat1() !== "/") + syntaxError("parsing regular expression"); + let flags = ""; + while (!EOL && next().match(/[dgimsuy]/)) + flags += eat1(); + try { + return new RegExp(source, flags); + } catch (e) { + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\`: ${e.message}`); + } + } + function readAttributeToken() { + let token = ""; + skipSpaces(); + if (next() === `'` || next() === `"`) + token = readQuotedString(next()).slice(1, -1); + else + token = readIdentifier(); + if (!token) + syntaxError("parsing property path"); + return token; + } + function readOperator() { + skipSpaces(); + let op = ""; + if (!EOL) + op += eat1(); + if (!EOL && op !== "=") + op += eat1(); + if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op)) + syntaxError("parsing operator"); + return op; + } + function readAttribute() { + eat1(); + const jsonPath = []; + jsonPath.push(readAttributeToken()); + skipSpaces(); + while (next() === ".") { + eat1(); + jsonPath.push(readAttributeToken()); + skipSpaces(); + } + if (next() === "]") { + eat1(); + return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false }; + } + const operator = readOperator(); + let value = void 0; + let caseSensitive = true; + skipSpaces(); + if (next() === "/") { + if (operator !== "=") + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with regular expression`); + value = readRegularExpression(); + } else if (next() === `'` || next() === `"`) { + value = readQuotedString(next()).slice(1, -1); + skipSpaces(); + if (next() === "i" || next() === "I") { + caseSensitive = false; + eat1(); + } else if (next() === "s" || next() === "S") { + caseSensitive = true; + eat1(); + } + } else { + value = ""; + while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === ".")) + value += eat1(); + if (value === "true") { + value = true; + } else if (value === "false") { + value = false; + } else ; + } + skipSpaces(); + if (next() !== "]") + syntaxError("parsing attribute value"); + eat1(); + if (operator !== "=" && typeof value !== "string") + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value}`); + return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive }; + } + const result = { + name: "", + attributes: [] + }; + result.name = readIdentifier(); + skipSpaces(); + while (next() === "[") { + result.attributes.push(readAttribute()); + skipSpaces(); + } + if (!EOL) + syntaxError(void 0); + if (!result.name && !result.attributes.length) + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - selector cannot be empty`); + return result; +} +function escapeWithQuotes(text, char = "'") { + const stringified = JSON.stringify(text); + const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"'); + if (char === "'") + return char + escapedText.replace(/[']/g, "\\'") + char; + if (char === '"') + return char + escapedText.replace(/["]/g, '\\"') + char; + if (char === "`") + return char + escapedText.replace(/[`]/g, "`") + char; + throw new Error("Invalid escape char"); +} +function toTitleCase(name) { + return name.charAt(0).toUpperCase() + name.substring(1); +} +function toSnakeCase(name) { + return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase(); +} +function normalizeEscapedRegexQuotes(source) { + return source.replace(/(^|[^\\])(\\\\)*\\(['"`])/g, "$1$2$3"); +} +function asLocator(lang, selector, isFrameLocator = false) { + return asLocators(lang, selector, isFrameLocator, 1)[0]; +} +function asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) { + try { + return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize); + } catch (e) { + return [selector]; + } +} +function innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) { + const parts = [...parsed.parts]; + const tokens = []; + let nextBase = isFrameLocator ? "frame-locator" : "page"; + for (let index = 0; index < parts.length; index++) { + const part = parts[index]; + const base = nextBase; + nextBase = "locator"; + if (part.name === "internal:describe") + continue; + if (part.name === "nth") { + if (part.body === "0") + tokens.push([factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0")]); + else if (part.body === "-1") + tokens.push([factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1")]); + else + tokens.push([factory.generateLocator(base, "nth", part.body)]); + continue; + } + if (part.name === "visible") { + tokens.push([factory.generateLocator(base, "visible", part.body), factory.generateLocator(base, "default", `visible=${part.body}`)]); + continue; + } + if (part.name === "internal:text") { + const { exact, text } = detectExact(part.body); + tokens.push([factory.generateLocator(base, "text", text, { exact })]); + continue; + } + if (part.name === "internal:has-text") { + const { exact, text } = detectExact(part.body); + if (!exact) { + tokens.push([factory.generateLocator(base, "has-text", text, { exact })]); + continue; + } + } + if (part.name === "internal:has-not-text") { + const { exact, text } = detectExact(part.body); + if (!exact) { + tokens.push([factory.generateLocator(base, "has-not-text", text, { exact })]); + continue; + } + } + if (part.name === "internal:has") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner))); + continue; + } + if (part.name === "internal:has-not") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner))); + continue; + } + if (part.name === "internal:and") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner))); + continue; + } + if (part.name === "internal:or") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner))); + continue; + } + if (part.name === "internal:chain") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner))); + continue; + } + if (part.name === "internal:label") { + const { exact, text } = detectExact(part.body); + tokens.push([factory.generateLocator(base, "label", text, { exact })]); + continue; + } + if (part.name === "internal:role") { + const attrSelector = parseAttributeSelector(part.body); + const options = { attrs: [] }; + for (const attr of attrSelector.attributes) { + if (attr.name === "name") { + options.exact = attr.caseSensitive; + options.name = attr.value; + } else { + if (attr.name === "level" && typeof attr.value === "string") + attr.value = +attr.value; + options.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value }); + } + } + tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]); + continue; + } + if (part.name === "internal:testid") { + const attrSelector = parseAttributeSelector(part.body); + const { value } = attrSelector.attributes[0]; + tokens.push([factory.generateLocator(base, "test-id", value)]); + continue; + } + if (part.name === "internal:attr") { + const attrSelector = parseAttributeSelector(part.body); + const { name, value, caseSensitive } = attrSelector.attributes[0]; + const text = value; + const exact = !!caseSensitive; + if (name === "placeholder") { + tokens.push([factory.generateLocator(base, "placeholder", text, { exact })]); + continue; + } + if (name === "alt") { + tokens.push([factory.generateLocator(base, "alt", text, { exact })]); + continue; + } + if (name === "title") { + tokens.push([factory.generateLocator(base, "title", text, { exact })]); + continue; + } + } + if (part.name === "internal:control" && part.body === "enter-frame") { + const lastTokens = tokens[tokens.length - 1]; + const lastPart = parts[index - 1]; + const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")])); + if (["xpath", "css"].includes(lastPart.name)) { + transformed.push( + factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })), + factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] }, true)) + ); + } + lastTokens.splice(0, lastTokens.length, ...transformed); + nextBase = "frame-locator"; + continue; + } + const nextPart = parts[index + 1]; + const selectorPart = stringifySelector({ parts: [part] }); + const locatorPart = factory.generateLocator(base, "default", selectorPart); + if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) { + const { exact, text } = detectExact(nextPart.body); + if (!exact) { + const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text, { exact }); + const options = {}; + if (nextPart.name === "internal:has-text") + options.hasText = text; + else + options.hasNotText = text; + const combinedPart = factory.generateLocator(base, "default", selectorPart, options); + tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]); + index++; + continue; + } + } + let locatorPartWithEngine; + if (["xpath", "css"].includes(part.name)) { + const selectorPart2 = stringifySelector( + { parts: [part] }, + /* forceEngineName */ + true + ); + locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart2); + } + tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean)); + } + return combineTokens(factory, tokens, maxOutputSize); +} +function combineTokens(factory, tokens, maxOutputSize) { + const currentTokens = tokens.map(() => ""); + const result = []; + const visit2 = (index) => { + if (index === tokens.length) { + result.push(factory.chainLocators(currentTokens)); + return result.length < maxOutputSize; + } + for (const taken of tokens[index]) { + currentTokens[index] = taken; + if (!visit2(index + 1)) + return false; + } + return true; + }; + visit2(0); + return result; +} +function detectExact(text) { + let exact = false; + const match = text.match(/^\/(.*)\/([igm]*)$/); + if (match) + return { text: new RegExp(match[1], match[2]) }; + if (text.endsWith('"')) { + text = JSON.parse(text); + exact = true; + } else if (text.endsWith('"s')) { + text = JSON.parse(text.substring(0, text.length - 1)); + exact = true; + } else if (text.endsWith('"i')) { + text = JSON.parse(text.substring(0, text.length - 1)); + exact = false; + } + return { exact, text }; +} +class JavaScriptLocatorFactory { + constructor(preferredQuote) { + this.preferredQuote = preferredQuote; + } + generateLocator(base, kind, body, options = {}) { + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`; + if (options.hasNotText !== void 0) + return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frameLocator(${this.quote(body)})`; + case "frame": + return `contentFrame()`; + case "nth": + return `nth(${body})`; + case "first": + return `first()`; + case "last": + return `last()`; + case "visible": + return `filter({ visible: ${body === "true" ? "true" : "false"} })`; + case "role": + const attrs = []; + if (isRegExp(options.name)) { + attrs.push(`name: ${this.regexToSourceString(options.name)}`); + } else if (typeof options.name === "string") { + attrs.push(`name: ${this.quote(options.name)}`); + if (options.exact) + attrs.push(`exact: true`); + } + for (const { name, value } of options.attrs) + attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`); + const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : ""; + return `getByRole(${this.quote(body)}${attrString})`; + case "has-text": + return `filter({ hasText: ${this.toHasText(body)} })`; + case "has-not-text": + return `filter({ hasNotText: ${this.toHasText(body)} })`; + case "has": + return `filter({ has: ${body} })`; + case "hasNot": + return `filter({ hasNot: ${body} })`; + case "and": + return `and(${body})`; + case "or": + return `or(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `getByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("getByText", body, !!options.exact); + case "alt": + return this.toCallWithExact("getByAltText", body, !!options.exact); + case "placeholder": + return this.toCallWithExact("getByPlaceholder", body, !!options.exact); + case "label": + return this.toCallWithExact("getByLabel", body, !!options.exact); + case "title": + return this.toCallWithExact("getByTitle", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToSourceString(re) { + return normalizeEscapedRegexQuotes(String(re)); + } + toCallWithExact(method, body, exact) { + if (isRegExp(body)) + return `${method}(${this.regexToSourceString(body)})`; + return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return this.regexToSourceString(body); + return this.quote(body); + } + toTestIdValue(value) { + if (isRegExp(value)) + return this.regexToSourceString(value); + return this.quote(value); + } + quote(text) { + return escapeWithQuotes(text, this.preferredQuote ?? "'"); + } +} +class PythonLocatorFactory { + generateLocator(base, kind, body, options = {}) { + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`; + if (options.hasNotText !== void 0) + return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frame_locator(${this.quote(body)})`; + case "frame": + return `content_frame`; + case "nth": + return `nth(${body})`; + case "first": + return `first`; + case "last": + return `last`; + case "visible": + return `filter(visible=${body === "true" ? "True" : "False"})`; + case "role": + const attrs = []; + if (isRegExp(options.name)) { + attrs.push(`name=${this.regexToString(options.name)}`); + } else if (typeof options.name === "string") { + attrs.push(`name=${this.quote(options.name)}`); + if (options.exact) + attrs.push(`exact=True`); + } + for (const { name, value } of options.attrs) { + let valueString = typeof value === "string" ? this.quote(value) : value; + if (typeof value === "boolean") + valueString = value ? "True" : "False"; + attrs.push(`${toSnakeCase(name)}=${valueString}`); + } + const attrString = attrs.length ? `, ${attrs.join(", ")}` : ""; + return `get_by_role(${this.quote(body)}${attrString})`; + case "has-text": + return `filter(has_text=${this.toHasText(body)})`; + case "has-not-text": + return `filter(has_not_text=${this.toHasText(body)})`; + case "has": + return `filter(has=${body})`; + case "hasNot": + return `filter(has_not=${body})`; + case "and": + return `and_(${body})`; + case "or": + return `or_(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `get_by_test_id(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("get_by_text", body, !!options.exact); + case "alt": + return this.toCallWithExact("get_by_alt_text", body, !!options.exact); + case "placeholder": + return this.toCallWithExact("get_by_placeholder", body, !!options.exact); + case "label": + return this.toCallWithExact("get_by_label", body, !!options.exact); + case "title": + return this.toCallWithExact("get_by_title", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = body.flags.includes("i") ? ", re.IGNORECASE" : ""; + return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\//, "/").replace(/"/g, '\\"')}"${suffix})`; + } + toCallWithExact(method, body, exact) { + if (isRegExp(body)) + return `${method}(${this.regexToString(body)})`; + if (exact) + return `${method}(${this.quote(body)}, exact=True)`; + return `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return this.regexToString(body); + return `${this.quote(body)}`; + } + toTestIdValue(value) { + if (isRegExp(value)) + return this.regexToString(value); + return this.quote(value); + } + quote(text) { + return escapeWithQuotes(text, '"'); + } +} +class JavaLocatorFactory { + generateLocator(base, kind, body, options = {}) { + let clazz; + switch (base) { + case "page": + clazz = "Page"; + break; + case "frame-locator": + clazz = "FrameLocator"; + break; + case "locator": + clazz = "Locator"; + break; + } + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`; + if (options.hasNotText !== void 0) + return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frameLocator(${this.quote(body)})`; + case "frame": + return `contentFrame()`; + case "nth": + return `nth(${body})`; + case "first": + return `first()`; + case "last": + return `last()`; + case "visible": + return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`; + case "role": + const attrs = []; + if (isRegExp(options.name)) { + attrs.push(`.setName(${this.regexToString(options.name)})`); + } else if (typeof options.name === "string") { + attrs.push(`.setName(${this.quote(options.name)})`); + if (options.exact) + attrs.push(`.setExact(true)`); + } + for (const { name, value } of options.attrs) + attrs.push(`.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`); + const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : ""; + return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`; + case "has-text": + return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`; + case "has-not-text": + return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`; + case "has": + return `filter(new ${clazz}.FilterOptions().setHas(${body}))`; + case "hasNot": + return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`; + case "and": + return `and(${body})`; + case "or": + return `or(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `getByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact(clazz, "getByText", body, !!options.exact); + case "alt": + return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact); + case "placeholder": + return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact); + case "label": + return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact); + case "title": + return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = body.flags.includes("i") ? ", Pattern.CASE_INSENSITIVE" : ""; + return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`; + } + toCallWithExact(clazz, method, body, exact) { + if (isRegExp(body)) + return `${method}(${this.regexToString(body)})`; + if (exact) + return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`; + return `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return this.regexToString(body); + return this.quote(body); + } + toTestIdValue(value) { + if (isRegExp(value)) + return this.regexToString(value); + return this.quote(value); + } + quote(text) { + return escapeWithQuotes(text, '"'); + } +} +class CSharpLocatorFactory { + generateLocator(base, kind, body, options = {}) { + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`; + if (options.hasNotText !== void 0) + return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`; + return `Locator(${this.quote(body)})`; + case "frame-locator": + return `FrameLocator(${this.quote(body)})`; + case "frame": + return `ContentFrame`; + case "nth": + return `Nth(${body})`; + case "first": + return `First`; + case "last": + return `Last`; + case "visible": + return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`; + case "role": + const attrs = []; + if (isRegExp(options.name)) { + attrs.push(`NameRegex = ${this.regexToString(options.name)}`); + } else if (typeof options.name === "string") { + attrs.push(`Name = ${this.quote(options.name)}`); + if (options.exact) + attrs.push(`Exact = true`); + } + for (const { name, value } of options.attrs) + attrs.push(`${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`); + const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : ""; + return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`; + case "has-text": + return `Filter(new() { ${this.toHasText(body)} })`; + case "has-not-text": + return `Filter(new() { ${this.toHasNotText(body)} })`; + case "has": + return `Filter(new() { Has = ${body} })`; + case "hasNot": + return `Filter(new() { HasNot = ${body} })`; + case "and": + return `And(${body})`; + case "or": + return `Or(${body})`; + case "chain": + return `Locator(${body})`; + case "test-id": + return `GetByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("GetByText", body, !!options.exact); + case "alt": + return this.toCallWithExact("GetByAltText", body, !!options.exact); + case "placeholder": + return this.toCallWithExact("GetByPlaceholder", body, !!options.exact); + case "label": + return this.toCallWithExact("GetByLabel", body, !!options.exact); + case "title": + return this.toCallWithExact("GetByTitle", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = body.flags.includes("i") ? ", RegexOptions.IgnoreCase" : ""; + return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`; + } + toCallWithExact(method, body, exact) { + if (isRegExp(body)) + return `${method}(${this.regexToString(body)})`; + if (exact) + return `${method}(${this.quote(body)}, new() { Exact = true })`; + return `${method}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return `HasTextRegex = ${this.regexToString(body)}`; + return `HasText = ${this.quote(body)}`; + } + toTestIdValue(value) { + if (isRegExp(value)) + return this.regexToString(value); + return this.quote(value); + } + toHasNotText(body) { + if (isRegExp(body)) + return `HasNotTextRegex = ${this.regexToString(body)}`; + return `HasNotText = ${this.quote(body)}`; + } + quote(text) { + return escapeWithQuotes(text, '"'); + } +} +class JsonlLocatorFactory { + generateLocator(base, kind, body, options = {}) { + return JSON.stringify({ + kind, + body, + options + }); + } + chainLocators(locators) { + const objects = locators.map((l) => JSON.parse(l)); + for (let i = 0; i < objects.length - 1; ++i) + objects[i].next = objects[i + 1]; + return JSON.stringify(objects[0]); + } +} +const generators = { + javascript: JavaScriptLocatorFactory, + python: PythonLocatorFactory, + java: JavaLocatorFactory, + csharp: CSharpLocatorFactory, + jsonl: JsonlLocatorFactory +}; +function isRegExp(obj) { + return obj instanceof RegExp; +} +const CallLogView = ({ + language, + log +}) => { + const messagesEndRef = reactExports.useRef(null); + const [expandOverrides, setExpandOverrides] = reactExports.useState(/* @__PURE__ */ new Map()); + reactExports.useLayoutEffect(() => { + var _a; + if (log.find((callLog) => callLog.reveal)) + (_a = messagesEndRef.current) == null ? void 0 : _a.scrollIntoView({ block: "center", inline: "nearest" }); + }, [messagesEndRef, log]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "call-log", style: { flex: "auto" }, children: [ + log.map((callLog) => { + const expandOverride = expandOverrides.get(callLog.id); + const isExpanded = typeof expandOverride === "boolean" ? expandOverride : callLog.status !== "done"; + const locator = callLog.params.selector ? asLocator(language, callLog.params.selector) : null; + let titlePrefix = callLog.title; + let titleSuffix = ""; + if (callLog.title.startsWith("expect.to") || callLog.title.startsWith("expect.not.to")) { + titlePrefix = "expect("; + titleSuffix = `).${callLog.title.substring("expect.".length)}()`; + } else if (callLog.title.startsWith("locator.")) { + titlePrefix = ""; + titleSuffix = `.${callLog.title.substring("locator.".length)}()`; + } else if (locator || callLog.params.url) { + titlePrefix = callLog.title + "("; + titleSuffix = ")"; + } + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx("call-log-call", callLog.status), children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "call-log-call-header", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("codicon", `codicon-chevron-${isExpanded ? "down" : "right"}`), style: { cursor: "pointer" }, onClick: () => { + const newOverrides = new Map(expandOverrides); + newOverrides.set(callLog.id, !isExpanded); + setExpandOverrides(newOverrides); + } }), + titlePrefix, + callLog.params.url ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "call-log-details", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "call-log-url", title: callLog.params.url, children: callLog.params.url }) }) : void 0, + locator ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "call-log-details", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "call-log-selector", title: `page.${locator}`, children: `page.${locator}` }) }) : void 0, + titleSuffix, + /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: clsx("codicon", iconClass(callLog)) }), + typeof callLog.duration === "number" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "call-log-time", children: [ + "— ", + msToString(callLog.duration) + ] }) : void 0 + ] }), + (isExpanded ? callLog.messages : []).map((message, i) => { + return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "call-log-message", children: message.trim() }, i); + }), + !!callLog.error && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "call-log-message error", hidden: !isExpanded, children: callLog.error }) + ] }, callLog.id); + }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: messagesEndRef }) + ] }); +}; +function iconClass(callLog) { + switch (callLog.status) { + case "done": + return "codicon-check"; + case "in-progress": + return "codicon-clock"; + case "paused": + return "codicon-debug-pause"; + case "error": + return "codicon-error"; + } +} +const ALIAS = Symbol.for("yaml.alias"); +const DOC = Symbol.for("yaml.document"); +const MAP = Symbol.for("yaml.map"); +const PAIR = Symbol.for("yaml.pair"); +const SCALAR$1 = Symbol.for("yaml.scalar"); +const SEQ = Symbol.for("yaml.seq"); +const NODE_TYPE = Symbol.for("yaml.node.type"); +const isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +const isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +const isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +const isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +const isScalar$1 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR$1; +const isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection$1(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR$1: + case SEQ: + return true; + } + return false; +} +const hasAnchor = (node) => (isScalar$1(node) || isCollection$1(node)) && !!node.anchor; +const BREAK$1 = Symbol("break visit"); +const SKIP$1 = Symbol("skip children"); +const REMOVE$1 = Symbol("remove node"); +function visit$1(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE$1) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit$1.BREAK = BREAK$1; +visit$1.SKIP = SKIP$1; +visit$1.REMOVE = REMOVE$1; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection$1(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE$1) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK$1; +visitAsync.SKIP = SKIP$1; +visitAsync.REMOVE = REMOVE$1; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection$1(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + var _a, _b, _c, _d, _e; + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return (_a = visitor.Map) == null ? void 0 : _a.call(visitor, key, node, path); + if (isSeq(node)) + return (_b = visitor.Seq) == null ? void 0 : _b.call(visitor, key, node, path); + if (isPair(node)) + return (_c = visitor.Pair) == null ? void 0 : _c.call(visitor, key, node, path); + if (isScalar$1(node)) + return (_d = visitor.Scalar) == null ? void 0 : _d.call(visitor, key, node, path); + if (isAlias(node)) + return (_e = visitor.Alias) == null ? void 0 : _e.call(visitor, key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection$1(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} +const escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +class Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy2 = new Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit$1(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } +} +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit$1(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + if (!prevAnchors) + prevAnchors = anchorNames(doc); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar$1(ref.node) || isCollection$1(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} +function applyReviver(reviver, obj, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key, val); +} +function toJS(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !(ctx == null ? void 0 : ctx.keep)) + return Number(value); + return value; +} +class NodeBase { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +} +class Alias extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc) { + let found = void 0; + visit$1(doc, { + Node: (_key, node) => { + if (node === this) + return visit$1.BREAK; + if (node.anchor === this.source) + found = node; + } + }); + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + toJS(source, null, ctx); + data = anchors.get(source); + } + if (!data || data.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +} +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection$1(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} +const isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; +class Scalar extends NodeBase { + constructor(value) { + super(SCALAR$1); + this.value = value; + } + toJSON(arg, ctx) { + return (ctx == null ? void 0 : ctx.keep) ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +} +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; +const defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => { + var _a; + return ((_a = t.identify) == null ? void 0 : _a.call(t, value)) && !t.format; + }); +} +function createNode(value, tagName, ctx) { + var _a, _b, _c; + if (isDocument(value)) + value = value.contents; + if (isNode(value)) + return value; + if (isPair(value)) { + const map2 = (_b = (_a = ctx.schema[MAP]).createNode) == null ? void 0 : _b.call(_a, ctx.schema, null, ctx); + map2.items.push(value); + return map2; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema2, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + if (!ref.anchor) + ref.anchor = onAnchor(value); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName == null ? void 0 : tagName.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema2.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); + } + if (!value || typeof value !== "object") { + const node2 = new Scalar(value); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value instanceof Map ? schema2[MAP] : Symbol.iterator in Object(value) ? schema2[SEQ] : schema2[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = (tagObj == null ? void 0 : tagObj.createNode) ? tagObj.createNode(ctx.schema, value, ctx) : typeof ((_c = tagObj == null ? void 0 : tagObj.nodeClass) == null ? void 0 : _c.from) === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} +function collectionFromPath(schema2, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema2, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +const isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +class Collection extends NodeBase { + constructor(type, schema2) { + super(type); + Object.defineProperty(this, "schema", { + value: schema2, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema2) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema2) + copy2.schema = schema2; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema2) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection$1(node)) + node.addIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection$1(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar$1(node) ? node.value : node; + else + return isCollection$1(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar$1(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection$1(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (isCollection$1(node)) + node.setIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +} +const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +const lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; +const FOLD_FLOW = "flow"; +const FOLD_BLOCK = "block"; +const FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} +const getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str += "\n"; + i += 2; + } + str += indent; + if (json[i + 2] === " ") + str += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +let blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (literal ? "|" : ">") + (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (literal) { + value = value.replace(/\n+/g, `$&${indent}`); + return `${header} +${indent}${start}${value}${end}`; + } + value = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true)); + return `${header} +${indent}${body}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); + } + if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => { + var _a; + return tag.default && tag.tag !== "tag:yaml.org,2002:str" && ((_a = tag.test) == null ? void 0 : _a.test(str)); + }; + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || (compat == null ? void 0 : compat.some(test))) + return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} +function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; +} +function getTagObject(tags, item) { + var _a; + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj; + if (isScalar$1(item)) { + obj = item.value; + let match = tags.filter((t) => { + var _a2; + return (_a2 = t.identify) == null ? void 0 : _a2.call(t, obj); + }); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj = item; + tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = ((_a = obj == null ? void 0 : obj.constructor) == null ? void 0 : _a.name) ?? typeof obj; + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar$1(node) || isCollection$1(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag; + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify$2(item, ctx, onComment, onChompKeep) { + var _a; + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if ((_a = ctx.resolvedAliases) == null ? void 0 : _a.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + if (!tagObj) + tagObj = getTagObject(ctx.doc.schema.tags, node); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar$1(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return isScalar$1(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} +${ctx.indent}${str}`; +} +function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection$1(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || isCollection$1(key) || (isScalar$1(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify$2(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += lineComment(str, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str} +${indent}:`; + } else { + str = `${str}:`; + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar$1(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify$2(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n") + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection$1(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str += lineComment(str, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; +} +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + if (typeof process !== "undefined" && process.emitWarning) + process.emitWarning(warning); + else + console.warn(warning); + } +} +const MERGE_KEY = "<<"; +const merge = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +const isMergeKey = (ctx, key) => (merge.identify(key) || isScalar$1(key) && (!key.type || key.type === Scalar.PLAIN) && merge.identify(key.value)) && (ctx == null ? void 0 : ctx.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default)); +function addMergeToJSMap(ctx, map2, value) { + value = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (isSeq(value)) + for (const it of value.items) + mergeValue(ctx, map2, it); + else if (Array.isArray(value)) + for (const it of value) + mergeValue(ctx, map2, it); + else + mergeValue(ctx, map2, value); +} +function mergeValue(ctx, map2, value) { + const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value; + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value2] of srcMap) { + if (map2 instanceof Map) { + if (!map2.has(key)) + map2.set(key, value2); + } else if (map2 instanceof Set) { + map2.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map2, key)) { + Object.defineProperty(map2, key, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map2; +} +function addPairToJSMap(ctx, map2, { key, value }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map2, value); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map2, value); + else { + const jsKey = toJS(key, "", ctx); + if (map2 instanceof Map) { + map2.set(jsKey, toJS(value, jsKey, ctx)); + } else if (map2 instanceof Set) { + map2.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value, stringKey, ctx); + if (stringKey in map2) + Object.defineProperty(map2, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map2[stringKey] = jsValue; + } + } + return map2; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && (ctx == null ? void 0 : ctx.doc)) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} +function createPair(key, value, ctx) { + const k = createNode(key, void 0, ctx); + const v = createNode(value, void 0, ctx); + return new Pair(k, v); +} +class Pair { + constructor(key, value = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value; + } + clone(schema2) { + let { key, value } = this; + if (isNode(key)) + key = key.clone(schema2); + if (isNode(value)) + value = value.clone(schema2); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return (ctx == null ? void 0 : ctx.doc) ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +} +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify2(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str2 = stringify$2(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str2 += lineComment(str2, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines.push(blockItemPrefix + str2); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && (ik == null ? void 0 : ik.comment)) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify$2(item, itemCtx, () => comment = null); + if (i < items.length - 1) + str += ","; + if (comment) + str += lineComment(str, itemIndent, commentString(comment)); + if (!reqNewline && (lines.length > linesAtValue || str.includes("\n"))) + reqNewline = true; + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } +} +function findPair(items, key) { + const k = isScalar$1(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar$1(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +class YAMLMap extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema2) { + super(MAP, schema2); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema2, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map2 = new this(schema2); + const add = (key, value) => { + if (typeof replacer === "function") + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== void 0 || keepUndefined) + map2.items.push(createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } else if (obj && typeof obj === "object") { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema2.sortMapEntries === "function") { + map2.items.sort(schema2.sortMapEntries); + } + return map2; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + var _a; + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair == null ? void 0 : pair.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = (_a = this.schema) == null ? void 0 : _a.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar$1(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it == null ? void 0 : it.value; + return (!keepScalar && isScalar$1(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map2 = Type ? new Type() : (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {}; + if (ctx == null ? void 0 : ctx.onCreate) + ctx.onCreate(map2); + for (const item of this.items) + addPairToJSMap(ctx, map2, item); + return map2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +} +const map = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map2, onError) { + if (!isMap(map2)) + onError("Expected a mapping for this tag"); + return map2; + }, + createNode: (schema2, obj, ctx) => YAMLMap.from(schema2, obj, ctx) +}; +class YAMLSeq extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema2) { + super(SEQ, schema2); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar$1(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar$1(prev) && isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx == null ? void 0 : ctx.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema2, obj, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema2); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq2.items.push(createNode(it, void 0, ctx)); + } + } + return seq2; + } +} +function asItemIndex(key) { + let idx = isScalar$1(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} +const seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema2, obj, ctx) => YAMLSeq.from(schema2, obj, ctx) +}; +const string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; +const nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; +const boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } +}; +function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === "bigint") + return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n = JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} +const floatNaN$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } +}; +const float$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; +const intIdentify$2 = (value) => typeof value === "bigint" || Number.isInteger(value); +const intResolve$1 = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); +function intStringify$1(node, radix, prefix) { + const { value } = node; + if (intIdentify$2(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber(node); +} +const intOct$1 = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt), + stringify: (node) => intStringify$1(node, 8, "0o") +}; +const int$1 = { + identify: intIdentify$2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex$1 = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt), + stringify: (node) => intStringify$1(node, 16, "0x") +}; +const schema$2 = [ + map, + seq, + string, + nullTag, + boolTag, + intOct$1, + int$1, + intHex$1, + floatNaN$1, + floatExp$1, + float$1 +]; +function intIdentify$1(value) { + return typeof value === "bigint" || Number.isInteger(value); +} +const stringifyJSON = ({ value }) => JSON.stringify(value); +const jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true|false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify$1, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } +]; +const jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } +}; +const schema$1 = [map, seq].concat(jsonScalars, jsonError); +const binary = { + identify: (value) => value instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof Buffer === "function") { + return Buffer.from(src, "base64"); + } else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + const buf = value; + let str; + if (typeof Buffer === "function") { + str = buf instanceof Buffer ? buf.toString("base64") : Buffer.from(buf.buffer).toString("base64"); + } else if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + if (!type) + type = Scalar.BLOCK_LITERAL; + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } +}; +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema2, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema2); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value, ctx)); + } + return pairs2; +} +const pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; +class YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map2 = /* @__PURE__ */ new Map(); + if (ctx == null ? void 0 : ctx.onCreate) + ctx.onCreate(map2); + for (const pair of this.items) { + let key, value; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map2.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map2.set(key, value); + } + return map2; + } + static from(schema2, iterable, ctx) { + const pairs2 = createPairs(schema2, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +} +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +const omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar$1(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema2, iterable, ctx) => YAMLOMap.from(schema2, iterable, ctx) +}; +function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; +} +const trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +const falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; +const floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +const floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } +}; +const float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; +const intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); +function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") + offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n2 = BigInt(str); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber(node); +} +const intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node) => intStringify(node, 2, "0b") +}; +const intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node) => intStringify(node, 8, "0") +}; +const int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber +}; +const intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") +}; +class YAMLSet extends YAMLMap { + constructor(schema2) { + super(schema2); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar$1(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema2, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema2); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set2.items.push(createPair(value, null, ctx)); + } + return set2; + } +} +YAMLSet.tag = "tag:yaml.org,2002:set"; +const set = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema2, iterable, ctx) => YAMLSet.from(schema2, iterable, ctx), + resolve(map2, onError) { + if (isMap(map2)) { + if (map2.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map2); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map2; + } +}; +function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); + return sign === "-" ? num(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === "bigint") + num = (n) => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) { + parts.unshift(0); + } else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +const intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal +}; +const timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "") +}; +const schema = [ + map, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct, + int, + intHex, + floatNaN, + floatExp, + float, + binary, + merge, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; +const schemas = /* @__PURE__ */ new Map([ + ["core", schema$2], + ["failsafe", [map, seq, string]], + ["json", schema$1], + ["yaml11", schema], + ["yaml-1.1", schema] +]); +const tagsByName = { + binary, + bool: boolTag, + float: float$1, + floatExp: floatExp$1, + floatNaN: floatNaN$1, + floatTime, + int: int$1, + intHex: intHex$1, + intOct: intOct$1, + intTime, + map, + merge, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +const coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge) ? schemaTags.concat(merge) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +class Schema { + constructor({ compat, customTags, merge: merge2, resolveKnownTags, schema: schema2, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema2 === "string" && schema2 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge2); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map }); + Object.defineProperty(this, SCALAR$1, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +} +function stringifyDocument(doc, options) { + var _a; + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify$2(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { + lines[lines.length - 1] = `--- ${body}`; + } else + lines.push(body); + } else { + lines.push(stringify$2(doc.contents, ctx)); + } + if ((_a = doc.directives) == null ? void 0 : _a.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines.push("..."); + lines.push(indentComment(cs, "")); + } else { + lines.push(`... ${cs}`); + } + } else { + lines.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") + lines.push(""); + lines.push(indentComment(commentString(dc), "")); + } + } + return lines.join("\n") + "\n"; +} +class Document { + constructor(value, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version } = opt; + if (options == null ? void 0 : options._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode(value, tag, ctx); + if (flow && isCollection$1(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection$1(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar$1(this.contents) ? this.contents.value : this.contents; + return isCollection$1(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection$1(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection$1(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (isEmptyPath(path)) { + this.contents = value; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +} +function assertCollection(contents) { + if (isCollection$1(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +} +class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +} +class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +} +const prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "…\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end && end.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer} +`; + } +}; +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || (next == null ? void 0 : next.type) !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + if (start === null) + start = token.offset; + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + if (start === null) + start = token.offset; + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || (next == null ? void 0 : next.type) === "block-map" || (next == null ? void 0 : next.type) === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} +function flowIndentCheck(indent, fc, onError) { + if ((fc == null ? void 0 : fc.type) === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar$1(a) && isScalar$1(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} +const startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + var _a; + const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLMap; + const map2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? (sep == null ? void 0 : sep[0]), + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map2.comment) + map2.comment += "\n" + keyProps.comment; + else + map2.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (((_a = keyProps.found) == null ? void 0 : _a.indent) !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map2.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if ((value == null ? void 0 : value.type) === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map2.range = [bm.offset, offset, commentEnd ?? offset]; + return map2; +} +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value && value.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} +const blockMsg = "Block collections are not allowed within flow collections"; +const isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? (sep == null ? void 0 : sep[0]), + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) { + if ("source" in value && value.source && value.source[0] === ":") + onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map2 = coll; + if (mapIncludes(ctx, map2.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map2.items.push(pair); + } else { + const map2 = new YAMLMap(ctx.schema); + map2.flow = true; + map2.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map2.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map2); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce && ce.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + var _a; + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt && kt.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt == null ? void 0 : kt.collection) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = ((_a = tag.resolve) == null ? void 0 : _a.call(tag, coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options)) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag == null ? void 0 : tag.format) + node.format = tag.format; + return node; +} +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines.length - 1; i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value += "\n"; + else + sep = "\n"; + } else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines.length; ++i) + value += "\n" + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== "\n") + value += "\n"; + break; + default: + value += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = (m == null ? void 0 : m[1]) ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines = [line0]; + for (let i = 1; i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; +} +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function foldLines(source) { + let first, line; + try { + first = new RegExp("(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +const escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "…", + // Unicode next line + _: " ", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + if (isNaN(code)) { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } + return String.fromCodePoint(code); +} +function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR$1]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value, token, onError); + else + tag = ctx.schema[SCALAR$1]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar$1(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema2, value, tagName, tagToken, onError) { + var _a; + if (tagName === "!") + return schema2[SCALAR$1]; + const matchWithTest = []; + for (const tag of schema2.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if ((_a = tag.test) == null ? void 0 : _a.test(value)) + return tag; + const kt = schema2.knownTags[tagName]; + if (kt && !kt.collection) { + schema2.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema2[SCALAR$1]; +} +function findScalarTagByTest({ atKey, directives, schema: schema2 }, value, token, onError) { + const tag = schema2.tags.find((tag2) => { + var _a; + return (tag2.default === true || atKey && tag2.default === "key") && ((_a = tag2.test) == null ? void 0 : _a.test(value)); + }) || schema2[SCALAR$1]; + if (schema2.compat) { + const compat = schema2.compat.find((tag2) => { + var _a; + return tag2.default && ((_a = tag2.test) == null ? void 0 : _a.test(value)); + }) ?? schema2[SCALAR$1]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} +function emptyScalarPosition(offset, before, pos) { + if (before) { + if (pos === null) + pos = before.length; + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while ((st == null ? void 0 : st.type) === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} +const CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError); + isSrcToken = false; + } + } + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar$1(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} +function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value ?? (end == null ? void 0 : end[0]), + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + var _a; + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (((_a = prelude[i + 1]) == null ? void 0 : _a[0]) !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +} +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} +const stringify$1 = (cst2) => "type" in cst2 ? stringifyToken(cst2) : stringifyItem(cst2); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; +} +const BREAK = Symbol("break visit"); +const SKIP = Symbol("skip children"); +const REMOVE = Symbol("remove item"); +function visit(cst2, visitor) { + if ("type" in cst2 && cst2.type === "document") + cst2 = { start: cst2.start, value: cst2.value }; + _visit(Object.freeze([]), cst2, visitor); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +visit.itemAtPath = (cst2, path) => { + let item = cst2; + for (const [field, index] of path) { + const tok = item == null ? void 0 : item[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit.parentCollection = (cst2, path) => { + const parent = visit.itemAtPath(cst2, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent == null ? void 0 : parent[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} +const BOM = "\uFEFF"; +const DOCUMENT = ""; +const FLOW_END = ""; +const SCALAR = ""; +const isCollection = (token) => !!token && "items" in token; +const isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} +const cst = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + BOM, + DOCUMENT, + FLOW_END, + SCALAR, + createScalarToken, + isCollection, + isScalar, + prettyToken, + resolveAsScalar, + setScalarValue, + stringify: stringify$1, + tokenType, + visit +}, Symbol.toStringTag, { value: "Module" })); +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +const hexDigits = new Set("0123456789ABCDEFabcdef"); +const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +const flowIndicatorChars = new Set(",[]{}"); +const invalidAnchorChars = new Set(" ,[]{}\n\r "); +const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +class Lexer { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return yield* this.parseBlockStart(); + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case "!": + return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "&": + return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +} +class LineCounter { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +} +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token == null ? void 0 : token.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + var _a; + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (((_a = prev[++i]) == null ? void 0 : _a.type) === "space") { + } + return prev.splice(i, prev.length); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } +} +class Parser { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && (!top || top.type !== "doc-end")) { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map2 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map2) { + var _a; + const it = map2.items[map2.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if ((last == null ? void 0 : last.type) === "comment") + end == null ? void 0 : end.push(this.sourceToken); + else + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map2.indent)) { + const prev = map2.items[map2.items.length - 2]; + const end = (_a = prev == null ? void 0 : prev.value) == null ? void 0 : _a.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map2.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map2.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map2.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map2.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map2.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map2.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs); + } else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map2); + if (bv) { + if (atMapIndent && bv.type !== "block-seq") { + map2.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + var _a; + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if ((last == null ? void 0 : last.type) === "comment") + end == null ? void 0 : end.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = (_a = prev == null ? void 0 : prev.value) == null ? void 0 : _a.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top && top.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map2 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +} +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter == null ? void 0 : lineCounter.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter == null ? void 0 : lineCounter.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value) && !_replacer) + return value.toString(options); + return new Document(value, _replacer, options).toString(options); +} +const YAML = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + Alias, + CST: cst, + Composer, + Document, + Lexer, + LineCounter, + Pair, + Parser, + Scalar, + Schema, + YAMLError, + YAMLMap, + YAMLParseError, + YAMLSeq, + YAMLWarning, + isAlias, + isCollection: isCollection$1, + isDocument, + isMap, + isNode, + isPair, + isScalar: isScalar$1, + isSeq, + parse, + parseAllDocuments, + parseDocument, + stringify, + visit: visit$1, + visitAsync +}, Symbol.toStringTag, { value: "Module" })); +function parseAriaSnapshot(yaml, text, options = {}) { + var _a; + const lineCounter = new yaml.LineCounter(); + const parseOptions2 = { + keepSourceTokens: true, + lineCounter, + ...options + }; + const yamlDoc = yaml.parseDocument(text, parseOptions2); + const errors = []; + const convertRange = (range) => { + return [lineCounter.linePos(range[0]), lineCounter.linePos(range[1])]; + }; + const addError = (error) => { + errors.push({ + message: error.message, + range: [lineCounter.linePos(error.pos[0]), lineCounter.linePos(error.pos[1])] + }); + }; + const convertSeq = (container, seq2) => { + for (const item of seq2.items) { + const itemIsString = item instanceof yaml.Scalar && typeof item.value === "string"; + if (itemIsString) { + const childNode = KeyParser.parse(item, parseOptions2, errors); + if (childNode) { + container.children = container.children || []; + container.children.push(childNode); + } + continue; + } + const itemIsMap = item instanceof yaml.YAMLMap; + if (itemIsMap) { + convertMap(container, item); + continue; + } + errors.push({ + message: "Sequence items should be strings or maps", + range: convertRange(item.range || seq2.range) + }); + } + }; + const convertMap = (container, map2) => { + for (const entry of map2.items) { + container.children = container.children || []; + const keyIsString = entry.key instanceof yaml.Scalar && typeof entry.key.value === "string"; + if (!keyIsString) { + errors.push({ + message: "Only string keys are supported", + range: convertRange(entry.key.range || map2.range) + }); + continue; + } + const key = entry.key; + const value = entry.value; + if (key.value === "text") { + const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string"; + if (!valueIsString) { + errors.push({ + message: "Text value should be a string", + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.children.push({ + kind: "text", + text: valueOrRegex(value.value) + }); + continue; + } + if (key.value === "/children") { + const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string"; + if (!valueIsString || value.value !== "contain" && value.value !== "equal" && value.value !== "deep-equal") { + errors.push({ + message: 'Strict value should be "contain", "equal" or "deep-equal"', + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.containerMode = value.value; + continue; + } + if (key.value.startsWith("/")) { + const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string"; + if (!valueIsString) { + errors.push({ + message: "Property value should be a string", + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.props = container.props ?? {}; + container.props[key.value.slice(1)] = valueOrRegex(value.value); + continue; + } + const childNode = KeyParser.parse(key, parseOptions2, errors); + if (!childNode) + continue; + const valueIsScalar = value instanceof yaml.Scalar; + if (valueIsScalar) { + const type = typeof value.value; + if (type !== "string" && type !== "number" && type !== "boolean") { + errors.push({ + message: "Node value should be a string or a sequence", + range: convertRange(entry.value.range || map2.range) + }); + continue; + } + container.children.push({ + ...childNode, + children: [{ + kind: "text", + text: valueOrRegex(String(value.value)) + }] + }); + continue; + } + const valueIsSequence = value instanceof yaml.YAMLSeq; + if (valueIsSequence) { + container.children.push(childNode); + convertSeq(childNode, value); + continue; + } + errors.push({ + message: "Map values should be strings or sequences", + range: convertRange(entry.value.range || map2.range) + }); + } + }; + const fragment = { kind: "role", role: "fragment" }; + yamlDoc.errors.forEach(addError); + if (errors.length) + return { errors, fragment }; + if (!(yamlDoc.contents instanceof yaml.YAMLSeq)) { + errors.push({ + message: 'Aria snapshot must be a YAML sequence, elements starting with " -"', + range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }] + }); + } + if (errors.length) + return { errors, fragment }; + convertSeq(fragment, yamlDoc.contents); + if (errors.length) + return { errors, fragment: emptyFragment }; + if (((_a = fragment.children) == null ? void 0 : _a.length) === 1) + return { fragment: fragment.children[0], errors }; + return { fragment, errors }; +} +const emptyFragment = { kind: "role", role: "fragment" }; +function normalizeWhitespace(text) { + return text.replace(/[\u200b\u00ad]/g, "").replace(/[\r\n\s\t]+/g, " ").trim(); +} +function valueOrRegex(value) { + return value.startsWith("/") && value.endsWith("/") && value.length > 1 ? { pattern: value.slice(1, -1) } : normalizeWhitespace(value); +} +class KeyParser { + static parse(text, options, errors) { + try { + return new KeyParser(text.value)._parse(); + } catch (e) { + if (e instanceof ParserError) { + const message = options.prettyErrors === false ? e.message : e.message + ":\n\n" + text.value + "\n" + " ".repeat(e.pos) + "^\n"; + errors.push({ + message, + range: [options.lineCounter.linePos(text.range[0]), options.lineCounter.linePos(text.range[0] + e.pos)] + }); + return null; + } + throw e; + } + } + constructor(input) { + this._input = input; + this._pos = 0; + this._length = input.length; + } + _peek() { + return this._input[this._pos] || ""; + } + _next() { + if (this._pos < this._length) + return this._input[this._pos++]; + return null; + } + _eof() { + return this._pos >= this._length; + } + _isWhitespace() { + return !this._eof() && /\s/.test(this._peek()); + } + _skipWhitespace() { + while (this._isWhitespace()) + this._pos++; + } + _readIdentifier(type) { + if (this._eof()) + this._throwError(`Unexpected end of input when expecting ${type}`); + const start = this._pos; + while (!this._eof() && /[a-zA-Z]/.test(this._peek())) + this._pos++; + return this._input.slice(start, this._pos); + } + _readString() { + let result = ""; + let escaped = false; + while (!this._eof()) { + const ch = this._next(); + if (escaped) { + result += ch; + escaped = false; + } else if (ch === "\\") { + escaped = true; + } else if (ch === '"') { + return result; + } else { + result += ch; + } + } + this._throwError("Unterminated string"); + } + _throwError(message, offset = 0) { + throw new ParserError(message, offset || this._pos); + } + _readRegex() { + let result = ""; + let escaped = false; + let insideClass = false; + while (!this._eof()) { + const ch = this._next(); + if (escaped) { + result += ch; + escaped = false; + } else if (ch === "\\") { + escaped = true; + result += ch; + } else if (ch === "/" && !insideClass) { + return { pattern: result }; + } else if (ch === "[") { + insideClass = true; + result += ch; + } else if (ch === "]" && insideClass) { + result += ch; + insideClass = false; + } else { + result += ch; + } + } + this._throwError("Unterminated regex"); + } + _readStringOrRegex() { + const ch = this._peek(); + if (ch === '"') { + this._next(); + return normalizeWhitespace(this._readString()); + } + if (ch === "/") { + this._next(); + return this._readRegex(); + } + return null; + } + _readAttributes(result) { + let errorPos = this._pos; + while (true) { + this._skipWhitespace(); + if (this._peek() === "[") { + this._next(); + this._skipWhitespace(); + errorPos = this._pos; + const flagName = this._readIdentifier("attribute"); + this._skipWhitespace(); + let flagValue = ""; + if (this._peek() === "=") { + this._next(); + this._skipWhitespace(); + errorPos = this._pos; + while (this._peek() !== "]" && !this._isWhitespace() && !this._eof()) + flagValue += this._next(); + } + this._skipWhitespace(); + if (this._peek() !== "]") + this._throwError("Expected ]"); + this._next(); + this._applyAttribute(result, flagName, flagValue || "true", errorPos); + } else { + break; + } + } + } + _parse() { + this._skipWhitespace(); + const role = this._readIdentifier("role"); + this._skipWhitespace(); + const name = this._readStringOrRegex() || ""; + const result = { kind: "role", role, name }; + this._readAttributes(result); + this._skipWhitespace(); + if (!this._eof()) + this._throwError("Unexpected input"); + return result; + } + _applyAttribute(node, key, value, errorPos) { + if (key === "checked") { + this._assert(value === "true" || value === "false" || value === "mixed", 'Value of "checked" attribute must be a boolean or "mixed"', errorPos); + node.checked = value === "true" ? true : value === "false" ? false : "mixed"; + return; + } + if (key === "disabled") { + this._assert(value === "true" || value === "false", 'Value of "disabled" attribute must be a boolean', errorPos); + node.disabled = value === "true"; + return; + } + if (key === "expanded") { + this._assert(value === "true" || value === "false", 'Value of "expanded" attribute must be a boolean', errorPos); + node.expanded = value === "true"; + return; + } + if (key === "level") { + this._assert(!isNaN(Number(value)), 'Value of "level" attribute must be a number', errorPos); + node.level = Number(value); + return; + } + if (key === "pressed") { + this._assert(value === "true" || value === "false" || value === "mixed", 'Value of "pressed" attribute must be a boolean or "mixed"', errorPos); + node.pressed = value === "true" ? true : value === "false" ? false : "mixed"; + return; + } + if (key === "selected") { + this._assert(value === "true" || value === "false", 'Value of "selected" attribute must be a boolean', errorPos); + node.selected = value === "true"; + return; + } + this._assert(false, `Unsupported attribute [${key}]`, errorPos); + } + _assert(value, message, valuePos) { + if (!value) + this._throwError(message || "Assertion error", valuePos); + } +} +class ParserError extends Error { + constructor(message, pos) { + super(message); + this.pos = pos; + } +} +const Recorder = ({ + sources, + paused, + log, + mode, + onEditedCode, + onCursorActivity +}) => { + var _a; + const [selectedFileId, setSelectedFileId] = reactExports.useState(); + const [runningFileId, setRunningFileId2] = reactExports.useState(); + const [selectedTab, setSelectedTab] = useSetting("recorderPropertiesTab", "log"); + const [ariaSnapshot, setAriaSnapshot] = reactExports.useState(); + const [ariaSnapshotErrors, setAriaSnapshotErrors] = reactExports.useState(); + const [selectorFocusOnChange, setSelectorFocusOnChange] = reactExports.useState(true); + const fileId = selectedFileId || runningFileId || ((_a = sources[0]) == null ? void 0 : _a.id); + const source = reactExports.useMemo(() => { + if (fileId) { + const source2 = sources.find((s) => s.id === fileId); + if (source2) + return source2; + } + return emptySource(); + }, [sources, fileId]); + const [locator, setLocator] = reactExports.useState(""); + window.playwrightElementPicked = (elementInfo, userGesture) => { + const language = source.language; + setLocator(asLocator(language, elementInfo.selector)); + setAriaSnapshot(elementInfo.ariaSnapshot); + setAriaSnapshotErrors([]); + setSelectorFocusOnChange(userGesture); + if (userGesture && selectedTab !== "locator" && selectedTab !== "aria") + setSelectedTab("locator"); + if (mode === "inspecting" && selectedTab === "aria") ; + else { + const isRecording = ["recording", "assertingText", "assertingVisibility", "assertingValue", "assertingSnapshot"].includes(mode); + window.dispatch({ event: "setMode", params: { mode: isRecording ? "recording" : "standby" } }).catch(() => { + }); + } + }; + window.playwrightSetRunningFile = setRunningFileId2; + const messagesEndRef = reactExports.useRef(null); + reactExports.useLayoutEffect(() => { + var _a2; + (_a2 = messagesEndRef.current) == null ? void 0 : _a2.scrollIntoView({ block: "center", inline: "nearest" }); + }, [messagesEndRef]); + reactExports.useEffect(() => { + const handleKeyDown = (event) => { + switch (event.key) { + case "F8": + event.preventDefault(); + if (paused) + window.dispatch({ event: "resume" }); + else + window.dispatch({ event: "pause" }); + break; + case "F10": + event.preventDefault(); + if (paused) + window.dispatch({ event: "step" }); + break; + } + }; + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); + }, [paused]); + const onEditorChange = reactExports.useCallback((selector) => { + if (mode === "none" || mode === "inspecting") + window.dispatch({ event: "setMode", params: { mode: "standby" } }); + setLocator(selector); + window.dispatch({ event: "highlightRequested", params: { selector } }); + }, [mode]); + const onAriaEditorChange = reactExports.useCallback((ariaSnapshot2) => { + if (mode === "none" || mode === "inspecting") + window.dispatch({ event: "setMode", params: { mode: "standby" } }); + const { fragment, errors } = parseAriaSnapshot(YAML, ariaSnapshot2, { prettyErrors: false }); + const highlights = errors.map((error) => { + const highlight = { + message: error.message, + line: error.range[1].line, + column: error.range[1].col, + type: "subtle-error" + }; + return highlight; + }); + setAriaSnapshotErrors(highlights); + setAriaSnapshot(ariaSnapshot2); + if (!errors.length) + window.dispatch({ event: "highlightRequested", params: { ariaTemplate: fragment } }); + }, [mode]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "recorder", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs(Toolbar, { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "circle-large-filled", title: "Record", toggled: mode === "recording" || mode === "recording-inspecting" || mode === "assertingText" || mode === "assertingVisibility", onClick: () => { + window.dispatch({ event: "setMode", params: { mode: mode === "none" || mode === "standby" || mode === "inspecting" ? "recording" : "standby" } }); + }, children: "Record" }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarSeparator, {}), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "inspect", title: "Pick locator", toggled: mode === "inspecting" || mode === "recording-inspecting", onClick: () => { + const newMode = { + "inspecting": "standby", + "none": "inspecting", + "standby": "inspecting", + "recording": "recording-inspecting", + "recording-inspecting": "recording", + "assertingText": "recording-inspecting", + "assertingVisibility": "recording-inspecting", + "assertingValue": "recording-inspecting", + "assertingSnapshot": "recording-inspecting" + }[mode]; + window.dispatch({ event: "setMode", params: { mode: newMode } }).catch(() => { + }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "eye", title: "Assert visibility", toggled: mode === "assertingVisibility", disabled: mode === "none" || mode === "standby" || mode === "inspecting", onClick: () => { + window.dispatch({ event: "setMode", params: { mode: mode === "assertingVisibility" ? "recording" : "assertingVisibility" } }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "whole-word", title: "Assert text", toggled: mode === "assertingText", disabled: mode === "none" || mode === "standby" || mode === "inspecting", onClick: () => { + window.dispatch({ event: "setMode", params: { mode: mode === "assertingText" ? "recording" : "assertingText" } }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "symbol-constant", title: "Assert value", toggled: mode === "assertingValue", disabled: mode === "none" || mode === "standby" || mode === "inspecting", onClick: () => { + window.dispatch({ event: "setMode", params: { mode: mode === "assertingValue" ? "recording" : "assertingValue" } }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "gist", title: "Assert snapshot", toggled: mode === "assertingSnapshot", disabled: mode === "none" || mode === "standby" || mode === "inspecting", onClick: () => { + window.dispatch({ event: "setMode", params: { mode: mode === "assertingSnapshot" ? "recording" : "assertingSnapshot" } }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarSeparator, {}), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "files", title: "Copy", disabled: !source || !source.text, onClick: () => { + copy(source.text); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "debug-continue", title: "Resume (F8)", ariaLabel: "Resume", disabled: !paused, onClick: () => { + window.dispatch({ event: "resume" }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "debug-pause", title: "Pause (F8)", ariaLabel: "Pause", disabled: paused, onClick: () => { + window.dispatch({ event: "pause" }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "debug-step-over", title: "Step over (F10)", ariaLabel: "Step over", disabled: !paused, onClick: () => { + window.dispatch({ event: "step" }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { flex: "auto" } }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Target:" }), + /* @__PURE__ */ jsxRuntimeExports.jsx(SourceChooser, { fileId, sources, setFileId: (fileId2) => { + setSelectedFileId(fileId2); + window.dispatch({ event: "fileChanged", params: { file: fileId2 } }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "clear-all", title: "Clear", disabled: !source || !source.text, onClick: () => { + window.dispatch({ event: "clear" }); + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "color-mode", title: "Toggle color mode", toggled: false, onClick: () => toggleTheme() }) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx( + SplitView, + { + sidebarSize: 200, + main: /* @__PURE__ */ jsxRuntimeExports.jsx(CodeMirrorWrapper, { text: source.text, language: source.language, highlight: source.highlight, revealLine: source.revealLine, readOnly: source.id !== "playwright-test", onChange: onEditedCode, onCursorActivity, lineNumbers: true }), + sidebar: /* @__PURE__ */ jsxRuntimeExports.jsx( + TabbedPane, + { + rightToolbar: selectedTab === "locator" || selectedTab === "aria" ? [/* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "files", title: "Copy", onClick: () => copy((selectedTab === "locator" ? locator : ariaSnapshot) || "") }, 1)] : [], + tabs: [ + { + id: "locator", + title: "Locator", + render: () => /* @__PURE__ */ jsxRuntimeExports.jsx(CodeMirrorWrapper, { text: locator, placeholder: "Type locator to inspect", language: source.language, focusOnChange: selectorFocusOnChange, onChange: onEditorChange, wrapLines: true }) + }, + { + id: "log", + title: "Log", + render: () => /* @__PURE__ */ jsxRuntimeExports.jsx(CallLogView, { language: source.language, log: Array.from(log.values()) }) + }, + { + id: "aria", + title: "Aria", + render: () => /* @__PURE__ */ jsxRuntimeExports.jsx(CodeMirrorWrapper, { text: ariaSnapshot || "", placeholder: "Type aria template to match", language: "yaml", onChange: onAriaEditorChange, highlight: ariaSnapshotErrors, wrapLines: true }) + } + ], + selectedTab, + setSelectedTab + } + ) + } + ) + ] }); +}; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +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. +***************************************************************************** */ +var __assign = function() { + __assign = Object.assign || function __assign2(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} +function __spreadArray(to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +} +var hexGen = function(len) { + if (len === void 0) { + len = 12; + } + var maxlen = 8; + var min = Math.pow(16, Math.min(len, maxlen) - 1); + var max = Math.pow(16, Math.min(len, maxlen)) - 1; + var n = Math.floor(Math.random() * (max - min + 1)) + min; + var r = n.toString(16); + while (r.length < len) { + r = r + hexGen(len - maxlen); + } + return r; +}; +var DEFAULT_SCOPE = "stack"; +var SCOPE_KEY = "factoryStack"; +if (typeof window !== "undefined") { + if (!window[SCOPE_KEY]) { + window[SCOPE_KEY] = {}; + } +} +var registerContainer = function(scope, ref) { + window[SCOPE_KEY][scope] = ref; + return ref; +}; +var unregisterContainer = function(scope) { + delete window[SCOPE_KEY][scope]; +}; +var getContainer = function(scope) { + return window[SCOPE_KEY][scope || DEFAULT_SCOPE]; +}; +var InstanceContainer = function(props, ref) { + var _a = (props || {}).scope, scope = _a === void 0 ? DEFAULT_SCOPE : _a; + var propsRef = reactExports.useRef(props); + var _b = reactExports.useState({}), instances = _b[0], setInstances = _b[1]; + var _c = reactExports.useState([]), hashStack = _c[0], setHashStack = _c[1]; + var resolve = reactExports.useCallback(function(hash, v) { + var _a2; + return (_a2 = instances === null || instances === void 0 ? void 0 : instances[hash]) === null || _a2 === void 0 ? void 0 : _a2.resolve(v); + }, [instances]); + var resolveAll = reactExports.useCallback(function(v) { + return Object.values(instances).forEach(function(i) { + return i.resolve(v); + }); + }, [instances]); + var reject = reactExports.useCallback(function(hash, r) { + var _a2; + return (_a2 = instances === null || instances === void 0 ? void 0 : instances[hash]) === null || _a2 === void 0 ? void 0 : _a2.reject(r); + }, [instances]); + var rejectAll = reactExports.useCallback(function(r) { + return Object.values(instances).forEach(function(i) { + return i.reject(r); + }); + }, [instances]); + var hasInstance = reactExports.useCallback(function(hash) { + return !!hashStack.find(function(id) { + return id === hash; + }); + }, [hashStack]); + var getInstance = reactExports.useCallback(function(hash) { + return instances === null || instances === void 0 ? void 0 : instances[hash]; + }, [ + instances + ]); + var remove = function(hash, options) { + var _a2; + setHashStack(function(stack) { + return stack.filter(function(s) { + return s !== hash; + }); + }); + setTimeout(function() { + setInstances(function(instances2) { + var _a3 = instances2, _b2 = hash; + _a3[_b2]; + var omitHash = __rest(_a3, [typeof _b2 === "symbol" ? _b2 : _b2 + ""]); + return omitHash; + }); + }, options === null || options === void 0 ? void 0 : options.exitTimeout); + (_a2 = props.onRemove) === null || _a2 === void 0 ? void 0 : _a2.call(props, hash); + }; + var create2 = function(Component, options, instanceProps) { + if (options === void 0) { + options = {}; + } + return new Promise(function(res, rej) { + var hash = (instanceProps === null || instanceProps === void 0 ? void 0 : instanceProps.instanceId) || hexGen(); + var _a2 = propsRef.current, enterTimeout = _a2.enterTimeout, exitTimeout = _a2.exitTimeout, isAppendIntances = _a2.isAppendIntances, onResolve = _a2.onResolve, onReject = _a2.onReject; + var instanceOptions = __assign({ + enterTimeout, + exitTimeout, + instanceId: hash + }, options); + var instance = __assign({ Component, props: __assign(__assign({}, options), instanceProps), resolve: function(v) { + removeRef.current(hash, instanceOptions); + res(v); + onResolve === null || onResolve === void 0 ? void 0 : onResolve(v, hash); + }, reject: function(r) { + removeRef.current(hash, instanceOptions); + rej(r); + onReject === null || onReject === void 0 ? void 0 : onReject(r, hash); + } }, instanceOptions); + setInstances(function(instances2) { + var _a3, _b2; + return isAppendIntances ? __assign(__assign({}, instances2), (_a3 = {}, _a3[hash] = instance, _a3)) : __assign((_b2 = {}, _b2[hash] = instance, _b2), instances2); + }); + setTimeout(function() { + var _a3, _b2; + setHashStack(function(stack) { + return __spreadArray(__spreadArray([], stack), [hash]); + }); + (_b2 = (_a3 = propsRef.current).onOpen) === null || _b2 === void 0 ? void 0 : _b2.call(_a3, hash, instance); + }, instanceOptions.enterTimeout); + }); + }; + var removeRef = reactExports.useRef(remove); + var createRef = reactExports.useRef(create2); + reactExports.useEffect(function() { + propsRef.current = props; + removeRef.current = remove; + createRef.current = create2; + }); + reactExports.useImperativeHandle(ref, function() { + return { + create: createRef.current, + resolve, + reject, + resolveAll, + rejectAll, + hasInstance, + getInstance + }; + }); + reactExports.useEffect(function() { + registerContainer(scope, { + create: createRef.current, + resolve, + reject, + resolveAll, + rejectAll, + hasInstance, + getInstance + }); + return function() { + return unregisterContainer(scope); + }; + }, [scope]); + var mapKeys = reactExports.useMemo(function() { + var keys = Object.keys(instances); + return keys.map(function(key) { + var _a2 = instances[key], Component = _a2.Component, props2 = _a2.props, resolve2 = _a2.resolve, reject2 = _a2.reject; + var isOpen = !!hashStack.find(function(h) { + return h === key; + }); + return React.createElement(Component, __assign({}, props2, { + key, + isOpen, + onReject: reject2, + onResolve: resolve2, + /** @deprecated **/ + close: resolve2, + /** @deprecated **/ + open: isOpen + })); + }); + }, [instances, hashStack]); + return React.createElement(React.Fragment, null, mapKeys); +}; +var Container = reactExports.forwardRef(InstanceContainer); +Container.defaultProps = { + exitTimeout: 500, + enterTimeout: 50 +}; +var create = function(Component, options) { + return function(props) { + return getContainer(void 0).create(Component, options, props); + }; +}; +const SaveCodeForm = ({ suggestedFilename, onSubmit }) => { + const [filename, setFilename] = React.useState(suggestedFilename ?? ""); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { id: "save-form", onSubmit: () => onSubmit({ filename }), children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("label", { htmlFor: "filename", children: "File Name:" }), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "input", + { + type: "text", + id: "filename", + name: "filename", + placeholder: "Enter file name", + required: true, + value: filename, + onChange: (e) => setFilename(e.target.value) + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx("button", { id: "submit", type: "submit", disabled: !filename, children: "Save" }) + ] }); +}; +function setElementPicked(elementInfo, userGesture) { + window.playwrightElementPicked(elementInfo, userGesture); +} +function setRunningFileId(fileId) { + window.playwrightSetRunningFile(fileId); +} +function download(filename, text) { + const blob = new Blob([text], { type: "text/plain" }); + const url = URL.createObjectURL(blob); + try { + const a = document.createElement("a"); + a.href = url; + a.download = filename; + a.click(); + } finally { + URL.revokeObjectURL(url); + } +} +function generateDatetimeSuffix() { + return (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-"); +} +const codegenFilenames = { + "javascript": "example.js", + "playwright-test": "example.spec.ts", + "java-junit": "TestExample.java", + "java": "Example.java", + "python-pytest": "test_example.py", + "python": "example.py", + "python-async": "example.py", + "csharp-mstest": "Tests.cs", + "csharp-nunit": "Tests.cs", + "csharp": "Example.cs" +}; +const CrxRecorder = ({}) => { + const [settings2, setSettings] = reactExports.useState(defaultSettings); + const [sources, setSources] = reactExports.useState([]); + const [paused, setPaused] = reactExports.useState(false); + const [log, setLog] = reactExports.useState(/* @__PURE__ */ new Map()); + const [mode, setMode] = reactExports.useState("none"); + const [selectedFileId, setSelectedFileId] = reactExports.useState(defaultSettings.targetLanguage); + reactExports.useEffect(() => { + const port = chrome.runtime.connect({ name: "recorder" }); + const onMessage = (msg) => { + if (!("type" in msg) || msg.type !== "recorder") + return; + switch (msg.method) { + case "setPaused": + setPaused(msg.paused); + break; + case "setMode": + setMode(msg.mode); + chrome.runtime.sendMessage({ type: "edge_share_crx_recorder_update", mode: msg.mode }).catch(() => { + }); + break; + case "setSources": + setSources(msg.sources); + chrome.runtime.sendMessage({ type: "edge_share_crx_recorder_update", sources: msg.sources }).catch(() => { + }); + break; + case "resetCallLogs": + setLog(/* @__PURE__ */ new Map()); + break; + case "updateCallLogs": + setLog((log2) => { + const newLog = new Map(log2); + for (const callLog of msg.callLogs) { + callLog.reveal = !log2.has(callLog.id); + newLog.set(callLog.id, callLog); + } + return newLog; + }); + break; + case "setRunningFile": + setRunningFileId(msg.file); + break; + case "elementPicked": + setElementPicked(msg.elementInfo, msg.userGesture); + break; + } + }; + port.onMessage.addListener(onMessage); + window.dispatch = async (data) => { + port.postMessage({ type: "recorderEvent", ...data }); + if (data.event === "fileChanged") + setSelectedFileId(data.params.file); + }; + loadSettings().then((settings22) => { + setSettings(settings22); + setSelectedFileId(settings22.targetLanguage); + }).catch(() => { + }); + addSettingsChangedListener(setSettings); + return () => { + removeSettingsChangedListener(setSettings); + port.disconnect(); + }; + }, []); + const source = reactExports.useMemo(() => sources.find((s) => s.id === selectedFileId), [sources, selectedFileId]); + const requestStorageState = reactExports.useCallback(() => { + if (!settings2.experimental) + return; + chrome.runtime.sendMessage({ event: "storageStateRequested" }).then((storageState) => { + const fileSuffix = generateDatetimeSuffix(); + download(`storageState-${fileSuffix}.json`, JSON.stringify(storageState, null, 2)); + }); + }, [settings2]); + const showPreferences = reactExports.useCallback(() => { + const modal = create( + ({ isOpen, onResolve }) => /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { title: "Preferences", isOpen, onClose: onResolve, children: /* @__PURE__ */ jsxRuntimeExports.jsx(PreferencesForm, {}) }) + ); + modal().catch(() => { + }); + }, []); + const saveCode = reactExports.useCallback(() => { + if (!settings2.experimental) + return; + const modal = create(({ isOpen, onResolve, onReject }) => { + return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { title: "Save code", isOpen, onClose: onReject, children: /* @__PURE__ */ jsxRuntimeExports.jsx(SaveCodeForm, { onSubmit: onResolve, suggestedFilename: codegenFilenames[selectedFileId] }) }); + }); + modal().then(({ filename }) => { + const code = source == null ? void 0 : source.text; + if (!code) + return; + download(filename, code); + }).catch(() => { + }); + }, [settings2, source, selectedFileId]); + reactExports.useEffect(() => { + if (!settings2.experimental) + return; + const keydownHandler = (e) => { + if (e.ctrlKey && e.key === "s") { + e.preventDefault(); + saveCode(); + } + }; + window.addEventListener("keydown", keydownHandler); + return () => { + window.removeEventListener("keydown", keydownHandler); + }; + }, [selectedFileId, settings2, saveCode]); + const dispatchEditedCode = reactExports.useCallback((code) => { + window.dispatch({ event: "codeChanged", params: { code } }); + }, []); + const dispatchCursorActivity = reactExports.useCallback((position) => { + window.dispatch({ event: "cursorActivity", params: { position } }); + }, []); + return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx(Container, {}), + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "recorder", children: [ + settings2.experimental && /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Toolbar, { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "save", title: "Save", disabled: false, onClick: saveCode, children: "Save" }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { flex: "auto" } }), + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "dropdown", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "tools", title: "Tools", disabled: false, onClick: () => { + } }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "dropdown-content right-align", children: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: "#", onClick: requestStorageState, children: "Download storage state" }) }) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarSeparator, {}), + /* @__PURE__ */ jsxRuntimeExports.jsx(ToolbarButton, { icon: "settings-gear", title: "Preferences", onClick: showPreferences }) + ] }) }), + /* @__PURE__ */ jsxRuntimeExports.jsx(Recorder, { sources, paused, log, mode, onEditedCode: dispatchEditedCode, onCursorActivity: dispatchCursorActivity }) + ] }) + ] }); +}; +(async () => { + applyTheme(); + clientExports.createRoot(document.querySelector("#root")).render(/* @__PURE__ */ jsxRuntimeExports.jsx(CrxRecorder, {})); +})(); diff --git a/extension/edge-share-crx/manifest.json b/extension/edge-share-crx/manifest.json new file mode 100644 index 0000000..bdf1920 --- /dev/null +++ b/extension/edge-share-crx/manifest.json @@ -0,0 +1,81 @@ +{ + "name": "Browser Connection Playwright CRX", + "version": "0.15.2", + "description": "Playwright CRX recorder integrated with browser-connection relay sharing.", + "manifest_version": 3, + "icons": { + "16": "icon-16x16.png", + "32": "icon-32x32.png", + "48": "icon-48x48.png", + "128": "icon-192x192.png" + }, + "background": { + "service_worker": "background.js", + "type": "module" + }, + "action": { + "default_icon": { + "16": "icon-16x16.png", + "32": "icon-32x32.png" + }, + "default_title": "Record" + }, + "commands": { + "record": { + "suggested_key": { + "default": "Shift+Alt+R" + }, + "description": "Start recording" + }, + "inspect": { + "suggested_key": { + "default": "Shift+Alt+C" + }, + "description": "Start inspecting" + } + }, + "side_panel": { + "default_path": "empty.html" + }, + "options_ui": { + "page": "preferences.html", + "open_in_tab": false + }, + "permissions": [ + "activeTab", + "debugger", + "scripting", + "tabs", + "contextMenus", + "storage", + "sidePanel", + "alarms" + ], + "host_permissions": [ + "" + ], + "content_scripts": [ + { + "matches": [ + "" + ], + "js": [ + "edge_share_content.js" + ], + "run_at": "document_start" + } + ], + "web_accessible_resources": [ + { + "resources": [ + "provider.js" + ], + "matches": [ + "" + ] + } + ], + "content_security_policy": { + "extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' http://* https://* ws://* wss://*;" + } +} diff --git a/extension/edge-share-crx/playwright-logo.svg b/extension/edge-share-crx/playwright-logo.svg new file mode 100644 index 0000000..7b3ca7d --- /dev/null +++ b/extension/edge-share-crx/playwright-logo.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/extension/edge-share-crx/preferences.css b/extension/edge-share-crx/preferences.css new file mode 100644 index 0000000..5cc12be --- /dev/null +++ b/extension/edge-share-crx/preferences.css @@ -0,0 +1,4 @@ +body { + font-family: sans-serif; + margin: 20px; +} diff --git a/extension/edge-share-crx/preferences.html b/extension/edge-share-crx/preferences.html new file mode 100644 index 0000000..c415c30 --- /dev/null +++ b/extension/edge-share-crx/preferences.html @@ -0,0 +1,31 @@ + + + + + + + Playwright CRX - Preferences + + + + + + + +
+ + diff --git a/extension/edge-share-crx/preferences.js b/extension/edge-share-crx/preferences.js new file mode 100644 index 0000000..9d96c6f --- /dev/null +++ b/extension/edge-share-crx/preferences.js @@ -0,0 +1,5 @@ +import { c as clientExports, j as jsxRuntimeExports, P as PreferencesForm } from "./form.js"; +import "./settings.js"; +(async () => { + clientExports.createRoot(document.querySelector("#root")).render(/* @__PURE__ */ jsxRuntimeExports.jsx(PreferencesForm, {})); +})(); diff --git a/extension/edge-share-crx/provider.js b/extension/edge-share-crx/provider.js new file mode 100644 index 0000000..1463eea --- /dev/null +++ b/extension/edge-share-crx/provider.js @@ -0,0 +1,115 @@ +"use strict"; + +(() => { + if (window.browserConnection) { + return; + } + + const SOURCE_PAGE = "browser-connection:page"; + const SOURCE_CONTENT = "browser-connection:content"; + const SOURCE_RECORDER = "browser-connection:recorder"; + const pending = new Map(); + let nextId = 1; + + function request(input) { + const payload = normalizeRequest(input); + const id = String(nextId++); + + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + window.postMessage( + { + source: SOURCE_PAGE, + id, + method: payload.method, + params: payload.params + }, + window.location.origin + ); + }); + } + + function normalizeRequest(input) { + if (!input || typeof input !== "object") { + throw new Error("browserConnection.request expects an object"); + } + const method = String(input.method || "").trim(); + if (!method) { + throw new Error("browserConnection request method is required"); + } + const params = input.params && typeof input.params === "object" ? input.params : {}; + return { method, params }; + } + + window.addEventListener("message", (event) => { + if (event.source !== window || event.origin !== window.location.origin) { + return; + } + const message = event.data; + if (!message || message.source !== SOURCE_CONTENT || !message.id) { + return; + } + + const entry = pending.get(message.id); + if (!entry) { + return; + } + pending.delete(message.id); + + if (message.ok) { + entry.resolve(message.result); + } else { + entry.reject(new Error(message.error || "browserConnection request failed")); + } + }); + + Object.defineProperty(window, "browserConnection", { + value: Object.freeze({ request }), + enumerable: false, + configurable: false, + writable: false + }); + + window.dispatchEvent(new Event("browserConnection#initialized")); + + installNavigationRecorder(); + + function installNavigationRecorder() { + if (window.__browserConnectionRecorderInstalled) { + return; + } + Object.defineProperty(window, "__browserConnectionRecorderInstalled", { + value: true, + enumerable: false, + configurable: false, + writable: false + }); + + const notify = () => { + window.postMessage( + { + source: SOURCE_RECORDER, + kind: "navigate", + href: location.href, + title: document.title || "" + }, + window.location.origin + ); + }; + + const pushState = history.pushState; + const replaceState = history.replaceState; + history.pushState = function (...args) { + const result = pushState.apply(this, args); + queueMicrotask(notify); + return result; + }; + history.replaceState = function (...args) { + const result = replaceState.apply(this, args); + queueMicrotask(notify); + return result; + }; + window.addEventListener("popstate", notify); + window.addEventListener("hashchange", notify); + } +})(); diff --git a/extension/edge-share-crx/settings.js b/extension/edge-share-crx/settings.js new file mode 100644 index 0000000..e55ce38 --- /dev/null +++ b/extension/edge-share-crx/settings.js @@ -0,0 +1,41 @@ +const defaultSettings = { + testIdAttributeName: "data-testid", + targetLanguage: "playwright-test", + sidepanel: true, + experimental: false, + playInIncognito: false +}; +async function loadSettings() { + const [isAllowedIncognitoAccess, loadedPreferences] = await Promise.all([ + chrome.extension.isAllowedIncognitoAccess(), + chrome.storage.sync.get(["testIdAttributeName", "targetLanguage", "sidepanel", "playInIncognito", "experimental"]) + ]); + return { ...defaultSettings, ...loadedPreferences, playInIncognito: !!loadedPreferences.playInIncognito && isAllowedIncognitoAccess }; +} +async function storeSettings(settings) { + await chrome.storage.sync.set(settings); +} +const listeners = /* @__PURE__ */ new Map(); +function addSettingsChangedListener(listener) { + const wrappedListener = ({ testIdAttributeName, targetLanguage, sidepanel, playInIncognito, experimental }) => { + if (!testIdAttributeName && !targetLanguage && sidepanel && playInIncognito && experimental) + return; + loadSettings().then(listener).catch(() => { + }); + }; + listeners.set(listener, wrappedListener); + chrome.storage.sync.onChanged.addListener(wrappedListener); +} +function removeSettingsChangedListener(listener) { + const wrappedListener = listeners.get(listener); + if (!wrappedListener) + return; + chrome.storage.sync.onChanged.removeListener(wrappedListener); +} +export { + addSettingsChangedListener as a, + defaultSettings as d, + loadSettings as l, + removeSettingsChangedListener as r, + storeSettings as s +}; diff --git a/extension/edge-share/README.md b/extension/edge-share/README.md new file mode 100644 index 0000000..918cfc5 --- /dev/null +++ b/extension/edge-share/README.md @@ -0,0 +1,133 @@ +# Browser Connection Edge Share + +Static Microsoft Edge extension skeleton for sharing a running Edge browser with +`browser-connection` through a relay link. This directory intentionally has no +build step and no dependencies. + +## Install for development + +1. Open `edge://extensions`. +2. Enable `Developer mode`. +3. Choose `Load unpacked`. +4. Select this `extension/edge-share` directory. +5. Open the extension popup, enter the relay URL, and click `Share`. + +## Connect from browser-connection control panel + +Open the `browser-connection` `controlPanelUrl` in the Edge profile where this +extension is installed. The page injects `window.browserConnection`, triggers a +connect request, and this extension opens a confirmation window. After approval, +the extension connects to the control panel origin as the relay and returns a +share link to the page, which registers it in the current browser pool. + +This mode does not require copying the share link or starting +`browser-connection-relay` separately for the current workspace. If the Edge +browser is on another machine, expose the control panel only through an +authenticated platform proxy or private tunnel that forwards HTTP(S) and +WebSocket upgrade to the same origin. The panel token is CSRF protection for the +UI, not public authentication. + +## Manual share link + +The popup generates a one-time browser session and a share link such as: + +```text +https://relay.example.com/share/#agent= +``` + +The extension connects as the browser side to: + +```text +wss://relay.example.com/ws/browser/?token=&agent_token= +``` + +For local development, `http://127.0.0.1:8765` becomes +`ws://127.0.0.1:8765/ws/browser/...`. + +## Relay protocol + +On WebSocket open the extension sends: + +```json +{ + "type": "hello", + "role": "browser", + "protocolVersion": 1, + "sessionId": "", + "userAgent": "" +} +``` + +The relay forwards command messages from the agent: + +```json +{ + "type": "command", + "id": "request-1", + "command": "navigate", + "params": { + "url": "https://example.com" + } +} +``` + +The extension replies: + +```json +{ + "type": "response", + "id": "request-1", + "ok": true, + "result": {} +} +``` + +Failed commands return `ok: false` and an `error` string. + +## Commands + +All commands accept optional `params.tabId`. If omitted, the extension uses the +last selected tab or the active tab in the last focused window. + +- `navigate`: requires `url`; uses `chrome.tabs.update`. +- `evaluate`: requires `expression`; runs JavaScript with `Runtime.evaluate`. +- `snapshot`: returns title, URL, visible text, active element, and common + interactive elements. +- `click`: requires `selector`; scrolls, dispatches mouse events, and calls + `click()`. +- `type`: requires `text`; uses `selector` when provided, otherwise the active + element. Set `replace: true` to replace existing input text. +- `press_key`: requires `key`; dispatches common keyboard events through CDP. +- `screenshot`: returns a base64 PNG by default, or JPEG with + `format: "jpeg"`. +- `list_tabs`: returns windows with nested tabs plus a flat `tabs` list. Window + and tab metadata includes `regular`/`incognito` when Edge exposes it. +- `activate_tab`: activates `tabId` or the current target tab. +- `start_recording`, `stop_recording`, `clear_recording`, and + `recording_state`: control the user action recorder. +- `set_recording_mode`: accepts `mode: "record"` or `mode: "inspect"`. Inspect + mode highlights elements and reports selectors without activating the page. +- `play_recording`: replays the currently recorded steps through the same + shared browser debugger transport. + +`rbc pw` can run a Playwright-compatible subset against share links by +translating supported `page` methods into these relay commands. Unsupported +Playwright APIs return a clear error instead of silently pretending to work. + +## Notes and limits + +- This extension is the browser side for `browser-connection-relay` and the + `browser-connection` shared-extension driver. +- `chrome.debugger` exposes useful CDP commands but is not identical to a full + remote debugging port. +- Pages such as `edge://`, extension pages, store pages, and policy-restricted + tabs may reject debugger, scripting, or screenshot actions. +- Edge/Chrome extensions cannot read the human profile name. A loaded extension + instance represents one browser profile; incognito windows are visible only + when the user enables the extension in InPrivate/Incognito mode. +- The share link should be treated as a bearer credential. Anyone with the link + can control the shared session until the user clicks `Stop` or the relay + expires the session. +- The extension uses broad host permissions so it can connect to arbitrary relay + hosts during development. A production build should narrow this to known relay + origins. diff --git a/extension/edge-share/connect.html b/extension/edge-share/connect.html new file mode 100644 index 0000000..0582858 --- /dev/null +++ b/extension/edge-share/connect.html @@ -0,0 +1,149 @@ + + + + + Connect Edge + + + +
+

Connect this Edge

+
+
+ Platform + - +
+
+ Workspace + - +
+
+ Relay + - +
+
+
+ + +
+
Loading request
+
+ + + diff --git a/extension/edge-share/connect.js b/extension/edge-share/connect.js new file mode 100644 index 0000000..05a5e64 --- /dev/null +++ b/extension/edge-share/connect.js @@ -0,0 +1,95 @@ +"use strict"; + +const params = new URLSearchParams(window.location.search); +const requestId = params.get("requestId") || ""; + +const originEl = document.getElementById("origin"); +const workspaceEl = document.getElementById("workspace"); +const relayEl = document.getElementById("relay"); +const statusEl = document.getElementById("status"); +const approveButton = document.getElementById("approveButton"); +const rejectButton = document.getElementById("rejectButton"); + +let request = null; + +document.addEventListener("DOMContentLoaded", () => { + approveButton.addEventListener("click", approve); + rejectButton.addEventListener("click", reject); + loadRequest().catch(showError); +}); + +async function loadRequest() { + if (!requestId) { + throw new Error("Missing request id"); + } + + request = await sendMessage({ + type: "get_platform_connect_request", + requestId + }); + + originEl.textContent = request.origin || "-"; + workspaceEl.textContent = request.workspaceId || request.poolId || "current-runtime"; + relayEl.textContent = request.relayUrl || "-"; + statusEl.textContent = "Allow this page to control this Edge session through the relay."; +} + +async function approve() { + setBusy(true); + statusEl.classList.remove("error"); + statusEl.textContent = "Connecting"; + + try { + const result = await sendMessage({ + type: "approve_platform_connect", + requestId + }); + statusEl.textContent = result.connected + ? "Connected" + : "Share session created. Waiting for relay connection."; + setTimeout(() => window.close(), 900); + } catch (error) { + showError(error); + setBusy(false); + } +} + +async function reject() { + setBusy(true); + + try { + await sendMessage({ + type: "reject_platform_connect", + requestId + }); + } finally { + window.close(); + } +} + +function setBusy(busy) { + approveButton.disabled = busy; + rejectButton.disabled = busy; +} + +function sendMessage(message) { + return new Promise((resolve, reject) => { + chrome.runtime.sendMessage(message, (response) => { + const runtimeError = chrome.runtime.lastError; + if (runtimeError) { + reject(new Error(runtimeError.message)); + return; + } + if (!response || response.ok !== true) { + reject(new Error((response && response.error) || "Extension message failed")); + return; + } + resolve(response.result); + }); + }); +} + +function showError(error) { + statusEl.textContent = error.message || String(error); + statusEl.classList.add("error"); +} diff --git a/extension/edge-share/content_script.js b/extension/edge-share/content_script.js new file mode 100644 index 0000000..7be65ce --- /dev/null +++ b/extension/edge-share/content_script.js @@ -0,0 +1,1057 @@ +"use strict"; + +const SOURCE_PAGE = "browser-connection:page"; +const SOURCE_CONTENT = "browser-connection:content"; +const SOURCE_RECORDER = "browser-connection:recorder"; +const RECORDER_OVERLAY_ID = "browser-connection-recorder-overlay"; +const RECORDER_OVERLAY_STORAGE_KEY = "browserConnectionRecorderOverlay"; + +let currentRecorderState = { + recording: false, + mode: "record" +}; +let lastInspectSentAt = 0; +let lastInspectSelector = ""; + +injectProvider(); +installRecorder(); +installRecorderOverlay(); + +window.addEventListener("message", (event) => { + if (event.source !== window || event.origin !== window.location.origin) { + return; + } + const message = event.data; + if (!message || message.source !== SOURCE_PAGE || !message.id) { + if (message && message.source === SOURCE_RECORDER && message.kind === "navigate") { + recordAction({ kind: "navigate" }); + } + return; + } + + chrome.runtime.sendMessage( + { + type: "platform_request", + id: message.id, + method: message.method, + params: message.params || {}, + origin: window.location.origin, + href: window.location.href, + title: document.title || "" + }, + (response) => { + const runtimeError = chrome.runtime.lastError; + if (runtimeError) { + postResponse(message.id, false, null, runtimeError.message); + return; + } + if (!response || response.ok !== true) { + postResponse( + message.id, + false, + null, + (response && response.error) || "Extension request failed" + ); + return; + } + postResponse(message.id, true, response.result, ""); + } + ); +}); + +function injectProvider() { + const script = document.createElement("script"); + script.src = chrome.runtime.getURL("provider.js"); + script.async = false; + script.onload = () => script.remove(); + (document.documentElement || document.head || document.body).appendChild(script); +} + +function postResponse(id, ok, result, error) { + window.postMessage( + { + source: SOURCE_CONTENT, + id, + ok, + result, + error + }, + window.location.origin + ); +} + +function installRecorder() { + const pendingInputs = new Map(); + + document.addEventListener("mousemove", (event) => { + if (isRecorderOverlayEvent(event) || !isInspectMode()) return; + inspectEventTarget(event, false); + }, true); + + document.addEventListener("click", (event) => { + if (isRecorderOverlayEvent(event)) return; + if (isInspectMode()) { + inspectEventTarget(event, true); + event.preventDefault(); + event.stopPropagation(); + return; + } + const target = closestRecordableElement(event.target); + if (!target) return; + recordAction({ + kind: "click", + selector: bestSelector(target), + label: elementLabel(target), + tag: target.tagName.toLowerCase() + }); + }, true); + + document.addEventListener("input", (event) => { + if (isRecorderOverlayEvent(event) || isInspectMode()) return; + const target = closestRecordableElement(event.target); + if (!target || !isEditable(target)) return; + const selector = bestSelector(target); + clearTimeout(pendingInputs.get(selector)); + pendingInputs.set(selector, setTimeout(() => { + pendingInputs.delete(selector); + recordFill(target); + }, 350)); + }, true); + + document.addEventListener("change", (event) => { + if (isRecorderOverlayEvent(event) || isInspectMode()) return; + const target = closestRecordableElement(event.target); + if (!target || !isEditable(target)) return; + recordFill(target); + }, true); + + document.addEventListener("keydown", (event) => { + if (isRecorderOverlayEvent(event)) return; + if (isInspectMode()) { + if (event.key === "Escape") { + hideInspectorHighlight(); + sendRuntimeMessage({ type: "set_recording_mode", mode: "record" }).catch(() => {}); + } + return; + } + if (!shouldRecordKey(event)) return; + const target = closestRecordableElement(event.target); + recordAction({ + kind: "press", + selector: target ? bestSelector(target) : "", + key: keyName(event), + label: target ? elementLabel(target) : "", + tag: target ? target.tagName.toLowerCase() : "" + }); + }, true); + + window.addEventListener("pageshow", () => { + recordAction({ kind: "navigate" }); + }); +} + +function isInspectMode() { + return !!currentRecorderState.recording && currentRecorderState.mode === "inspect"; +} + +function inspectEventTarget(event, commit) { + const target = closestRecordableElement(event.target) || elementFromEvent(event); + if (!target) return; + showInspectorHighlight(target); + sendInspectTarget(target, commit); +} + +function elementFromEvent(event) { + if (event.target && event.target.nodeType === Node.ELEMENT_NODE) { + return event.target; + } + return null; +} + +function sendInspectTarget(element, force) { + const selector = bestSelector(element); + const now = Date.now(); + if (!force && selector === lastInspectSelector && now - lastInspectSentAt < 400) { + return; + } + if (!force && now - lastInspectSentAt < 160) { + return; + } + + lastInspectSentAt = now; + lastInspectSelector = selector; + chrome.runtime.sendMessage({ + type: "inspect_target", + target: { + selector, + label: elementLabel(element), + tag: element.tagName.toLowerCase(), + url: location.href, + title: document.title || "" + } + }, () => { + void chrome.runtime.lastError; + }); +} + +function showInspectorHighlight(element) { + const rect = element.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return; + + let highlight = document.getElementById(`${RECORDER_OVERLAY_ID}-highlight`); + if (!highlight) { + highlight = document.createElement("div"); + highlight.id = `${RECORDER_OVERLAY_ID}-highlight`; + highlight.style.position = "fixed"; + highlight.style.zIndex = "2147483646"; + highlight.style.pointerEvents = "none"; + highlight.style.border = "2px solid #35b184"; + highlight.style.borderRadius = "6px"; + highlight.style.boxShadow = "0 0 0 4px rgba(53, 177, 132, 0.22)"; + highlight.style.transition = "left 80ms ease, top 80ms ease, width 80ms ease, height 80ms ease"; + document.documentElement.appendChild(highlight); + } + + highlight.style.left = `${Math.max(0, rect.left)}px`; + highlight.style.top = `${Math.max(0, rect.top)}px`; + highlight.style.width = `${rect.width}px`; + highlight.style.height = `${rect.height}px`; + highlight.style.display = "block"; +} + +function hideInspectorHighlight() { + const highlight = document.getElementById(`${RECORDER_OVERLAY_ID}-highlight`); + if (highlight) { + highlight.style.display = "none"; + } +} + +function installRecorderOverlay() { + if (!canInstallRecorderOverlay()) { + return; + } + + const overlay = { + host: null, + shadow: null, + state: { + recording: false, + count: 0, + script: "" + }, + prefs: { + left: null, + top: null, + minimized: false + }, + dragging: null + }; + + const init = () => { + if (document.getElementById(RECORDER_OVERLAY_ID)) { + return; + } + readOverlayPrefs() + .then((prefs) => { + overlay.prefs = { ...overlay.prefs, ...prefs }; + createRecorderOverlay(overlay); + refreshRecorderOverlay(overlay); + setInterval(() => refreshRecorderOverlay(overlay), 3000); + }) + .catch(() => { + createRecorderOverlay(overlay); + refreshRecorderOverlay(overlay); + }); + }; + + if (document.documentElement) { + init(); + } else { + document.addEventListener("DOMContentLoaded", init, { once: true }); + } + + chrome.runtime.onMessage.addListener((message) => { + if (!message || message.type !== "recording_state_changed") { + return; + } + renderRecorderOverlay(overlay, message.recording || {}); + }); +} + +function canInstallRecorderOverlay() { + if (!/^https?:\/\//i.test(location.href)) { + return false; + } + try { + return window.top === window; + } catch (_error) { + return false; + } +} + +function createRecorderOverlay(overlay) { + const host = document.createElement("div"); + host.id = RECORDER_OVERLAY_ID; + host.style.all = "initial"; + host.style.position = "fixed"; + host.style.zIndex = "2147483647"; + host.style.display = "none"; + applyOverlayPosition(host, overlay.prefs); + + const shadow = host.attachShadow({ mode: "closed" }); + shadow.innerHTML = ` + +
+
+
+ + Recording 0 actions +
+ +
+
+
+ + +
+

User actions are being recorded for the agent.

+
+
Selector
+
Hover an element
+
+
+
No recorded steps yet.
+
+
+ + + + +
+
+
+ + `; + + overlay.host = host; + overlay.shadow = shadow; + document.documentElement.appendChild(host); + + shadow.getElementById("recordModeButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + hideInspectorHighlight(); + sendRuntimeMessage({ type: "set_recording_mode", mode: "record" }) + .then((recording) => renderRecorderOverlay(overlay, recording)) + .catch(() => refreshRecorderOverlay(overlay)); + }); + + shadow.getElementById("inspectModeButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + sendRuntimeMessage({ type: "set_recording_mode", mode: "inspect" }) + .then((recording) => renderRecorderOverlay(overlay, recording)) + .catch(() => refreshRecorderOverlay(overlay)); + }); + + shadow.getElementById("playButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + hideInspectorHighlight(); + sendRuntimeMessage({ type: "play_recording" }) + .then((recording) => renderRecorderOverlay(overlay, recording)) + .catch(() => refreshRecorderOverlay(overlay)); + }); + + shadow.getElementById("stopButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + hideInspectorHighlight(); + sendRuntimeMessage({ type: "stop_recording" }) + .then((recording) => renderRecorderOverlay(overlay, recording)) + .catch(() => refreshRecorderOverlay(overlay)); + }); + + shadow.getElementById("clearButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + sendRuntimeMessage({ type: "clear_recording" }) + .then((recording) => renderRecorderOverlay(overlay, recording)) + .catch(() => refreshRecorderOverlay(overlay)); + }); + + shadow.getElementById("copyButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + copyRecordedScript(overlay); + }); + + shadow.getElementById("minimizeButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + overlay.prefs.minimized = true; + saveOverlayPrefs(overlay.prefs); + renderRecorderOverlay(overlay, overlay.state); + }); + + shadow.getElementById("restoreButton").addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + overlay.prefs.minimized = false; + saveOverlayPrefs(overlay.prefs); + renderRecorderOverlay(overlay, overlay.state); + }); + + shadow.getElementById("dragHandle").addEventListener("pointerdown", (event) => { + beginOverlayDrag(event, overlay); + }); + shadow.getElementById("restoreButton").addEventListener("pointerdown", (event) => { + beginOverlayDrag(event, overlay); + }); +} + +function refreshRecorderOverlay(overlay) { + if (!overlay.host) { + return; + } + sendRuntimeMessage({ type: "get_recording" }) + .then((recording) => renderRecorderOverlay(overlay, recording)) + .catch(() => { + if (overlay.host) { + overlay.host.style.display = "none"; + } + }); +} + +function renderRecorderOverlay(overlay, recording) { + if (!overlay.host || !overlay.shadow) { + return; + } + + overlay.state = { + ...overlay.state, + ...(recording || {}) + }; + currentRecorderState = { + recording: !!overlay.state.recording, + mode: overlay.state.mode || "record" + }; + + const recordingActive = !!overlay.state.recording; + overlay.host.style.display = recordingActive ? "block" : "none"; + overlay.host.classList.toggle("is-minimized", !!overlay.prefs.minimized); + + const count = Number(overlay.state.count || 0); + const label = `${count} ${count === 1 ? "action" : "actions"}`; + const mode = overlay.state.mode === "inspect" ? "inspect" : "record"; + const playing = !!overlay.state.playing; + overlay.shadow.getElementById("statusText").textContent = playing + ? `Playing ${label}` + : mode === "inspect" + ? `Inspecting ${label}` + : `Recording ${label}`; + overlay.shadow.getElementById("pillText").textContent = `REC ${count}`; + overlay.shadow.getElementById("hintText").textContent = mode === "inspect" + ? "Hover elements to preview selectors. Click captures the selector without activating the page." + : "User actions are being recorded for the agent."; + + overlay.shadow.getElementById("recordModeButton").classList.toggle("active", mode === "record"); + overlay.shadow.getElementById("inspectModeButton").classList.toggle("active", mode === "inspect"); + overlay.shadow.getElementById("playButton").disabled = playing || count === 0; + overlay.shadow.getElementById("clearButton").disabled = playing || count === 0; + overlay.shadow.getElementById("copyButton").disabled = !String(overlay.state.script || "").trim(); + + const inspectTarget = overlay.shadow.getElementById("inspectTarget"); + const inspect = overlay.state.lastInspect || null; + inspectTarget.classList.toggle("visible", mode === "inspect"); + overlay.shadow.getElementById("inspectSelector").textContent = inspect?.selector || "Hover an element"; + renderOverlaySteps(overlay); + if (mode !== "inspect") { + hideInspectorHighlight(); + } +} + +function renderOverlaySteps(overlay) { + const steps = Array.isArray(overlay.state.actions) ? overlay.state.actions : []; + const list = overlay.shadow.getElementById("stepsList"); + const visible = steps.slice(-6).reverse(); + if (visible.length === 0) { + list.replaceChildren(createShadowElement(overlay.shadow, "div", "empty", "No recorded steps yet.")); + return; + } + + list.replaceChildren(...visible.map((action) => { + const row = createShadowElement(overlay.shadow, "div", `step${action.id && action.id === overlay.state.playbackStepId ? " playing" : ""}`, ""); + row.appendChild(createShadowElement(overlay.shadow, "span", "step-kind", action.kind || "step")); + row.appendChild(createShadowElement(overlay.shadow, "span", "step-selector", recordedActionLabel(action))); + return row; + })); +} + +function createShadowElement(shadow, tag, className, text) { + const element = document.createElement(tag); + if (className) { + element.className = className; + } + element.textContent = text; + return element; +} + +function recordedActionLabel(action) { + if (action.selector) return action.selector; + if (action.url) return action.url; + if (action.key) return action.key; + return action.title || "-"; +} + +function beginOverlayDrag(event, overlay) { + if (!overlay.host || event.button !== 0) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + + const rect = overlay.host.getBoundingClientRect(); + overlay.dragging = { + pointerId: event.pointerId, + startX: event.clientX, + startY: event.clientY, + left: rect.left, + top: rect.top + }; + + const move = (moveEvent) => moveOverlay(moveEvent, overlay); + const up = (upEvent) => { + if (!overlay.dragging || upEvent.pointerId !== overlay.dragging.pointerId) { + return; + } + document.removeEventListener("pointermove", move, true); + document.removeEventListener("pointerup", up, true); + overlay.dragging = null; + saveOverlayPrefs(overlay.prefs); + }; + + document.addEventListener("pointermove", move, true); + document.addEventListener("pointerup", up, true); +} + +function moveOverlay(event, overlay) { + if (!overlay.host || !overlay.dragging || event.pointerId !== overlay.dragging.pointerId) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + + const width = overlay.host.offsetWidth || 300; + const height = overlay.host.offsetHeight || 120; + const left = clampNumber( + overlay.dragging.left + event.clientX - overlay.dragging.startX, + 8, + Math.max(8, window.innerWidth - width - 8) + ); + const top = clampNumber( + overlay.dragging.top + event.clientY - overlay.dragging.startY, + 8, + Math.max(8, window.innerHeight - height - 8) + ); + + overlay.prefs.left = Math.round(left); + overlay.prefs.top = Math.round(top); + applyOverlayPosition(overlay.host, overlay.prefs); +} + +function applyOverlayPosition(host, prefs) { + if (Number.isFinite(prefs.left) && Number.isFinite(prefs.top)) { + host.style.left = `${prefs.left}px`; + host.style.top = `${prefs.top}px`; + host.style.right = "auto"; + host.style.bottom = "auto"; + return; + } + host.style.left = "auto"; + host.style.top = "auto"; + host.style.right = "16px"; + host.style.bottom = "16px"; +} + +function readOverlayPrefs() { + return new Promise((resolve) => { + chrome.storage.local.get(RECORDER_OVERLAY_STORAGE_KEY, (items) => { + const prefs = items && items[RECORDER_OVERLAY_STORAGE_KEY]; + resolve(prefs && typeof prefs === "object" ? prefs : {}); + }); + }); +} + +function saveOverlayPrefs(prefs) { + chrome.storage.local.set({ + [RECORDER_OVERLAY_STORAGE_KEY]: { + left: Number.isFinite(prefs.left) ? prefs.left : null, + top: Number.isFinite(prefs.top) ? prefs.top : null, + minimized: !!prefs.minimized + } + }); +} + +function copyRecordedScript(overlay) { + const script = String(overlay.state.script || ""); + if (!script) { + return; + } + + const button = overlay.shadow.getElementById("copyButton"); + copyText(script).then(() => { + button.classList.add("copied"); + button.textContent = "Copied"; + setTimeout(() => { + button.classList.remove("copied"); + button.textContent = "Copy"; + }, 1200); + }); +} + +function copyText(text) { + if (navigator.clipboard && window.isSecureContext) { + return navigator.clipboard.writeText(text); + } + + const textarea = document.createElement("textarea"); + textarea.value = text; + textarea.setAttribute("readonly", "true"); + textarea.style.position = "fixed"; + textarea.style.left = "-9999px"; + document.documentElement.appendChild(textarea); + textarea.select(); + document.execCommand("copy"); + textarea.remove(); + return Promise.resolve(); +} + +function sendRuntimeMessage(message) { + return new Promise((resolve, reject) => { + chrome.runtime.sendMessage(message, (response) => { + const runtimeError = chrome.runtime.lastError; + if (runtimeError) { + reject(new Error(runtimeError.message)); + return; + } + if (!response || response.ok !== true) { + reject(new Error((response && response.error) || "Extension message failed")); + return; + } + resolve(response.result); + }); + }); +} + +function isRecorderOverlayEvent(event) { + if (!event || typeof event.composedPath !== "function") { + return false; + } + return event.composedPath().some((node) => { + return node && node.nodeType === Node.ELEMENT_NODE && node.id === RECORDER_OVERLAY_ID; + }); +} + +function clampNumber(value, min, max) { + return Math.min(Math.max(value, min), max); +} + +function recordFill(element) { + if (isSensitiveEditable(element)) return; + const value = elementValue(element); + recordAction({ + kind: "fill", + selector: bestSelector(element), + text: value, + label: elementLabel(element), + tag: element.tagName.toLowerCase() + }); +} + +function recordAction(action) { + if (!/^https?:\/\//i.test(location.href)) return; + chrome.runtime.sendMessage({ + type: "recorder_action", + action: { + ...action, + url: location.href, + title: document.title || "" + } + }, () => { + void chrome.runtime.lastError; + }); +} + +function closestRecordableElement(node) { + if (!node || node.nodeType !== Node.ELEMENT_NODE) { + return null; + } + return node.closest("a,button,input,textarea,select,[role='button'],[contenteditable='true'],[data-testid],[data-test],[data-qa]"); +} + +function isEditable(element) { + const tag = element.tagName.toLowerCase(); + return element.isContentEditable || tag === "input" || tag === "textarea" || tag === "select"; +} + +function isSensitiveEditable(element) { + const haystack = [ + element.type, + element.name, + element.id, + element.getAttribute("autocomplete"), + element.getAttribute("aria-label"), + element.getAttribute("placeholder") + ].join(" ").toLowerCase(); + return /\b(password|passwd|token|secret|otp|2fa|mfa|code)\b/.test(haystack); +} + +function elementValue(element) { + if (element.isContentEditable) return element.innerText || ""; + if ("value" in element) return element.value || ""; + return ""; +} + +function shouldRecordKey(event) { + if (event.isComposing) return false; + if (event.ctrlKey || event.metaKey || event.altKey) return true; + return [ + "Enter", + "Escape", + "Tab", + "ArrowUp", + "ArrowDown", + "ArrowLeft", + "ArrowRight", + "Backspace", + "Delete" + ].includes(event.key); +} + +function keyName(event) { + const parts = []; + if (event.ctrlKey) parts.push("Control"); + if (event.metaKey) parts.push("Meta"); + if (event.altKey) parts.push("Alt"); + if (event.shiftKey && event.key !== "Shift") parts.push("Shift"); + parts.push(event.key); + return parts.join("+"); +} + +function bestSelector(element) { + const direct = stableSelector(element); + if (direct) return direct; + const labelled = labelledSelector(element); + if (labelled) return labelled; + return cssPath(element); +} + +function stableSelector(element) { + for (const name of ["data-testid", "data-test", "data-qa", "data-cy"]) { + const value = element.getAttribute(name); + if (value) return `[${name}="${cssString(value)}"]`; + } + if (element.id) return `#${cssIdent(element.id)}`; + if (element.getAttribute("name")) { + return `${element.tagName.toLowerCase()}[name="${cssString(element.getAttribute("name"))}"]`; + } + return ""; +} + +function labelledSelector(element) { + const label = element.getAttribute("aria-label") || element.getAttribute("placeholder") || element.getAttribute("title"); + if (!label) return ""; + return `${element.tagName.toLowerCase()}[${element.getAttribute("aria-label") ? "aria-label" : element.getAttribute("placeholder") ? "placeholder" : "title"}="${cssString(label)}"]`; +} + +function cssPath(element) { + const parts = []; + let current = element; + while (current && current.nodeType === Node.ELEMENT_NODE && parts.length < 5) { + let part = current.tagName.toLowerCase(); + if (current.classList.length > 0) { + part += `.${cssIdent(current.classList[0])}`; + } + const parent = current.parentElement; + if (parent) { + const siblings = Array.from(parent.children).filter((child) => child.tagName === current.tagName); + if (siblings.length > 1) { + part += `:nth-of-type(${siblings.indexOf(current) + 1})`; + } + } + parts.unshift(part); + current = parent; + } + return parts.join(" > "); +} + +function elementLabel(element) { + return String( + element.getAttribute("aria-label") || + element.getAttribute("alt") || + element.getAttribute("title") || + element.getAttribute("placeholder") || + element.innerText || + element.value || + "" + ).replace(/\s+/g, " ").trim().slice(0, 300); +} + +function cssIdent(value) { + if (window.CSS && typeof CSS.escape === "function") { + return CSS.escape(String(value)); + } + return String(value).replace(/[^a-zA-Z0-9_-]/g, "\\$&"); +} + +function cssString(value) { + return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"'); +} diff --git a/extension/edge-share/manifest.json b/extension/edge-share/manifest.json new file mode 100644 index 0000000..e7b10ec --- /dev/null +++ b/extension/edge-share/manifest.json @@ -0,0 +1,47 @@ +{ + "manifest_version": 3, + "name": "Browser Connection Edge Share", + "version": "0.1.0", + "description": "Share this Edge browser with browser-connection through a relay link.", + "permissions": [ + "activeTab", + "debugger", + "scripting", + "storage", + "tabs" + ], + "host_permissions": [ + "" + ], + "background": { + "service_worker": "service_worker.js" + }, + "content_scripts": [ + { + "matches": [ + "" + ], + "js": [ + "content_script.js" + ], + "run_at": "document_start" + } + ], + "action": { + "default_title": "Edge Share", + "default_popup": "popup.html" + }, + "web_accessible_resources": [ + { + "resources": [ + "provider.js" + ], + "matches": [ + "" + ] + } + ], + "content_security_policy": { + "extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' http://* https://* ws://* wss://*;" + } +} diff --git a/extension/edge-share/popup.html b/extension/edge-share/popup.html new file mode 100644 index 0000000..114eb2c --- /dev/null +++ b/extension/edge-share/popup.html @@ -0,0 +1,268 @@ + + + + + Edge Share + + + +
+

Edge Share

+ +
+ + Loading +
+ + + + + +
+ + + +
+ +
+
+ Action recorder + idle +
+
+ + + + + + +
+

After Record starts, a floating recorder stays visible on each supported page.

+ +
+ +

+ Keep Edge open while sharing. Anyone with the share link can control this browser session through the relay. +

+

+
+ + + + diff --git a/extension/edge-share/popup.js b/extension/edge-share/popup.js new file mode 100644 index 0000000..209d0e2 --- /dev/null +++ b/extension/edge-share/popup.js @@ -0,0 +1,308 @@ +"use strict"; + +const DEFAULT_RELAY_URL = "http://127.0.0.1:8765"; + +const relayUrlInput = document.getElementById("relayUrl"); +const shareUrlInput = document.getElementById("shareUrl"); +const shareButton = document.getElementById("shareButton"); +const stopButton = document.getElementById("stopButton"); +const copyButton = document.getElementById("copyButton"); +const recordButton = document.getElementById("recordButton"); +const inspectButton = document.getElementById("inspectButton"); +const playRecordButton = document.getElementById("playRecordButton"); +const stopRecordButton = document.getElementById("stopRecordButton"); +const clearRecordButton = document.getElementById("clearRecordButton"); +const copyScriptButton = document.getElementById("copyScriptButton"); +const recordingStatus = document.getElementById("recordingStatus"); +const recordedScript = document.getElementById("recordedScript"); +const statusDot = document.getElementById("statusDot"); +const statusText = document.getElementById("statusText"); +const errorText = document.getElementById("errorText"); + +let currentState = null; +let currentRecording = null; + +document.addEventListener("DOMContentLoaded", () => { + shareButton.addEventListener("click", onShare); + stopButton.addEventListener("click", onStop); + copyButton.addEventListener("click", onCopy); + recordButton.addEventListener("click", onRecord); + inspectButton.addEventListener("click", onInspect); + playRecordButton.addEventListener("click", onPlayRecord); + stopRecordButton.addEventListener("click", onStopRecord); + clearRecordButton.addEventListener("click", onClearRecord); + copyScriptButton.addEventListener("click", onCopyScript); + + refreshState(); + setInterval(refreshState, 1000); +}); + +chrome.runtime.onMessage.addListener((message) => { + if (message && message.type === "state_changed") { + renderState(message.state); + } + if (message && message.type === "recording_state_changed") { + renderRecording(message.recording); + } +}); + +async function onShare() { + setBusy(true); + clearError(); + + try { + const response = await sendMessage({ + type: "start_share", + relayUrl: relayUrlInput.value || DEFAULT_RELAY_URL + }); + renderState(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onStop() { + setBusy(true); + clearError(); + + try { + const response = await sendMessage({ type: "stop_share" }); + renderState(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onCopy() { + clearError(); + + try { + const link = shareUrlInput.value.trim(); + if (!link) { + throw new Error("No share link to copy"); + } + + await navigator.clipboard.writeText(link); + copyButton.textContent = "Copied"; + setTimeout(() => { + copyButton.textContent = "Copy"; + }, 1200); + } catch (error) { + showError(error); + } +} + +async function onRecord() { + setBusy(true); + clearError(); + + try { + const response = currentRecording && currentRecording.recording + ? await sendMessage({ type: "set_recording_mode", mode: "record" }) + : await sendMessage({ type: "start_recording", params: { mode: "record" } }); + renderRecording(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onInspect() { + setBusy(true); + clearError(); + + try { + const response = currentRecording && currentRecording.recording + ? await sendMessage({ type: "set_recording_mode", mode: "inspect" }) + : await sendMessage({ type: "start_recording", params: { mode: "inspect" } }); + renderRecording(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onPlayRecord() { + setBusy(true); + clearError(); + + try { + const response = await sendMessage({ type: "play_recording" }); + renderRecording(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onStopRecord() { + setBusy(true); + clearError(); + + try { + const response = await sendMessage({ type: "stop_recording" }); + renderRecording(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onClearRecord() { + setBusy(true); + clearError(); + + try { + const response = await sendMessage({ type: "clear_recording" }); + renderRecording(response); + } catch (error) { + showError(error); + } finally { + setBusy(false); + } +} + +async function onCopyScript() { + clearError(); + + try { + const script = recordedScript.value.trim(); + if (!script) { + throw new Error("No recorded script to copy"); + } + await navigator.clipboard.writeText(script); + copyScriptButton.textContent = "Copied"; + setTimeout(() => { + copyScriptButton.textContent = "Copy script"; + }, 1200); + } catch (error) { + showError(error); + } +} + +async function refreshState() { + try { + const [stateResponse, recordingResponse] = await Promise.all([ + sendMessage({ type: "get_state" }), + sendMessage({ type: "get_recording" }) + ]); + renderState(stateResponse); + renderRecording(recordingResponse); + } catch (error) { + showError(error); + } +} + +function renderState(state) { + currentState = state || {}; + + relayUrlInput.value = currentState.relayUrl || relayUrlInput.value || DEFAULT_RELAY_URL; + shareUrlInput.value = currentState.shareUrl || ""; + + statusDot.className = "dot"; + if (currentState.connected) { + statusDot.classList.add("connected"); + } else if (currentState.lastError) { + statusDot.classList.add("error"); + } + + statusText.textContent = statusLabel(currentState); + stopButton.disabled = !currentState.sharing; + copyButton.disabled = !currentState.shareUrl; + recordButton.disabled = false; + stopRecordButton.disabled = !currentState.recording; + + if (currentState.lastError) { + showError(currentState.lastError); + } else { + clearError(); + } +} + +function renderRecording(recording) { + currentRecording = recording || {}; + const count = currentRecording.count || 0; + const mode = currentRecording.mode === "inspect" ? "inspect" : "record"; + recordingStatus.textContent = currentRecording.playing + ? `playing ${count}` + : currentRecording.recording ? `${mode} ${count}` : `idle ${count}`; + recordingStatus.classList.toggle("active", !!currentRecording.recording); + recordedScript.value = currentRecording.script || ""; + recordButton.classList.toggle("primary", mode === "record"); + inspectButton.classList.toggle("primary", mode === "inspect"); + playRecordButton.disabled = !!currentRecording.playing || count === 0; + stopRecordButton.disabled = !currentRecording.recording; + clearRecordButton.disabled = count === 0 && !currentRecording.recording; + copyScriptButton.disabled = !recordedScript.value.trim(); +} + +function statusLabel(state) { + if (!state) { + return "Unknown"; + } + if (state.connected) { + if (state.platformOrigin) { + return `Connected to ${originLabel(state.platformOrigin)}`; + } + return "Connected"; + } + if (state.sharing) { + return state.status || "Sharing"; + } + return state.status || "Idle"; +} + +function originLabel(origin) { + try { + return new URL(origin).host; + } catch (_error) { + return origin; + } +} + +function setBusy(busy) { + shareButton.disabled = busy; + stopButton.disabled = busy || !(currentState && currentState.sharing); + copyButton.disabled = busy || !(currentState && currentState.shareUrl); + recordButton.disabled = busy; + inspectButton.disabled = busy; + playRecordButton.disabled = busy || !(currentRecording && currentRecording.count > 0) || !!(currentRecording && currentRecording.playing); + stopRecordButton.disabled = busy || !(currentRecording && currentRecording.recording); + clearRecordButton.disabled = busy || !(currentRecording && (currentRecording.count || currentRecording.recording)); + copyScriptButton.disabled = busy || !recordedScript.value.trim(); +} + +function sendMessage(message) { + return new Promise((resolve, reject) => { + chrome.runtime.sendMessage(message, (response) => { + const runtimeError = chrome.runtime.lastError; + if (runtimeError) { + reject(new Error(runtimeError.message)); + return; + } + if (!response || response.ok !== true) { + reject(new Error((response && response.error) || "Extension message failed")); + return; + } + resolve(response.result); + }); + }); +} + +function showError(error) { + errorText.textContent = typeof error === "string" ? error : error.message || String(error); + errorText.classList.add("visible"); +} + +function clearError() { + errorText.textContent = ""; + errorText.classList.remove("visible"); +} diff --git a/extension/edge-share/provider.js b/extension/edge-share/provider.js new file mode 100644 index 0000000..1463eea --- /dev/null +++ b/extension/edge-share/provider.js @@ -0,0 +1,115 @@ +"use strict"; + +(() => { + if (window.browserConnection) { + return; + } + + const SOURCE_PAGE = "browser-connection:page"; + const SOURCE_CONTENT = "browser-connection:content"; + const SOURCE_RECORDER = "browser-connection:recorder"; + const pending = new Map(); + let nextId = 1; + + function request(input) { + const payload = normalizeRequest(input); + const id = String(nextId++); + + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + window.postMessage( + { + source: SOURCE_PAGE, + id, + method: payload.method, + params: payload.params + }, + window.location.origin + ); + }); + } + + function normalizeRequest(input) { + if (!input || typeof input !== "object") { + throw new Error("browserConnection.request expects an object"); + } + const method = String(input.method || "").trim(); + if (!method) { + throw new Error("browserConnection request method is required"); + } + const params = input.params && typeof input.params === "object" ? input.params : {}; + return { method, params }; + } + + window.addEventListener("message", (event) => { + if (event.source !== window || event.origin !== window.location.origin) { + return; + } + const message = event.data; + if (!message || message.source !== SOURCE_CONTENT || !message.id) { + return; + } + + const entry = pending.get(message.id); + if (!entry) { + return; + } + pending.delete(message.id); + + if (message.ok) { + entry.resolve(message.result); + } else { + entry.reject(new Error(message.error || "browserConnection request failed")); + } + }); + + Object.defineProperty(window, "browserConnection", { + value: Object.freeze({ request }), + enumerable: false, + configurable: false, + writable: false + }); + + window.dispatchEvent(new Event("browserConnection#initialized")); + + installNavigationRecorder(); + + function installNavigationRecorder() { + if (window.__browserConnectionRecorderInstalled) { + return; + } + Object.defineProperty(window, "__browserConnectionRecorderInstalled", { + value: true, + enumerable: false, + configurable: false, + writable: false + }); + + const notify = () => { + window.postMessage( + { + source: SOURCE_RECORDER, + kind: "navigate", + href: location.href, + title: document.title || "" + }, + window.location.origin + ); + }; + + const pushState = history.pushState; + const replaceState = history.replaceState; + history.pushState = function (...args) { + const result = pushState.apply(this, args); + queueMicrotask(notify); + return result; + }; + history.replaceState = function (...args) { + const result = replaceState.apply(this, args); + queueMicrotask(notify); + return result; + }; + window.addEventListener("popstate", notify); + window.addEventListener("hashchange", notify); + } +})(); diff --git a/extension/edge-share/service_worker.js b/extension/edge-share/service_worker.js new file mode 100644 index 0000000..fe14382 --- /dev/null +++ b/extension/edge-share/service_worker.js @@ -0,0 +1,1598 @@ +"use strict"; + +const PROTOCOL_VERSION = 1; +const DEFAULT_RELAY_URL = "http://127.0.0.1:8765"; +const STORAGE_KEY = "edgeShareState"; +const RECONNECT_MIN_MS = 1000; +const RECONNECT_MAX_MS = 30000; +const RELAY_KEEPALIVE_MS = 20 * 1000; +const PLATFORM_CONNECT_TTL_MS = 2 * 60 * 1000; +const PLATFORM_RELAY_CONNECT_TIMEOUT_MS = 8000; +const MAX_RECORDED_ACTIONS = 500; + +let state = { + sharing: false, + connected: false, + relayUrl: DEFAULT_RELAY_URL, + sessionId: "", + browserToken: "", + agentToken: "", + shareUrl: "", + status: "idle", + lastError: "", + activeTabId: null, + platformOrigin: "", + platformHref: "", + workspaceId: "", + poolId: "", + browserName: "", + recording: false, + recordingTabId: null, + recorderMode: "record", + recordingStartedAt: "", + recordingStoppedAt: "", + recordedActions: [], + lastInspect: null, + playbackRunning: false, + playbackError: "", + playbackStepId: "", + updatedAt: "" +}; + +let socket = null; +let reconnectTimer = null; +let keepAliveTimer = null; +let reconnectDelayMs = RECONNECT_MIN_MS; +let intentionallyClosed = false; +const attachedTabs = new Set(); +const pendingPlatformRequests = new Map(); + +chrome.runtime.onInstalled.addListener(() => { + restoreState().then(connectIfNeeded).catch(reportError); +}); + +chrome.runtime.onStartup.addListener(() => { + restoreState().then(connectIfNeeded).catch(reportError); +}); + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + handleExtensionMessage(message, sender) + .then((result) => sendResponse({ ok: true, result })) + .catch((error) => sendResponse({ ok: false, error: errorMessage(error) })); + return true; +}); + +chrome.debugger.onDetach.addListener((source) => { + if (Number.isInteger(source.tabId)) { + attachedTabs.delete(source.tabId); + } +}); + +restoreState().then(connectIfNeeded).catch(reportError); + +async function handleExtensionMessage(message, sender) { + if (!message || typeof message.type !== "string") { + throw new Error("Invalid message"); + } + + if (message.type === "get_state") { + await restoreState(); + return publicState(); + } + + if (message.type === "get_recording") { + await restoreState(); + return recordingState(); + } + + if (message.type === "start_share") { + return startShare(message.relayUrl || DEFAULT_RELAY_URL); + } + + if (message.type === "start_recording") { + await restoreState(); + return startRecording(message.params || {}); + } + + if (message.type === "set_recording_mode") { + await restoreState(); + return setRecordingMode(message.mode); + } + + if (message.type === "stop_recording") { + await restoreState(); + return stopRecording(); + } + + if (message.type === "clear_recording") { + await restoreState(); + return clearRecording(); + } + + if (message.type === "recorder_action") { + await restoreState(); + return recordContentAction(message.action || {}, sender); + } + + if (message.type === "inspect_target") { + await restoreState(); + return recordInspectTarget(message.target || {}, sender); + } + + if (message.type === "play_recording") { + await restoreState(); + return playRecording(); + } + + if (message.type === "platform_request") { + return handlePlatformRequest(message, sender); + } + + if (message.type === "get_platform_connect_request") { + return getPlatformConnectRequest(message.requestId); + } + + if (message.type === "approve_platform_connect") { + return approvePlatformConnect(message.requestId); + } + + if (message.type === "reject_platform_connect") { + return rejectPlatformConnect(message.requestId); + } + + if (message.type === "stop_share") { + return stopShare(); + } + + throw new Error(`Unknown popup message: ${message.type}`); +} + +async function startShare(relayUrlInput, options = {}) { + const relayUrl = normalizeRelayUrl(relayUrlInput); + const sessionId = randomHex(12); + const browserToken = randomHex(24); + const agentToken = randomHex(24); + const shareUrl = buildShareUrl(relayUrl, sessionId, agentToken); + + intentionallyClosed = false; + reconnectDelayMs = RECONNECT_MIN_MS; + + await persistState({ + sharing: true, + connected: false, + relayUrl, + sessionId, + browserToken, + agentToken, + shareUrl, + status: "connecting", + lastError: "", + activeTabId: null, + platformOrigin: options.platformOrigin || "", + platformHref: options.platformHref || "", + workspaceId: options.workspaceId || "", + poolId: options.poolId || "", + browserName: options.browserName || "" + }); + + connectRelay(); + return publicState(); +} + +async function stopShare() { + intentionallyClosed = true; + clearReconnectTimer(); + clearKeepAliveTimer(); + + if (socket) { + try { + socket.close(1000, "sharing stopped"); + } catch (_error) { + // Ignore close errors while stopping. + } + socket = null; + } + + await detachAllDebuggers(); + + await persistState({ + sharing: false, + connected: false, + sessionId: "", + browserToken: "", + agentToken: "", + shareUrl: "", + status: "stopped", + lastError: "", + recording: false, + recordingTabId: null, + recorderMode: "record", + recordingStoppedAt: new Date().toISOString(), + playbackRunning: false, + playbackError: "", + playbackStepId: "", + platformOrigin: "", + platformHref: "", + workspaceId: "", + poolId: "", + browserName: "" + }); + + return publicState(); +} + +async function restoreState() { + const stored = await chromeCall(chrome.storage.local.get, chrome.storage.local, STORAGE_KEY); + if (stored && stored[STORAGE_KEY]) { + state = { ...state, ...stored[STORAGE_KEY] }; + } +} + +async function persistState(patch) { + state = { + ...state, + ...patch, + updatedAt: new Date().toISOString() + }; + + await chromeCall(chrome.storage.local.set, chrome.storage.local, { + [STORAGE_KEY]: state + }); + + notifyPopup(); +} + +function publicState() { + return { + sharing: state.sharing, + connected: state.connected, + relayUrl: state.relayUrl || DEFAULT_RELAY_URL, + sessionId: state.sessionId, + shareUrl: state.shareUrl, + status: state.status, + lastError: state.lastError, + activeTabId: state.activeTabId, + recording: state.recording, + recordingTabId: state.recordingTabId, + recorderMode: state.recorderMode || "record", + recordingCount: Array.isArray(state.recordedActions) ? state.recordedActions.length : 0, + recordingStartedAt: state.recordingStartedAt, + recordingStoppedAt: state.recordingStoppedAt, + platformOrigin: state.platformOrigin, + workspaceId: state.workspaceId, + poolId: state.poolId, + browserName: state.browserName, + updatedAt: state.updatedAt + }; +} + +function notifyPopup() { + try { + chrome.runtime.sendMessage({ type: "state_changed", state: publicState() }, () => { + // Popup may be closed; reading lastError prevents noisy extension logs. + void chrome.runtime.lastError; + }); + } catch (_error) { + // Popup may be closed. + } +} + +function notifyRecordingChanged() { + const message = { + type: "recording_state_changed", + recording: recordingState() + }; + + try { + chrome.tabs.query({}, (tabs) => { + const error = chrome.runtime.lastError; + if (error || !Array.isArray(tabs)) { + return; + } + for (const tab of tabs) { + if (!Number.isInteger(tab.id) || !isRecordableUrl(tab.url || "")) { + continue; + } + chrome.tabs.sendMessage(tab.id, message, () => { + // Some pages will not have this content script yet. + void chrome.runtime.lastError; + }); + } + }); + } catch (_error) { + // Tabs may be unavailable in restricted extension contexts. + } +} + +function connectIfNeeded() { + if (state.sharing) { + connectRelay(); + } +} + +function connectRelay() { + if (!state.sharing || !state.relayUrl || !state.sessionId || !state.browserToken) { + return; + } + + clearReconnectTimer(); + clearKeepAliveTimer(); + + if (socket) { + try { + socket.close(1000, "reconnecting"); + } catch (_error) { + // Continue with a new socket. + } + } + + const wsUrl = buildBrowserWsUrl( + state.relayUrl, + state.sessionId, + state.browserToken, + state.agentToken + ); + socket = new WebSocket(wsUrl); + + persistState({ connected: false, status: "connecting", lastError: "" }).catch(reportError); + + socket.addEventListener("open", () => { + reconnectDelayMs = RECONNECT_MIN_MS; + persistState({ connected: true, status: "connected", lastError: "" }).catch(reportError); + sendSocket({ + type: "hello", + role: "browser", + protocolVersion: PROTOCOL_VERSION, + sessionId: state.sessionId, + userAgent: navigator.userAgent + }); + startKeepAliveTimer(); + }); + + socket.addEventListener("message", (event) => { + handleRelayMessage(event.data).catch((error) => { + sendSocket({ + type: "event", + event: "handler_error", + error: errorMessage(error) + }); + }); + }); + + socket.addEventListener("close", (event) => { + clearKeepAliveTimer(); + socket = null; + persistState({ + connected: false, + status: state.sharing ? "disconnected" : "stopped", + lastError: event.reason || "" + }).catch(reportError); + + if (state.sharing && !intentionallyClosed) { + scheduleReconnect(); + } + }); + + socket.addEventListener("error", () => { + clearKeepAliveTimer(); + persistState({ lastError: "WebSocket error" }).catch(reportError); + }); +} + +function scheduleReconnect() { + clearReconnectTimer(); + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + reconnectDelayMs = Math.min(reconnectDelayMs * 2, RECONNECT_MAX_MS); + connectRelay(); + }, reconnectDelayMs); +} + +function clearReconnectTimer() { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } +} + +function startKeepAliveTimer() { + clearKeepAliveTimer(); + keepAliveTimer = setInterval(() => { + sendSocket({ + type: "keepalive", + at: new Date().toISOString() + }); + }, RELAY_KEEPALIVE_MS); +} + +function clearKeepAliveTimer() { + if (keepAliveTimer) { + clearInterval(keepAliveTimer); + keepAliveTimer = null; + } +} + +async function handlePlatformRequest(message, sender) { + if (message.method !== "connect") { + throw new Error(`Unsupported platform request method: ${message.method}`); + } + if (!sender || !sender.tab || !Number.isInteger(sender.tab.id) || !sender.url) { + throw new Error("Platform requests must come from a browser tab"); + } + + const pageUrl = new URL(sender.url); + if (pageUrl.protocol !== "http:" && pageUrl.protocol !== "https:") { + throw new Error("Platform requests must come from an http or https page"); + } + if (message.origin !== pageUrl.origin) { + throw new Error("Platform request origin did not match the sender tab"); + } + + const params = message.params && typeof message.params === "object" ? message.params : {}; + const requestId = randomHex(12); + const request = { + requestId, + origin: pageUrl.origin, + href: sender.url, + title: message.title || sender.tab.title || "", + tabId: sender.tab.id, + workspaceId: stringParam(params.workspaceId), + poolId: stringParam(params.poolId), + browserName: stringParam(params.displayName || params.browserName) || "Edge", + relayUrl: normalizeRelayUrl(stringParam(params.relayUrl) || pageUrl.origin), + createdAt: Date.now() + }; + + if (new URL(request.relayUrl).origin !== request.origin) { + throw new Error("Platform relayUrl must use the requesting page origin"); + } + + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pendingPlatformRequests.delete(requestId); + reject(new Error("Platform connect request expired")); + }, PLATFORM_CONNECT_TTL_MS); + + pendingPlatformRequests.set(requestId, { + request, + resolve, + reject, + timeout + }); + + chrome.windows.create( + { + url: chrome.runtime.getURL(`connect.html?requestId=${encodeURIComponent(requestId)}`), + type: "popup", + width: 420, + height: 560 + }, + () => { + const error = chrome.runtime.lastError; + if (error) { + clearTimeout(timeout); + pendingPlatformRequests.delete(requestId); + reject(new Error(error.message)); + } + } + ); + }); +} + +async function getPlatformConnectRequest(requestId) { + const entry = pendingPlatformRequests.get(String(requestId || "")); + if (!entry) { + throw new Error("Platform connect request was not found or expired"); + } + return sanitizePlatformRequest(entry.request); +} + +async function approvePlatformConnect(requestId) { + const id = String(requestId || ""); + const entry = pendingPlatformRequests.get(id); + if (!entry) { + throw new Error("Platform connect request was not found or expired"); + } + + pendingPlatformRequests.delete(id); + clearTimeout(entry.timeout); + + let started = false; + try { + await startShare(entry.request.relayUrl, { + platformOrigin: entry.request.origin, + platformHref: entry.request.href, + workspaceId: entry.request.workspaceId, + poolId: entry.request.poolId, + browserName: entry.request.browserName + }); + started = true; + if (!(await waitForRelayConnection(PLATFORM_RELAY_CONNECT_TIMEOUT_MS))) { + throw new Error(state.lastError || "Timed out connecting to browser relay"); + } + const result = publicState(); + const response = { + shareUrl: result.shareUrl, + sessionId: result.sessionId, + connected: result.connected, + relayUrl: result.relayUrl, + platformOrigin: entry.request.origin, + workspaceId: entry.request.workspaceId, + poolId: entry.request.poolId, + browserName: entry.request.browserName + }; + entry.resolve(response); + return response; + } catch (error) { + if (started) { + await stopShare().catch(reportError); + } + entry.reject(error); + throw error; + } +} + +async function rejectPlatformConnect(requestId) { + const id = String(requestId || ""); + const entry = pendingPlatformRequests.get(id); + if (!entry) { + return { rejected: true }; + } + + pendingPlatformRequests.delete(id); + clearTimeout(entry.timeout); + const error = new Error("User rejected browser connection"); + entry.reject(error); + return { rejected: true }; +} + +function sanitizePlatformRequest(request) { + return { + requestId: request.requestId, + origin: request.origin, + href: request.href, + title: request.title, + workspaceId: request.workspaceId, + poolId: request.poolId, + browserName: request.browserName, + relayUrl: request.relayUrl, + createdAt: request.createdAt + }; +} + +async function waitForRelayConnection(timeoutMs) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (state.connected) { + return true; + } + if (!state.sharing) { + return false; + } + await sleep(100); + } + return state.connected; +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function handleRelayMessage(rawData) { + let message; + try { + message = JSON.parse(rawData); + } catch (_error) { + sendSocket({ type: "event", event: "invalid_json" }); + return; + } + + if (message.type === "ping") { + sendSocket({ type: "pong", at: new Date().toISOString() }); + return; + } + + const requestId = message.id || message.requestId; + const command = message.command || message.method; + const params = message.params || {}; + + if (!requestId || !command) { + sendSocket({ + type: "event", + event: "ignored_message", + reason: "missing id or command" + }); + return; + } + + try { + const result = await handleCommand(command, params); + sendSocket({ + type: "response", + id: requestId, + ok: true, + result + }); + } catch (error) { + sendSocket({ + type: "response", + id: requestId, + ok: false, + error: errorMessage(error) + }); + } +} + +async function handleCommand(command, params) { + if (command === "navigate") { + return commandNavigate(params); + } + if (command === "evaluate") { + return commandEvaluate(params); + } + if (command === "snapshot") { + return commandSnapshot(params); + } + if (command === "click") { + return commandClick(params); + } + if (command === "type") { + return commandType(params); + } + if (command === "press_key") { + return commandPressKey(params); + } + if (command === "screenshot") { + return commandScreenshot(params); + } + if (command === "list_tabs") { + return commandListTabs(); + } + if (command === "activate_tab") { + return commandActivateTab(params); + } + if (command === "start_recording") { + return startRecording(params); + } + if (command === "set_recording_mode") { + return setRecordingMode(params.mode); + } + if (command === "stop_recording") { + return stopRecording(); + } + if (command === "clear_recording") { + return clearRecording(); + } + if (command === "play_recording") { + return playRecording(); + } + if (command === "recording_state") { + return recordingState(); + } + + throw new Error(`Unsupported command: ${command}`); +} + +async function commandNavigate(params) { + if (!params.url || typeof params.url !== "string") { + throw new Error("navigate requires params.url"); + } + + const tabId = await getTargetTabId(params); + const tab = await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { + url: params.url, + active: params.activate !== false + }); + + state.activeTabId = tab.id; + return { tab: tabSummary(tab) }; +} + +async function commandEvaluate(params) { + if (!params.expression || typeof params.expression !== "string") { + throw new Error("evaluate requires params.expression"); + } + + const tabId = await getTargetTabId(params); + const value = await evaluateInPage(tabId, params.expression); + return { + tab: await currentTabSummary(tabId), + value + }; +} + +async function commandSnapshot(params) { + const tabId = await getTargetTabId(params); + const snapshot = await runFunctionInPage(tabId, createSnapshot, [ + params.maxTextLength || 200000, + params.maxItems || 200 + ]); + + return { + tab: await currentTabSummary(tabId), + snapshot + }; +} + +async function commandClick(params) { + if (!params.selector || typeof params.selector !== "string") { + throw new Error("click requires params.selector"); + } + + const tabId = await getTargetTabId(params); + const result = await runFunctionInPage(tabId, clickSelector, [params.selector]); + return { + tab: await currentTabSummary(tabId), + action: result + }; +} + +async function commandType(params) { + if (typeof params.text !== "string") { + throw new Error("type requires params.text"); + } + + const tabId = await getTargetTabId(params); + const result = await runFunctionInPage(tabId, typeText, [ + params.selector || "", + params.text, + params.replace === true || params.clear === true + ]); + + return { + tab: await currentTabSummary(tabId), + action: result + }; +} + +async function commandPressKey(params) { + if (!params.key || typeof params.key !== "string") { + throw new Error("press_key requires params.key"); + } + + const tabId = await getTargetTabId(params); + const key = normalizeKey(params.key); + await sendKeyEvent(tabId, key, "rawKeyDown"); + + if (key.text) { + await sendKeyEvent(tabId, key, "char"); + } + + await sendKeyEvent(tabId, key, "keyUp"); + + return { + tab: await currentTabSummary(tabId), + action: { key: key.key, code: key.code } + }; +} + +async function commandScreenshot(params) { + const tabId = await getTargetTabId(params); + const format = params.format === "jpeg" ? "jpeg" : "png"; + const quality = format === "jpeg" ? clampNumber(params.quality || 80, 1, 100) : undefined; + + try { + await sendCdp(tabId, "Page.enable", {}); + const result = await sendCdp(tabId, "Page.captureScreenshot", { + format, + quality, + fromSurface: true, + captureBeyondViewport: params.fullPage === true + }); + + return { + tab: await currentTabSummary(tabId), + mimeType: `image/${format}`, + data: result.data + }; + } catch (error) { + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { active: true }); + const dataUrl = await chromeCall(chrome.tabs.captureVisibleTab, chrome.tabs, tab.windowId, { + format, + quality + }); + + return { + tab: tabSummary(tab), + mimeType: `image/${format}`, + dataUrl, + fallback: "tabs.captureVisibleTab", + warning: errorMessage(error) + }; + } +} + +async function commandListTabs() { + const windows = await chromeCall(chrome.windows.getAll, chrome.windows, { + populate: true + }); + const summaries = windows.map(windowSummary); + return { + windows: summaries, + tabs: summaries.flatMap((window) => window.tabs) + }; +} + +async function commandActivateTab(params) { + const tabId = await getTargetTabId(params); + const tab = await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { active: true }); + state.activeTabId = tab.id; + await persistState({ activeTabId: tab.id }); + return { tab: tabSummary(tab) }; +} + +async function startRecording(params = {}) { + const tabId = Number.isInteger(params.tabId) ? params.tabId : await getTargetTabId({}); + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + const startedAt = new Date().toISOString(); + const actions = []; + if (tab.url && isRecordableUrl(tab.url)) { + actions.push(recordedAction("navigate", { + url: tab.url, + title: tab.title || "", + tabId, + windowId: tab.windowId + })); + } + + await persistState({ + recording: true, + recordingTabId: null, + recorderMode: normalizeRecorderMode(params.mode), + recordingStartedAt: startedAt, + recordingStoppedAt: "", + recordedActions: actions, + lastInspect: null, + playbackError: "", + playbackStepId: "", + activeTabId: tabId + }); + + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function setRecordingMode(mode) { + if (!state.recording) { + return startRecording({ mode }); + } + await persistState({ + recorderMode: normalizeRecorderMode(mode), + lastInspect: null + }); + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function stopRecording() { + await persistState({ + recording: false, + recorderMode: "record", + recordingStoppedAt: new Date().toISOString(), + lastInspect: null, + playbackRunning: false + }); + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function clearRecording() { + await persistState({ + recording: false, + recordingTabId: null, + recorderMode: "record", + recordingStartedAt: "", + recordingStoppedAt: "", + recordedActions: [], + lastInspect: null, + playbackRunning: false, + playbackError: "", + playbackStepId: "" + }); + const recording = recordingState(); + notifyRecordingChanged(); + return recording; +} + +async function recordContentAction(action, sender) { + if (!state.recording || !sender?.tab || !Number.isInteger(sender.tab.id)) { + return { recorded: false }; + } + if ((state.recorderMode || "record") !== "record") { + return { recorded: false }; + } + if (!isRecordableUrl(sender.tab.url || action.url || "")) { + return { recorded: false }; + } + + const normalized = recordedAction(action.kind, { + ...action, + tabId: sender.tab.id, + windowId: sender.tab.windowId, + title: action.title || sender.tab.title || "", + url: action.url || sender.tab.url || "" + }); + if (!normalized) { + return { recorded: false }; + } + + const actions = Array.isArray(state.recordedActions) ? [...state.recordedActions] : []; + upsertRecordedAction(actions, normalized); + while (actions.length > MAX_RECORDED_ACTIONS) { + actions.shift(); + } + + await persistState({ recordedActions: actions, activeTabId: sender.tab.id }); + notifyRecordingChanged(); + return { recorded: true, action: normalized, count: actions.length }; +} + +async function recordInspectTarget(target, sender) { + if (!state.recording || (state.recorderMode || "record") !== "inspect") { + return { inspected: false }; + } + if (!sender?.tab || !Number.isInteger(sender.tab.id)) { + return { inspected: false }; + } + if (!isRecordableUrl(sender.tab.url || target.url || "")) { + return { inspected: false }; + } + + const inspected = { + at: new Date().toISOString(), + selector: String(target.selector || "").slice(0, 1024), + label: String(target.label || "").slice(0, 512), + tag: String(target.tag || "").slice(0, 64), + url: String(target.url || sender.tab.url || "").slice(0, 4096), + title: String(target.title || sender.tab.title || "").slice(0, 512), + tabId: sender.tab.id, + windowId: sender.tab.windowId + }; + + await persistState({ lastInspect: inspected, activeTabId: sender.tab.id }); + notifyRecordingChanged(); + return { inspected: true, target: inspected }; +} + +async function playRecording() { + const actions = Array.isArray(state.recordedActions) ? [...state.recordedActions] : []; + if (actions.length === 0) { + throw new Error("No recorded actions to play"); + } + + await persistState({ + playbackRunning: true, + playbackError: "", + playbackStepId: "" + }); + notifyRecordingChanged(); + + let caught = null; + try { + for (const action of actions) { + await persistState({ playbackStepId: action.id || "" }); + notifyRecordingChanged(); + await playRecordedAction(action); + } + } catch (error) { + caught = error; + await persistState({ playbackError: errorMessage(error) }); + } finally { + await persistState({ playbackRunning: false }); + notifyRecordingChanged(); + } + + if (caught) { + throw caught; + } + return recordingState(); +} + +async function playRecordedAction(action) { + const tabId = await playbackTabId(action); + if (action.kind === "navigate" && action.url) { + await chromeCall(chrome.tabs.update, chrome.tabs, tabId, { + url: action.url, + active: true + }); + state.activeTabId = tabId; + await waitForTabReady(tabId, 10000); + return; + } + if (action.kind === "click" && action.selector) { + await runFunctionInPage(tabId, clickSelector, [action.selector]); + return; + } + if (action.kind === "fill" && action.selector) { + await runFunctionInPage(tabId, typeText, [action.selector, action.text || "", true]); + return; + } + if (action.kind === "press" && action.key) { + if (action.selector) { + await runFunctionInPage(tabId, focusSelector, [action.selector]); + } + const key = normalizeKey(action.key); + await sendKeyEvent(tabId, key, "rawKeyDown"); + if (key.text) { + await sendKeyEvent(tabId, key, "char"); + } + await sendKeyEvent(tabId, key, "keyUp"); + } +} + +async function playbackTabId(action) { + if (Number.isInteger(action.tabId)) { + try { + await chromeCall(chrome.tabs.get, chrome.tabs, action.tabId); + state.activeTabId = action.tabId; + return action.tabId; + } catch (_error) { + // The original tab was closed; fall back to the active tab. + } + } + return getTargetTabId({}); +} + +async function waitForTabReady(tabId, timeoutMs) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + if (tab.status === "complete") { + return; + } + } catch (_error) { + return; + } + await sleep(100); + } +} + +function recordingState() { + const actions = Array.isArray(state.recordedActions) ? state.recordedActions : []; + return { + recording: state.recording, + mode: state.recorderMode || "record", + tabId: state.recordingTabId, + startedAt: state.recordingStartedAt, + stoppedAt: state.recordingStoppedAt, + count: actions.length, + actions, + lastInspect: state.lastInspect || null, + playing: !!state.playbackRunning, + playbackError: state.playbackError || "", + playbackStepId: state.playbackStepId || "", + script: renderRecordedPlaywright(actions) + }; +} + +function normalizeRecorderMode(mode) { + return mode === "inspect" ? "inspect" : "record"; +} + +function recordedAction(kind, fields) { + const actionKind = String(kind || ""); + if (!["navigate", "click", "fill", "press"].includes(actionKind)) { + return null; + } + const action = { + id: randomHex(6), + kind: actionKind, + at: new Date().toISOString(), + url: String(fields.url || "").slice(0, 4096), + title: String(fields.title || "").slice(0, 512), + tabId: Number.isInteger(fields.tabId) ? fields.tabId : null, + windowId: Number.isInteger(fields.windowId) ? fields.windowId : null + }; + if (fields.selector) action.selector = String(fields.selector).slice(0, 1024); + if (fields.text !== undefined) action.text = String(fields.text).slice(0, 4096); + if (fields.key) action.key = String(fields.key).slice(0, 128); + if (fields.label) action.label = String(fields.label).slice(0, 512); + if (fields.tag) action.tag = String(fields.tag).slice(0, 64); + return action; +} + +function upsertRecordedAction(actions, action) { + const previous = actions[actions.length - 1]; + if ( + previous && + action.kind === "fill" && + previous.kind === "fill" && + previous.selector === action.selector + ) { + actions[actions.length - 1] = { ...previous, ...action, id: previous.id }; + return; + } + if ( + previous && + action.kind === "navigate" && + previous.kind === "navigate" && + previous.url === action.url + ) { + return; + } + actions.push(action); +} + +function renderRecordedPlaywright(actions) { + const lines = [ + "module.exports = async ({ page }) => {" + ]; + let previousTabId = null; + for (const action of actions) { + if (action.tabId && action.tabId !== previousTabId) { + lines.push(` // Tab ${action.tabId}${action.title ? `: ${action.title}` : ""}`); + previousTabId = action.tabId; + } + if (action.kind === "navigate" && action.url) { + lines.push(` await page.goto(${JSON.stringify(action.url)});`); + } else if (action.kind === "click" && action.selector) { + lines.push(` await page.click(${JSON.stringify(action.selector)});`); + } else if (action.kind === "fill" && action.selector) { + lines.push(` await page.fill(${JSON.stringify(action.selector)}, ${JSON.stringify(action.text || "")});`); + } else if (action.kind === "press" && action.key) { + if (action.selector) { + lines.push(` await page.press(${JSON.stringify(action.selector)}, ${JSON.stringify(action.key)});`); + } else { + lines.push(` await page.keyboard.press(${JSON.stringify(action.key)});`); + } + } + } + lines.push("};"); + return lines.join("\n"); +} + +function isRecordableUrl(url) { + return /^https?:\/\//i.test(String(url || "")); +} + +async function getTargetTabId(params) { + if (Number.isInteger(params.tabId)) { + state.activeTabId = params.tabId; + return params.tabId; + } + + if (Number.isInteger(state.activeTabId)) { + try { + await chromeCall(chrome.tabs.get, chrome.tabs, state.activeTabId); + return state.activeTabId; + } catch (_error) { + state.activeTabId = null; + } + } + + const activeTabs = await chromeCall(chrome.tabs.query, chrome.tabs, { + active: true, + lastFocusedWindow: true + }); + + if (activeTabs.length > 0 && Number.isInteger(activeTabs[0].id)) { + state.activeTabId = activeTabs[0].id; + return activeTabs[0].id; + } + + const tabs = await chromeCall(chrome.tabs.query, chrome.tabs, { active: true }); + if (tabs.length > 0 && Number.isInteger(tabs[0].id)) { + state.activeTabId = tabs[0].id; + return tabs[0].id; + } + + throw new Error("No active tab found"); +} + +async function currentTabSummary(tabId) { + const tab = await chromeCall(chrome.tabs.get, chrome.tabs, tabId); + return tabSummary(tab); +} + +function windowSummary(window) { + return { + id: window.id, + focused: window.focused, + incognito: window.incognito, + profile: window.incognito ? "incognito" : "regular", + type: window.type || "", + state: window.state || "", + top: window.top, + left: window.left, + width: window.width, + height: window.height, + tabs: (window.tabs || []).map((tab) => tabSummary(tab, window)) + }; +} + +function tabSummary(tab, window) { + return { + id: tab.id, + windowId: tab.windowId, + active: tab.active, + index: tab.index, + incognito: tab.incognito || window?.incognito || false, + profile: tab.incognito || window?.incognito ? "incognito" : "regular", + pinned: tab.pinned || false, + audible: tab.audible || false, + discarded: tab.discarded || false, + title: tab.title || "", + url: tab.url || "", + status: tab.status || "" + }; +} + +async function evaluateInPage(tabId, expression) { + await sendCdp(tabId, "Runtime.enable", {}); + const result = await sendCdp(tabId, "Runtime.evaluate", { + expression, + awaitPromise: true, + returnByValue: true, + userGesture: true + }); + + if (result.exceptionDetails) { + throw new Error(formatException(result.exceptionDetails)); + } + + return unwrapRemoteObject(result.result); +} + +async function runFunctionInPage(tabId, fn, args) { + const expression = `(${fn.toString()})(${args.map((arg) => JSON.stringify(arg)).join(",")})`; + return evaluateInPage(tabId, expression); +} + +async function ensureDebugger(tabId) { + if (attachedTabs.has(tabId)) { + return; + } + + try { + await chromeCall(chrome.debugger.attach, chrome.debugger, { tabId }, "1.3"); + attachedTabs.add(tabId); + } catch (error) { + if (String(errorMessage(error)).includes("Another debugger is already attached")) { + attachedTabs.add(tabId); + return; + } + throw error; + } +} + +async function detachAllDebuggers() { + const tabIds = Array.from(attachedTabs); + attachedTabs.clear(); + + await Promise.all( + tabIds.map(async (tabId) => { + try { + await chromeCall(chrome.debugger.detach, chrome.debugger, { tabId }); + } catch (_error) { + // The tab may have closed or detached already. + } + }) + ); +} + +async function sendCdp(tabId, method, params) { + await ensureDebugger(tabId); + return chromeCall(chrome.debugger.sendCommand, chrome.debugger, { tabId }, method, params || {}); +} + +async function sendKeyEvent(tabId, key, type) { + await sendCdp(tabId, "Input.dispatchKeyEvent", { + type, + key: key.key, + code: key.code, + windowsVirtualKeyCode: key.keyCode, + nativeVirtualKeyCode: key.keyCode, + text: type === "char" ? key.text : "", + unmodifiedText: type === "char" ? key.text : "", + modifiers: 0 + }); +} + +function createSnapshot(maxTextLength, maxItems) { + function trim(value, length) { + return String(value || "").replace(/\s+/g, " ").trim().slice(0, length); + } + + function cssPath(element) { + if (!element || element.nodeType !== Node.ELEMENT_NODE) { + return ""; + } + + if (element.id) { + return `#${CSS.escape(element.id)}`; + } + + const parts = []; + let current = element; + + while (current && current.nodeType === Node.ELEMENT_NODE && parts.length < 5) { + let part = current.tagName.toLowerCase(); + if (current.classList.length > 0) { + part += `.${CSS.escape(current.classList[0])}`; + } + + const parent = current.parentElement; + if (parent) { + const siblings = Array.from(parent.children).filter((child) => child.tagName === current.tagName); + if (siblings.length > 1) { + part += `:nth-of-type(${siblings.indexOf(current) + 1})`; + } + } + + parts.unshift(part); + current = parent; + } + + return parts.join(" > "); + } + + function describe(element) { + return { + selector: cssPath(element), + tag: element.tagName.toLowerCase(), + role: element.getAttribute("role") || "", + label: trim( + element.getAttribute("aria-label") || + element.getAttribute("alt") || + element.getAttribute("title") || + element.value || + element.innerText, + 300 + ), + href: element.href || "", + type: element.getAttribute("type") || "" + }; + } + + const clickableSelector = "a,button,input,textarea,select,[role='button'],[contenteditable='true']"; + const elements = Array.from(document.querySelectorAll(clickableSelector)) + .slice(0, maxItems) + .map(describe); + + return { + url: location.href, + title: document.title, + text: trim(document.body ? document.body.innerText : "", maxTextLength), + activeElement: cssPath(document.activeElement), + elements + }; +} + +function clickSelector(selector) { + const element = document.querySelector(selector); + if (!element) { + throw new Error(`No element matches selector: ${selector}`); + } + + element.scrollIntoView({ block: "center", inline: "center", behavior: "auto" }); + const rect = element.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const y = rect.top + rect.height / 2; + + element.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, clientX: x, clientY: y })); + element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, clientX: x, clientY: y })); + element.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, clientX: x, clientY: y })); + element.click(); + + return { + selector, + text: String(element.innerText || element.value || "").trim().slice(0, 300), + rect: { + x: Math.round(rect.x), + y: Math.round(rect.y), + width: Math.round(rect.width), + height: Math.round(rect.height) + } + }; +} + +function typeText(selector, text, replace) { + const element = selector ? document.querySelector(selector) : document.activeElement; + if (!element) { + throw new Error(selector ? `No element matches selector: ${selector}` : "No active element"); + } + + element.scrollIntoView({ block: "center", inline: "center", behavior: "auto" }); + element.focus(); + + if (element.isContentEditable) { + if (replace) { + element.innerText = ""; + } + document.execCommand("insertText", false, text); + } else if ("value" in element) { + if (replace) { + element.value = text; + } else { + const start = Number.isInteger(element.selectionStart) ? element.selectionStart : element.value.length; + const end = Number.isInteger(element.selectionEnd) ? element.selectionEnd : element.value.length; + element.value = `${element.value.slice(0, start)}${text}${element.value.slice(end)}`; + const cursor = start + text.length; + if (element.setSelectionRange) { + element.setSelectionRange(cursor, cursor); + } + } + element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: text })); + element.dispatchEvent(new Event("change", { bubbles: true })); + } else { + throw new Error("Target element is not editable"); + } + + return { + selector: selector || "", + tag: element.tagName.toLowerCase(), + textLength: text.length + }; +} + +function focusSelector(selector) { + const element = document.querySelector(selector); + if (!element) { + throw new Error(`No element matches selector: ${selector}`); + } + + element.scrollIntoView({ block: "center", inline: "center", behavior: "auto" }); + element.focus(); + return { + selector, + tag: element.tagName.toLowerCase() + }; +} + +function normalizeKey(input) { + const aliases = { + escape: ["Escape", "Escape", 27], + esc: ["Escape", "Escape", 27], + enter: ["Enter", "Enter", 13], + tab: ["Tab", "Tab", 9], + backspace: ["Backspace", "Backspace", 8], + delete: ["Delete", "Delete", 46], + arrowup: ["ArrowUp", "ArrowUp", 38], + arrowdown: ["ArrowDown", "ArrowDown", 40], + arrowleft: ["ArrowLeft", "ArrowLeft", 37], + arrowright: ["ArrowRight", "ArrowRight", 39], + home: ["Home", "Home", 36], + end: ["End", "End", 35], + pageup: ["PageUp", "PageUp", 33], + pagedown: ["PageDown", "PageDown", 34], + space: [" ", "Space", 32] + }; + + const lower = input.toLowerCase(); + if (aliases[lower]) { + const [key, code, keyCode] = aliases[lower]; + return { key, code, keyCode, text: key.length === 1 ? key : "" }; + } + + if (input.length === 1) { + const keyCode = input.toUpperCase().charCodeAt(0); + return { key: input, code: `Key${input.toUpperCase()}`, keyCode, text: input }; + } + + return { key: input, code: input, keyCode: 0, text: "" }; +} + +function unwrapRemoteObject(remoteObject) { + if (!remoteObject) { + return null; + } + if (Object.prototype.hasOwnProperty.call(remoteObject, "value")) { + return remoteObject.value; + } + if (remoteObject.unserializableValue) { + return remoteObject.unserializableValue; + } + return remoteObject.description || null; +} + +function formatException(exceptionDetails) { + if (exceptionDetails.exception) { + return unwrapRemoteObject(exceptionDetails.exception) || exceptionDetails.exception.description || "Evaluation failed"; + } + return exceptionDetails.text || "Evaluation failed"; +} + +function sendSocket(message) { + if (!socket || socket.readyState !== WebSocket.OPEN) { + return false; + } + socket.send(JSON.stringify(message)); + return true; +} + +function buildShareUrl(relayUrl, sessionId, agentToken) { + const url = new URL(relayUrl); + const prefix = url.pathname.replace(/\/+$/, ""); + url.pathname = `${prefix}/share/${encodeURIComponent(sessionId)}`; + url.search = ""; + url.hash = `agent=${encodeURIComponent(agentToken)}`; + return url.href; +} + +function buildBrowserWsUrl(relayUrl, sessionId, browserToken, agentToken) { + const url = new URL(relayUrl); + url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; + const prefix = url.pathname.replace(/\/+$/, ""); + url.pathname = `${prefix}/ws/browser/${encodeURIComponent(sessionId)}`; + url.search = `token=${encodeURIComponent(browserToken)}&agent_token=${encodeURIComponent(agentToken)}`; + url.hash = ""; + return url.href; +} + +function normalizeRelayUrl(input) { + const raw = String(input || "").trim(); + if (!raw) { + throw new Error("Relay URL is required"); + } + + const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`; + const url = new URL(withScheme); + + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("Relay URL must use http or https"); + } + + url.search = ""; + url.hash = ""; + url.pathname = url.pathname.replace(/\/+$/, ""); + return url.href.replace(/\/$/, ""); +} + +function stringParam(value) { + if (typeof value !== "string") { + return ""; + } + return value.trim().slice(0, 512); +} + +function randomHex(lengthBytes) { + const bytes = new Uint8Array(lengthBytes); + crypto.getRandomValues(bytes); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +function clampNumber(value, min, max) { + const number = Number(value); + if (!Number.isFinite(number)) { + return min; + } + return Math.min(Math.max(number, min), max); +} + +function chromeCall(fn, context, ...args) { + return new Promise((resolve, reject) => { + try { + fn.call(context, ...args, (result) => { + const error = chrome.runtime.lastError; + if (error) { + reject(new Error(error.message)); + } else { + resolve(result); + } + }); + } catch (error) { + reject(error); + } + }); +} + +function reportError(error) { + persistState({ lastError: errorMessage(error), status: "error" }).catch(() => { + // Avoid recursive error reporting. + }); +} + +function errorMessage(error) { + if (!error) { + return "Unknown error"; + } + if (error.message) { + return error.message; + } + return String(error); +} diff --git a/skills/browser-cli/SKILL.md b/skills/browser-cli/SKILL.md new file mode 100644 index 0000000..70189d9 --- /dev/null +++ b/skills/browser-cli/SKILL.md @@ -0,0 +1,93 @@ +--- +name: browser-cli +description: Use rbc CLI commands to inspect and automate browser sessions without MCP, including Playwright-style scripts for CDP and shared-extension browsers. Trigger this skill when Codex needs browser automation, page inspection, clicking, typing, tab/window control, screenshots, Playwright page APIs, or multi-step JavaScript browser scripts while minimizing MCP token overhead. +--- + +# Browser CLI + +Use `rbc` instead of MCP browser tools when a normal shell command can drive the active browser. Prefer CLI commands for repeatable page workflows, scripts, screenshots, and audit traces. + +## Workflow + +1. Resolve the target: + - Use `rbc edge ...` for a browser shared by the Edge extension. + - Use `rbc chromium ...` for the managed container browser. + - Use `rbc active ...` when the noVNC/control panel selected browser should be used. + - Use `--control-url`, `--share-url`, or `--cdp-url` only when overriding the configured pool. +2. Inspect first: + - Run `rbc snapshot` before choosing selectors. + - For shared-extension targets, run `rbc tabs` to see windows/tabs and `rbc activate-tab ` before acting on a non-active tab. +3. Prefer scripts for multi-step actions: + - Put complex DOM logic in a temporary `.js` file. + - Run it with `rbc eval --file /path/to/script.js`. + - Return a compact JSON object from the script. +4. Log actions when transparency matters: + - Add `--trace-dir ` to append `rbc.jsonl`. + - Use `--json` when another script will parse the output. + +## Commands + +```bash +rbc edge snapshot +rbc edge navigate https://example.com +rbc edge click 'button[type="submit"]' +rbc edge type 'input[name="q"]' 'search text' +rbc edge key Enter +rbc edge eval 'document.title' +rbc edge eval --file /tmp/browser-task.js +rbc edge pw --code 'return await page.title()' +rbc edge pw /tmp/playwright-task.js +rbc edge screenshot --full-page --output /tmp/page.png +rbc edge tabs +rbc edge activate-tab 123 +rbc chromium snapshot +rbc active pw --code 'return await page.title()' +``` + +## Script Pattern + +Use one browser round trip for several DOM reads/actions: + +```js +(() => { + const button = [...document.querySelectorAll('button')] + .find((el) => /save|submit/i.test(el.innerText || '')); + if (!button) return { ok: false, error: 'button not found' }; + button.click(); + return { ok: true, title: document.title, url: location.href }; +})() +``` + +Run it: + +```bash +rbc edge --json --trace-dir .browser-trace eval --file /tmp/browser-task.js +``` + +## Playwright Pattern + +Use `pw` when Playwright-style page APIs are more ergonomic. CDP-backed targets run real +Playwright; shared-extension targets run the supported compatibility subset. + +```js +await page.goto('https://example.com'); +await page.getByRole('link', { name: /more/i }).click(); +return { title: await page.title(), url: page.url() }; +``` + +Run it: + +```bash +rbc edge --json --trace-dir .browser-trace pw /tmp/playwright-task.js +``` + +`pw` exposes `playwright`, `browser`, `context`, `page`, and `pages` in scope. On shared-extension targets, use the supported subset: `page.goto`, `title`, `url`, `evaluate`, `click`, `fill`, `type`, `press`, `screenshot`, `content`, `locator`, `getByText`, `getByRole`, `waitForSelector`, `waitForTimeout`, and `waitForLoadState`. Unsupported Playwright APIs fail with a clear error. + +## Rules + +- Do not expose full shared browser URLs in logs or final answers; they contain bearer tokens. +- Prefer browser names such as `edge`, `chromium`, or `active`; the platform should provide `BROWSER_CONNECTION_CONTROL_URL` or browser env aliases. +- Do not use `tabs` or `activate-tab` against direct CDP targets; those are shared-extension only. +- Expect `pw` on shared-extension targets to be a compatibility subset, not full Playwright. +- If browser-pool discovery fails, retry with explicit `--control-url`, `--share-url`, or `--cdp-url`. +- Keep command output compact; use screenshots only when visual state matters. diff --git a/skills/browser-cli/agents/openai.yaml b/skills/browser-cli/agents/openai.yaml new file mode 100644 index 0000000..d496769 --- /dev/null +++ b/skills/browser-cli/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Browser CLI" + short_description: "Automate browsers with rbc and Playwright" + default_prompt: "Use $browser-cli to inspect the current browser page and automate it with rbc or Playwright-over-CDP." diff --git a/src/bin/browser-connection-relay.rs b/src/bin/browser-connection-relay.rs new file mode 100644 index 0000000..0d8d7d9 --- /dev/null +++ b/src/bin/browser-connection-relay.rs @@ -0,0 +1,22 @@ +//! WebSocket relay for browser-connection shared browser extension sessions. + +use clap::Parser; +use docker_git_browser_connection::shared_browser::{run_relay, RelayConfig, DEFAULT_RELAY_BIND}; + +#[derive(Debug, Parser)] +#[command( + name = "browser-connection-relay", + version, + about = "WebSocket relay for browser-connection shared browser links" +)] +struct Cli { + /// Address to bind, e.g. 127.0.0.1:8765 or 0.0.0.0:8765. + #[arg(long, default_value = DEFAULT_RELAY_BIND)] + bind: String, +} + +fn main() -> anyhow::Result<()> { + env_logger::init(); + let cli = Cli::parse(); + run_relay(RelayConfig::new(cli.bind)) +} diff --git a/src/bin/browser-connection.rs b/src/bin/browser-connection.rs index 96bc34d..83685dd 100644 --- a/src/bin/browser-connection.rs +++ b/src/bin/browser-connection.rs @@ -6,8 +6,12 @@ //! This command intentionally replaces external upstream Playwright MCP configs. use clap::Parser; +use docker_git_browser_connection::compute_browser_control_panel_port; use docker_git_browser_connection::mcp::{ - project_id_from_env_or_default, run_stdio, McpServerConfig, SERVER_NAME, + active_browser_from_env, browser_endpoints_from_env, parse_named_browser_endpoint, + parse_named_browser_novnc_url, parse_named_browser_share_url, parse_named_browser_vnc_endpoint, + project_id_from_env_or_default, run_stdio, McpServerConfig, NamedBrowserEndpoint, + PERSONAL_BROWSER_NAME, SERVER_NAME, }; use std::io; @@ -30,6 +34,46 @@ struct Cli { #[arg(long)] cdp_endpoint: Option, + /// Register an additional browser target as NAME=CDP_ENDPOINT. Can be repeated. + #[arg(long = "browser", value_name = "NAME=CDP_ENDPOINT")] + browser: Vec, + + /// Register a VNC display endpoint for a browser target as NAME=HOST:PORT. Can be repeated. + #[arg(long = "browser-vnc", value_name = "NAME=HOST:PORT")] + browser_vnc: Vec, + + /// Register a pre-existing noVNC URL for a browser target as NAME=URL. Can be repeated. + #[arg(long = "browser-novnc", value_name = "NAME=URL")] + browser_novnc: Vec, + + /// Register a shared browser extension link as NAME=URL. Can be repeated. + #[arg(long = "browser-share", value_name = "NAME=URL")] + browser_share: Vec, + + /// Register and select a personal browser CDP endpoint, e.g. http://127.0.0.1:9222. + #[arg(long)] + personal_browser: Option, + + /// Register a VNC display endpoint for the personal browser, e.g. host.docker.internal:5900. + #[arg(long)] + personal_vnc: Option, + + /// Register a pre-existing noVNC URL for the personal browser. + #[arg(long)] + personal_novnc: Option, + + /// Browser target to use at startup: managed, explicit, personal, or a --browser name. + #[arg(long)] + active_browser: Option, + + /// Host port for the local browser/noVNC control panel. + #[arg(long)] + control_port: Option, + + /// Disable the local browser/noVNC control panel. + #[arg(long)] + no_control_panel: bool, + /// Do not start/reuse Docker browser on startup; useful for MCP handshake tests. #[arg(long)] no_start_browser: bool, @@ -38,12 +82,67 @@ struct Cli { fn main() -> anyhow::Result<()> { env_logger::init(); let cli = Cli::parse(); - let config = McpServerConfig::new( - project_id_from_env_or_default(cli.project), + let mut browser_endpoints = browser_endpoints_from_env()?; + let mut active_browser = active_browser_from_env(); + let project_id = project_id_from_env_or_default(cli.project); + let control_port = if cli.no_control_panel { + None + } else { + Some( + cli.control_port + .unwrap_or_else(|| compute_browser_control_panel_port(&project_id)), + ) + }; + + for browser in &cli.browser { + browser_endpoints.push(parse_named_browser_endpoint(browser)?); + } + + let mut config = McpServerConfig::new( + project_id, cli.network, cli.cdp_endpoint, !cli.no_start_browser, - ); + ) + .with_browser_endpoints(browser_endpoints) + .with_control_port(control_port); + + for browser_vnc in &cli.browser_vnc { + let (name, endpoint) = parse_named_browser_vnc_endpoint(browser_vnc)?; + config = config.with_browser_vnc_endpoint(name, endpoint)?; + } + + for browser_novnc in &cli.browser_novnc { + let (name, url) = parse_named_browser_novnc_url(browser_novnc)?; + config = config.with_browser_novnc_url(name, url)?; + } + + for browser_share in &cli.browser_share { + let (name, url) = parse_named_browser_share_url(browser_share)?; + config = config.with_browser_share_url(name, url)?; + } + + if let Some(endpoint) = cli.personal_browser { + config = config.with_browser_endpoints(vec![NamedBrowserEndpoint::new( + PERSONAL_BROWSER_NAME, + endpoint, + )?]); + active_browser = Some(PERSONAL_BROWSER_NAME.to_string()); + } + + if let Some(endpoint) = cli.personal_vnc { + config = config.with_browser_vnc_endpoint(PERSONAL_BROWSER_NAME, endpoint)?; + } + + if let Some(url) = cli.personal_novnc { + config = config.with_browser_novnc_url(PERSONAL_BROWSER_NAME, url)?; + } + + if cli.active_browser.is_some() { + active_browser = cli.active_browser; + } + + let config = config.with_active_browser(active_browser)?; let stdin = io::stdin(); let stdout = io::stdout(); diff --git a/src/bin/playwright/mod.rs b/src/bin/playwright/mod.rs new file mode 100644 index 0000000..0549f75 --- /dev/null +++ b/src/bin/playwright/mod.rs @@ -0,0 +1,263 @@ +use anyhow::{anyhow, Context, Result}; +use docker_git_browser_connection::browser_actions::BrowserTarget; +use docker_git_browser_connection::shared_browser::SharedBrowserClient; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{SystemTime, UNIX_EPOCH}; + +const PLAYWRIGHT_CORE_VERSION: &str = "1.61.1"; + +pub(super) fn run_playwright_script( + target: &BrowserTarget, + source: &str, + allow_close: bool, +) -> Result { + match target { + BrowserTarget::Cdp { endpoint } => run_cdp_playwright_script(endpoint, source, allow_close), + BrowserTarget::Shared { share_url } => { + run_shared_playwright_script(share_url, source, allow_close) + } + } +} + +fn run_cdp_playwright_script(endpoint: &str, source: &str, allow_close: bool) -> Result { + ensure_node_available()?; + let playwright_core_path = ensure_playwright_core()?; + let wrapper = playwright_wrapper_source(endpoint, &playwright_core_path, source, allow_close)?; + let wrapper_path = write_temp_playwright_wrapper(&wrapper)?; + let output = run_node_playwright_wrapper(&wrapper_path); + let _ = fs::remove_file(&wrapper_path); + output +} + +fn run_shared_playwright_script( + share_url: &str, + source: &str, + allow_close: bool, +) -> Result { + let client = SharedBrowserClient::new(share_url); + let result = client.run_playwright(source, allow_close)?; + render_shared_result(&result) +} + +pub(super) fn parse_playwright_result(text: &str) -> Value { + serde_json::from_str(text).unwrap_or_else(|_| json!({ "text": text })) +} + +fn ensure_node_available() -> Result<()> { + Command::new("node") + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("node is required for rbc pw but was not found")? + .success() + .then_some(()) + .ok_or_else(|| anyhow!("node is required for rbc pw but did not run successfully")) +} + +fn ensure_playwright_core() -> Result { + if let Some(path) = node_resolve_playwright_core(None)? { + return Ok(path); + }; + let node_modules = install_temp_playwright_core()?; + node_resolve_playwright_core(Some(&node_modules))?.ok_or_else(|| { + anyhow!( + "playwright-core was installed but node could not resolve it from {}", + node_modules.display() + ) + }) +} + +fn run_node_playwright_wrapper(wrapper_path: &Path) -> Result { + let output = Command::new("node") + .arg(wrapper_path) + .stdin(Stdio::null()) + .output() + .context("failed to run node for rbc pw")?; + if !output.status.success() { + return Err(anyhow!( + "rbc pw failed with status {}\n{}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&output.stdout) + .trim_end_matches(['\r', '\n']) + .to_string()) +} + +fn render_shared_result(value: &Value) -> Result { + if value.is_null() { + return Ok(String::new()); + } + if let Some(text) = value.as_str() { + return Ok(text.to_string()); + } + serde_json::to_string_pretty(value).context("failed to render shared-extension rbc pw result") +} + +fn node_resolve_playwright_core(node_modules: Option<&Path>) -> Result> { + let mut command = Command::new("node"); + command + .args(["-p", "require.resolve('playwright-core')"]) + .stdin(Stdio::null()) + .stderr(Stdio::null()); + if let Some(node_modules) = node_modules { + command.env("NODE_PATH", node_path_with(node_modules)?); + } + let output = command + .output() + .context("failed to ask node to resolve playwright-core")?; + if !output.status.success() { + return Ok(None); + } + let path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + Ok((!path.is_empty()).then_some(path)) +} + +fn install_temp_playwright_core() -> Result { + let package_dir = + std::env::temp_dir().join(format!("rbc-playwright-core-{PLAYWRIGHT_CORE_VERSION}")); + let node_modules = package_dir.join("node_modules"); + let package_json = node_modules.join("playwright-core/package.json"); + if package_json.exists() { + return Ok(node_modules); + } + fs::create_dir_all(&package_dir) + .with_context(|| format!("failed to create {}", package_dir.display()))?; + let package = format!("playwright-core@{PLAYWRIGHT_CORE_VERSION}"); + let output = Command::new("npm") + .args(["install", "--silent", "--no-audit", "--no-fund", "--prefix"]) + .arg(&package_dir) + .arg(&package) + .stdin(Stdio::null()) + .output() + .context("playwright-core is not installed and npm is required for rbc pw fallback")?; + if !output.status.success() { + return Err(anyhow!( + "failed to install {package} for rbc pw fallback with status {}\n{}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(node_modules) +} + +fn node_path_with(path: &Path) -> Result { + let mut paths = vec![path.to_path_buf()]; + if let Some(existing) = std::env::var_os("NODE_PATH") { + paths.extend(std::env::split_paths(&existing)); + } + std::env::join_paths(paths).map_err(|error| anyhow!("failed to build NODE_PATH: {error}")) +} + +fn write_temp_playwright_wrapper(source: &str) -> Result { + let path = std::env::temp_dir().join(format!( + "rbc-playwright-{}-{}.js", + std::process::id(), + unix_ms() + )); + fs::write(&path, source).with_context(|| format!("failed to write {}", path.display()))?; + Ok(path) +} + +fn playwright_wrapper_source( + cdp_url: &str, + playwright_core_path: &str, + user_source: &str, + allow_close: bool, +) -> Result { + let cdp_url = serde_json::to_string(cdp_url).context("failed to encode CDP URL")?; + let playwright_core_path = + serde_json::to_string(playwright_core_path).context("failed to encode Playwright path")?; + let user_source = + serde_json::to_string(user_source).context("failed to encode Playwright script")?; + Ok(format!( + r#""use strict"; +const cdpUrl = {cdp_url}; +const playwrightCorePath = {playwright_core_path}; +const userSource = {user_source}; +const allowClose = {allow_close}; + +function renderResult(value) {{ + if (value === undefined) return ""; + if (typeof value === "string") return value; + return JSON.stringify(value, null, 2); +}} + +(async () => {{ + const playwright = require(playwrightCorePath); + const browser = await playwright.chromium.connectOverCDP(cdpUrl); + const contexts = browser.contexts(); + const context = contexts[0] || await browser.newContext(); + const pages = context.pages(); + const page = pages[0] || await context.newPage(); + if (!allowClose) {{ + const blocked = async () => {{ + throw new Error("rbc pw keeps shared browser sessions open; pass --allow-close to close them"); + }}; + browser.close = blocked; + context.close = blocked; + }} + const run = new Function( + "playwright", + "browser", + "context", + "page", + "pages", + `"use strict"; return (async () => {{ +${{userSource}} + }})();` + ); + const result = await run(playwright, browser, context, page, pages); + const output = renderResult(result); + if (output) process.stdout.write(String(output)); +}})().catch((error) => {{ + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}}); +"# + )) +} + +fn unix_ms() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wrapper_uses_cdp_and_guards_close_by_default() { + let wrapper = playwright_wrapper_source( + "http://127.0.0.1:9222", + "/tmp/node_modules/playwright-core/index.js", + "return await page.title();", + false, + ) + .unwrap(); + assert!(wrapper.contains("require(playwrightCorePath)")); + assert!(wrapper.contains("connectOverCDP(cdpUrl)")); + assert!(wrapper.contains("browser.close = blocked")); + assert!(wrapper.contains("context.close = blocked")); + assert!(wrapper.contains("return await page.title();")); + } + + #[test] + fn shared_results_render_as_pretty_json() { + let result = render_shared_result(&json!({ + "ok": true, + "mode": "playwright-crx" + })) + .unwrap(); + assert!(result.contains("\"mode\": \"playwright-crx\"")); + } +} diff --git a/src/bin/rbc.rs b/src/bin/rbc.rs new file mode 100644 index 0000000..68b7c0e --- /dev/null +++ b/src/bin/rbc.rs @@ -0,0 +1,638 @@ +//! CLI browser automation without MCP. + +use anyhow::{anyhow, Context, Result}; +use clap::{Parser, Subcommand}; +use docker_git_browser_connection::browser_actions::{ + command_result_json, dispatch_browser_command, BrowserCommand, BrowserTarget, +}; +use serde_json::{json, Value}; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +mod playwright; +mod target_resolution; + +#[derive(Debug, Parser)] +#[command( + name = "rbc", + version, + about = "Rust browser-connection CLI automation without MCP" +)] +struct Cli { + /// Shared browser extension URL from Edge Share. + #[arg(long, global = true, conflicts_with = "cdp_url")] + share_url: Option, + + /// CDP endpoint, e.g. http://127.0.0.1:9223. + #[arg(long, global = true, conflicts_with = "share_url")] + cdp_url: Option, + + /// Control panel port. Defaults to the deterministic port for TARGET when used as a project id. + #[arg(long, global = true)] + control_port: Option, + + /// Browser control panel URL. Defaults to BROWSER_CONNECTION_CONTROL_URL, then local project panel. + #[arg(long, global = true, value_name = "URL")] + control_url: Option, + + /// Emit machine-readable JSON. + #[arg(long = "json", global = true)] + json_output: bool, + + /// Append JSONL action traces under this directory. + #[arg(long, global = true, value_name = "DIR")] + trace_dir: Option, + + /// Browser name from the configured pool, or a legacy docker-git project id. + target: String, + + #[command(subcommand)] + command: TopCommand, +} + +#[derive(Debug, Subcommand)] +enum TopCommand { + /// Optional explicit namespace for tool commands: rbc TARGET tools snapshot. + Tools { + #[command(subcommand)] + command: ToolCommand, + }, + /// Navigate the current page to a URL. + Navigate { url: String }, + /// Return page title, URL, visible text, and simple selectors. + Snapshot, + /// Evaluate JavaScript in the current page. + Eval { + /// JavaScript expression to evaluate. + #[arg(value_name = "JS", conflicts_with_all = ["expression", "file"])] + code: Option, + /// JavaScript expression to evaluate. + #[arg(long, conflicts_with_all = ["code", "file"])] + expression: Option, + /// Read JavaScript expression from a file. + #[arg(long, value_name = "PATH", conflicts_with_all = ["code", "expression"])] + file: Option, + }, + /// Click an element by CSS selector. + Click { selector: String }, + /// Set text in an input-like element. + Type { selector: String, text: String }, + /// Press a keyboard key. + Key { key: String }, + /// Capture a PNG screenshot. + Screenshot { + /// Capture beyond the viewport. + #[arg(long)] + full_page: bool, + /// Decode the screenshot and write PNG bytes to this path. + #[arg(long, value_name = "PNG")] + output: Option, + }, + /// List tabs/windows for a shared-extension browser. + Tabs, + /// Activate a tab by browser tab id. + ActivateTab { tab_id: i64 }, + /// Run Playwright code against a browser target. + Pw { + /// JavaScript file body for CDP targets, or Playwright CRX script for shared targets. + #[arg(value_name = "SCRIPT", conflicts_with = "code")] + script: Option, + /// JavaScript body for CDP targets, or Playwright CRX actions for shared targets. + #[arg(long, value_name = "JS", conflicts_with = "script")] + code: Option, + /// Allow the script to close the shared browser/context. + #[arg(long)] + allow_close: bool, + }, +} + +#[derive(Debug, Clone, Subcommand)] +enum ToolCommand { + /// Navigate the current page to a URL. + Navigate { url: String }, + /// Return page title, URL, visible text, and simple selectors. + Snapshot, + /// Evaluate JavaScript in the current page. + Eval { + /// JavaScript expression to evaluate. + #[arg(value_name = "JS", conflicts_with_all = ["expression", "file"])] + code: Option, + /// JavaScript expression to evaluate. + #[arg(long, conflicts_with_all = ["code", "file"])] + expression: Option, + /// Read JavaScript expression from a file. + #[arg(long, value_name = "PATH", conflicts_with_all = ["code", "expression"])] + file: Option, + }, + /// Click an element by CSS selector. + Click { selector: String }, + /// Set text in an input-like element. + Type { selector: String, text: String }, + /// Press a keyboard key. + Key { key: String }, + /// Capture a PNG screenshot. + Screenshot { + /// Capture beyond the viewport. + #[arg(long)] + full_page: bool, + /// Decode the screenshot and write PNG bytes to this path. + #[arg(long, value_name = "PNG")] + output: Option, + }, + /// List tabs/windows for a shared-extension browser. + Tabs, + /// Activate a tab by browser tab id. + ActivateTab { tab_id: i64 }, +} + +fn main() { + env_logger::init(); + if let Err(error) = run() { + eprintln!("{error:#}"); + std::process::exit(1); + } +} + +fn run() -> Result<()> { + let cli = Cli::parse(); + if matches!(cli.command, TopCommand::Pw { .. }) { + return run_playwright_cli(&cli); + } + + run_tool_cli(&cli) +} + +fn run_tool_cli(cli: &Cli) -> Result<()> { + let target = resolve_target(cli)?; + let tool = tool_command(&cli.command); + let command = browser_command(&tool)?; + let started = Instant::now(); + let result = dispatch_browser_command(&target, &command); + let duration_ms = started.elapsed().as_millis() as u64; + + match result { + Ok(text) => { + let output = command_output(&command, &text, cli)?; + write_trace( + cli, + &target, + &command, + duration_ms, + Ok(&output.trace_result), + )?; + print_output(cli, &target, &command, &output)?; + Ok(()) + } + Err(error) => { + write_trace(cli, &target, &command, duration_ms, Err(&error))?; + Err(error) + } + } +} + +fn run_playwright_cli(cli: &Cli) -> Result<()> { + let (script, allow_close) = playwright_input(&cli.command)?; + let target = resolve_target(cli)?; + let started = Instant::now(); + let result = playwright::run_playwright_script(&target, &script, allow_close); + let duration_ms = started.elapsed().as_millis() as u64; + + match result { + Ok(output) => { + let json_result = playwright::parse_playwright_result(&output); + write_trace_event( + cli, + &target, + "browser_playwright", + duration_ms, + Ok(&json_result), + )?; + print_event_output(cli, &target, "browser_playwright", &output, &json_result)?; + Ok(()) + } + Err(error) => { + write_trace_event(cli, &target, "browser_playwright", duration_ms, Err(&error))?; + Err(error) + } + } +} + +#[derive(Debug)] +struct CommandOutput { + text: String, + json_result: Value, + trace_result: Value, +} + +fn resolve_target(cli: &Cli) -> Result { + target_resolution::resolve_target(target_resolution::ResolveOptions { + share_url: cli.share_url.as_deref(), + cdp_url: cli.cdp_url.as_deref(), + control_port: cli.control_port, + control_url: cli.control_url.as_deref(), + target: &cli.target, + }) +} + +fn tool_command(command: &TopCommand) -> ToolCommand { + match command { + TopCommand::Tools { command } => command.clone(), + TopCommand::Navigate { url } => ToolCommand::Navigate { url: url.clone() }, + TopCommand::Snapshot => ToolCommand::Snapshot, + TopCommand::Eval { + code, + expression, + file, + } => ToolCommand::Eval { + code: code.clone(), + expression: expression.clone(), + file: file.clone(), + }, + TopCommand::Click { selector } => ToolCommand::Click { + selector: selector.clone(), + }, + TopCommand::Type { selector, text } => ToolCommand::Type { + selector: selector.clone(), + text: text.clone(), + }, + TopCommand::Key { key } => ToolCommand::Key { key: key.clone() }, + TopCommand::Screenshot { full_page, output } => ToolCommand::Screenshot { + full_page: *full_page, + output: output.clone(), + }, + TopCommand::Tabs => ToolCommand::Tabs, + TopCommand::ActivateTab { tab_id } => ToolCommand::ActivateTab { tab_id: *tab_id }, + TopCommand::Pw { .. } => unreachable!("Playwright command is handled before tool dispatch"), + } +} + +fn browser_command(command: &ToolCommand) -> Result { + match command { + ToolCommand::Navigate { url } => Ok(BrowserCommand::Navigate { url: url.clone() }), + ToolCommand::Snapshot => Ok(BrowserCommand::Snapshot), + ToolCommand::Eval { + code, + expression, + file, + } => { + let expression = match (code, expression, file) { + (Some(expression), None, None) | (None, Some(expression), None) => { + expression.clone() + } + (None, None, Some(path)) => fs::read_to_string(path) + .with_context(|| format!("failed to read {}", path.display()))?, + (None, None, None) => { + return Err(anyhow!("eval requires JS, --expression, or --file")) + } + _ => { + return Err(anyhow!( + "eval accepts only one of JS, --expression, or --file" + )) + } + }; + Ok(BrowserCommand::Evaluate { expression }) + } + ToolCommand::Click { selector } => Ok(BrowserCommand::Click { + selector: selector.clone(), + }), + ToolCommand::Type { selector, text } => Ok(BrowserCommand::TypeText { + selector: selector.clone(), + text: text.clone(), + }), + ToolCommand::Key { key } => Ok(BrowserCommand::PressKey { key: key.clone() }), + ToolCommand::Screenshot { full_page, .. } => Ok(BrowserCommand::Screenshot { + full_page: *full_page, + }), + ToolCommand::Tabs => Ok(BrowserCommand::ListTabs), + ToolCommand::ActivateTab { tab_id } => Ok(BrowserCommand::ActivateTab { tab_id: *tab_id }), + } +} + +fn command_output(command: &BrowserCommand, text: &str, cli: &Cli) -> Result { + if let BrowserCommand::Screenshot { .. } = command { + if let ToolCommand::Screenshot { + output: Some(path), .. + } = tool_command(&cli.command) + { + let written = write_screenshot(text, &path)?; + let result = json!({ + "path": path, + "mimeType": written.mime_type, + "bytes": written.bytes + }); + return Ok(CommandOutput { + text: path.display().to_string(), + json_result: result.clone(), + trace_result: result, + }); + } + } + + let result = command_result_json(command, text); + Ok(CommandOutput { + text: text.to_string(), + json_result: result.clone(), + trace_result: result, + }) +} + +fn print_output( + cli: &Cli, + target: &BrowserTarget, + command: &BrowserCommand, + output: &CommandOutput, +) -> Result<()> { + if cli.json_output { + println!( + "{}", + serde_json::to_string_pretty(&json!({ + "ok": true, + "tool": command.tool_name(), + "target": { + "kind": target.kind(), + "label": target.safe_label() + }, + "result": output.json_result + }))? + ); + } else { + println!("{}", output.text); + } + Ok(()) +} + +fn print_event_output( + cli: &Cli, + target: &BrowserTarget, + tool: &str, + text: &str, + result: &Value, +) -> Result<()> { + if cli.json_output { + println!( + "{}", + serde_json::to_string_pretty(&json!({ + "ok": true, + "tool": tool, + "target": { + "kind": target.kind(), + "label": target.safe_label() + }, + "result": result + }))? + ); + } else if !text.is_empty() { + println!("{text}"); + } + Ok(()) +} + +fn write_trace( + cli: &Cli, + target: &BrowserTarget, + command: &BrowserCommand, + duration_ms: u64, + result: Result<&Value, &anyhow::Error>, +) -> Result<()> { + let Some(dir) = cli.trace_dir.as_ref() else { + return Ok(()); + }; + fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?; + let path = dir.join("rbc.jsonl"); + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .with_context(|| format!("failed to open {}", path.display()))?; + let event = match result { + Ok(value) => json!({ + "at": unix_ms(), + "tool": command.tool_name(), + "target": { "kind": target.kind(), "label": target.safe_label() }, + "durationMs": duration_ms, + "ok": true, + "result": value + }), + Err(error) => json!({ + "at": unix_ms(), + "tool": command.tool_name(), + "target": { "kind": target.kind(), "label": target.safe_label() }, + "durationMs": duration_ms, + "ok": false, + "error": error.to_string() + }), + }; + writeln!(file, "{}", serde_json::to_string(&event)?) + .with_context(|| format!("failed to write {}", path.display())) +} + +fn write_trace_event( + cli: &Cli, + target: &BrowserTarget, + tool: &str, + duration_ms: u64, + result: Result<&Value, &anyhow::Error>, +) -> Result<()> { + let Some(dir) = cli.trace_dir.as_ref() else { + return Ok(()); + }; + fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?; + let path = dir.join("rbc.jsonl"); + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .with_context(|| format!("failed to open {}", path.display()))?; + let event = match result { + Ok(value) => json!({ + "at": unix_ms(), + "tool": tool, + "target": { "kind": target.kind(), "label": target.safe_label() }, + "durationMs": duration_ms, + "ok": true, + "result": value + }), + Err(error) => json!({ + "at": unix_ms(), + "tool": tool, + "target": { "kind": target.kind(), "label": target.safe_label() }, + "durationMs": duration_ms, + "ok": false, + "error": error.to_string() + }), + }; + writeln!(file, "{}", serde_json::to_string(&event)?) + .with_context(|| format!("failed to write {}", path.display())) +} + +fn playwright_input(command: &TopCommand) -> Result<(String, bool)> { + let TopCommand::Pw { + script, + code, + allow_close, + } = command + else { + return Err(anyhow!("internal error: expected pw command")); + }; + let source = match (script, code) { + (Some(path), None) => fs::read_to_string(path) + .with_context(|| format!("failed to read {}", path.display()))?, + (None, Some(code)) => code.clone(), + (None, None) => return Err(anyhow!("pw requires SCRIPT or --code")), + (Some(_), Some(_)) => return Err(anyhow!("pw accepts only one of SCRIPT or --code")), + }; + Ok((source, *allow_close)) +} + +struct WrittenScreenshot { + mime_type: String, + bytes: usize, +} + +fn write_screenshot(text: &str, path: &Path) -> Result { + let (mime_type, data) = screenshot_payload(text)?; + let bytes = decode_base64(&data)?; + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + fs::create_dir_all(parent) + .with_context(|| format!("failed to create {}", parent.display()))?; + } + fs::write(path, &bytes).with_context(|| format!("failed to write {}", path.display()))?; + Ok(WrittenScreenshot { + mime_type, + bytes: bytes.len(), + }) +} + +fn screenshot_payload(text: &str) -> Result<(String, String)> { + let trimmed = text.trim(); + if trimmed.starts_with("data:") { + return parse_data_url(trimmed); + } + let value: Value = + serde_json::from_str(trimmed).context("screenshot result was not JSON or data URL")?; + if let Some(data_url) = value.get("dataUrl").and_then(Value::as_str) { + return parse_data_url(data_url); + } + if let Some(data) = value.get("data").and_then(Value::as_str) { + let mime_type = value + .get("mimeType") + .and_then(Value::as_str) + .unwrap_or("image/png") + .to_string(); + return Ok((mime_type, data.to_string())); + } + Err(anyhow!("screenshot result did not include dataUrl or data")) +} + +fn parse_data_url(data_url: &str) -> Result<(String, String)> { + let (header, data) = data_url + .split_once(',') + .ok_or_else(|| anyhow!("invalid data URL screenshot"))?; + let mime_type = header + .strip_prefix("data:") + .and_then(|value| value.strip_suffix(";base64")) + .unwrap_or("image/png") + .to_string(); + Ok((mime_type, data.to_string())) +} + +fn decode_base64(input: &str) -> Result> { + let mut output = Vec::new(); + let mut buffer = 0u32; + let mut bits = 0u8; + for ch in input.chars().filter(|ch| !ch.is_whitespace()) { + if ch == '=' { + break; + } + let value = match ch { + 'A'..='Z' => ch as u32 - 'A' as u32, + 'a'..='z' => ch as u32 - 'a' as u32 + 26, + '0'..='9' => ch as u32 - '0' as u32 + 52, + '+' => 62, + '/' => 63, + _ => return Err(anyhow!("invalid base64 character `{ch}`")), + }; + buffer = (buffer << 6) | value; + bits += 6; + if bits >= 8 { + bits -= 8; + output.push(((buffer >> bits) & 0xff) as u8); + } + } + Ok(output) +} + +fn unix_ms() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes_base64_with_padding() { + assert_eq!(decode_base64("TWE=").unwrap(), b"Ma"); + assert_eq!(decode_base64("TQ==").unwrap(), b"M"); + } + + #[test] + fn parses_shared_screenshot_json_payload() { + let (mime, data) = screenshot_payload(r#"{"mimeType":"image/png","data":"TQ=="}"#).unwrap(); + assert_eq!(mime, "image/png"); + assert_eq!(data, "TQ=="); + } + + #[test] + fn eval_command_reads_expression_from_file() { + let path = std::env::temp_dir().join(format!("rbc-eval-{}.js", unix_ms())); + fs::write(&path, "document.title").unwrap(); + let command = browser_command(&ToolCommand::Eval { + code: None, + expression: None, + file: Some(path.clone()), + }) + .unwrap(); + let _ = fs::remove_file(path); + assert_eq!( + command, + BrowserCommand::Evaluate { + expression: "document.title".to_string() + } + ); + } + + #[test] + fn eval_command_accepts_direct_javascript() { + let command = browser_command(&ToolCommand::Eval { + code: Some("document.title".to_string()), + expression: None, + file: None, + }) + .unwrap(); + assert_eq!( + command, + BrowserCommand::Evaluate { + expression: "document.title".to_string() + } + ); + } + + #[test] + fn writes_screenshot_png_from_data_url() { + let path = std::env::temp_dir().join(format!("rbc-shot-{}.png", unix_ms())); + let written = write_screenshot("data:image/png;base64,TQ==", &path).unwrap(); + assert_eq!(written.mime_type, "image/png"); + assert_eq!(written.bytes, 1); + assert_eq!(fs::read(&path).unwrap(), b"M"); + let _ = fs::remove_file(path); + } +} diff --git a/src/bin/target_resolution/mod.rs b/src/bin/target_resolution/mod.rs new file mode 100644 index 0000000..9d0c0ff --- /dev/null +++ b/src/bin/target_resolution/mod.rs @@ -0,0 +1,319 @@ +use anyhow::{anyhow, Context, Result}; +use docker_git_browser_connection::browser_actions::BrowserTarget; +use docker_git_browser_connection::mcp::{ + active_browser_from_env, browser_endpoints_from_env, NamedBrowserEndpoint, +}; +use docker_git_browser_connection::{ + compute_browser_control_panel_port, compute_browser_ports, render_cdp_url_for_ports, +}; +use serde_json::Value; +use std::env; +use std::process::Command; + +pub(super) struct ResolveOptions<'a> { + pub share_url: Option<&'a str>, + pub cdp_url: Option<&'a str>, + pub control_port: Option, + pub control_url: Option<&'a str>, + pub target: &'a str, +} + +pub(super) fn resolve_target(options: ResolveOptions<'_>) -> Result { + if let Some(url) = options.share_url { + return Ok(BrowserTarget::shared(url)); + } + if let Some(url) = options.cdp_url { + return Ok(BrowserTarget::cdp(url)); + } + + let selector = options.target.trim(); + if selector.is_empty() { + return Err(anyhow!("browser target must not be empty")); + } + + if let Some(url) = configured_control_url(options.control_url) { + let inventory = load_control_panel_inventory_url(&url)?; + return target_from_inventory_for_selector(&inventory, selector) + .with_context(|| format!("control panel {url} did not expose browser `{selector}`")); + } + + if let Some(target) = target_from_env_endpoints(selector)? { + return Ok(target); + } + + if let Some(project) = project_id_from_env() { + let port = options + .control_port + .unwrap_or_else(|| compute_browser_control_panel_port(&project)); + if let Ok(inventory) = load_control_panel_inventory(port) { + if let Ok(target) = target_from_inventory_for_selector(&inventory, selector) { + return Ok(target); + } + } + } + + let port = options + .control_port + .unwrap_or_else(|| compute_browser_control_panel_port(selector)); + match load_control_panel_inventory(port) { + Ok(inventory) => target_from_inventory(&inventory).with_context(|| { + format!("control panel on port {port} did not expose an active browser") + }), + Err(_) => Ok(BrowserTarget::cdp(render_cdp_url_for_ports( + compute_browser_ports(selector), + ))), + } +} + +fn load_control_panel_inventory(port: u16) -> Result { + let url = format!("http://127.0.0.1:{port}/api/browsers"); + load_control_panel_inventory_url(&url) +} + +fn load_control_panel_inventory_url(url: &str) -> Result { + let url = control_panel_inventory_url(url)?; + let output = Command::new("curl") + .args(["-fsS", url.as_str()]) + .output() + .with_context(|| format!("failed to run curl for {url}"))?; + if !output.status.success() { + return Err(anyhow!( + "control panel request failed with status {}", + output.status + )); + } + serde_json::from_slice(&output.stdout).context("control panel inventory was not JSON") +} + +fn target_from_inventory(inventory: &Value) -> Result { + target_from_inventory_for_selector(inventory, "active") +} + +fn target_from_inventory_for_selector(inventory: &Value, selector: &str) -> Result { + let browser = browser_from_inventory(inventory, selector)?; + target_from_browser_inventory(browser) +} + +fn browser_from_inventory<'a>(inventory: &'a Value, selector: &str) -> Result<&'a Value> { + let active = inventory + .get("active") + .and_then(Value::as_str) + .ok_or_else(|| anyhow!("inventory did not include active browser"))?; + let browsers = inventory + .get("browsers") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("inventory did not include browsers"))?; + let selector = selector.trim(); + if selector.eq_ignore_ascii_case("active") { + return browsers + .iter() + .find(|browser| browser.get("active").and_then(Value::as_bool) == Some(true)) + .or_else(|| { + browsers + .iter() + .find(|browser| browser.get("name").and_then(Value::as_str) == Some(active)) + }) + .ok_or_else(|| anyhow!("active browser `{active}` was not found in inventory")); + } + + browsers + .iter() + .find(|browser| browser.get("name").and_then(Value::as_str) == Some(selector)) + .or_else(|| { + selector.eq_ignore_ascii_case("chromium").then(|| { + browsers + .iter() + .find(|browser| browser.get("name").and_then(Value::as_str) == Some("managed")) + })? + }) + .ok_or_else(|| { + let names = browsers + .iter() + .filter_map(|browser| browser.get("name").and_then(Value::as_str)) + .collect::>() + .join(", "); + anyhow!("browser `{selector}` was not found in inventory; available: {names}") + }) +} + +fn target_from_browser_inventory(browser: &Value) -> Result { + if let Some(share_url) = browser + .get("shareUrl") + .and_then(Value::as_str) + .filter(|url| !url.trim().is_empty()) + { + return Ok(BrowserTarget::shared(share_url)); + } + if let Some(endpoint) = browser + .get("cdpEndpoint") + .and_then(Value::as_str) + .filter(|url| !url.trim().is_empty()) + { + return Ok(BrowserTarget::cdp(endpoint)); + } + let name = browser + .get("name") + .and_then(Value::as_str) + .unwrap_or("browser"); + Err(anyhow!( + "browser `{name}` has neither shareUrl nor cdpEndpoint" + )) +} + +fn target_from_env_endpoints(selector: &str) -> Result> { + let endpoints = browser_endpoints_from_env().context("failed to parse browser target env")?; + let Some(endpoint) = endpoint_from_env_for_selector(&endpoints, selector) else { + return Ok(None); + }; + if let Some(share_url) = endpoint + .share_url + .as_deref() + .filter(|url| !url.trim().is_empty()) + { + return Ok(Some(BrowserTarget::shared(share_url))); + } + if !endpoint.cdp_endpoint.trim().is_empty() { + return Ok(Some(BrowserTarget::cdp(&endpoint.cdp_endpoint))); + } + Ok(None) +} + +fn endpoint_from_env_for_selector<'a>( + endpoints: &'a [NamedBrowserEndpoint], + selector: &str, +) -> Option<&'a NamedBrowserEndpoint> { + let selector = selector.trim(); + if selector.eq_ignore_ascii_case("active") { + return active_browser_from_env() + .and_then(|active| endpoint_from_env_for_selector(endpoints, &active)) + .or_else(|| endpoints.first()); + } + endpoints + .iter() + .find(|endpoint| endpoint.name == selector) + .or_else(|| { + selector + .eq_ignore_ascii_case("chromium") + .then(|| endpoints.iter().find(|endpoint| endpoint.name == "managed"))? + }) +} + +fn configured_control_url(control_url: Option<&str>) -> Option { + control_url.and_then(nonempty_string).or_else(|| { + env::var("BROWSER_CONNECTION_CONTROL_URL") + .ok() + .and_then(|value| nonempty_string(&value)) + }) +} + +fn control_panel_inventory_url(input: &str) -> Result { + let raw = input.trim(); + if raw.is_empty() { + return Err(anyhow!("control URL must not be empty")); + } + let base = raw.trim_end_matches('/'); + if base.ends_with("/api/browsers") { + return Ok(base.to_string()); + } + Ok(format!("{base}/api/browsers")) +} + +fn project_id_from_env() -> Option { + env::var("DOCKER_GIT_PROJECT_ID") + .ok() + .and_then(|value| nonempty_string(&value)) + .or_else(|| { + env::var("PROJECT_ID") + .ok() + .and_then(|value| nonempty_string(&value)) + }) +} + +fn nonempty_string(value: &str) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn chooses_share_target_before_cdp_from_inventory() { + let inventory = json!({ + "active": "edge", + "browsers": [{ + "name": "edge", + "active": true, + "shareUrl": "https://relay.example/share/s#agent=a", + "cdpEndpoint": "http://127.0.0.1:1" + }] + }); + let target = target_from_inventory(&inventory).unwrap(); + assert!(matches!(target, BrowserTarget::Shared { .. })); + } + + #[test] + fn selects_named_browser_even_when_inactive() { + let inventory = json!({ + "active": "managed", + "browsers": [ + { + "name": "managed", + "active": true, + "cdpEndpoint": "http://127.0.0.1:9223" + }, + { + "name": "edge", + "active": false, + "shareUrl": "https://relay.example/share/s#agent=a" + } + ] + }); + let target = target_from_inventory_for_selector(&inventory, "edge").unwrap(); + assert!(matches!(target, BrowserTarget::Shared { .. })); + } + + #[test] + fn chromium_alias_selects_managed_browser() { + let inventory = json!({ + "active": "edge", + "browsers": [ + { + "name": "edge", + "active": true, + "shareUrl": "https://relay.example/share/s#agent=a" + }, + { + "name": "managed", + "active": false, + "cdpEndpoint": "http://127.0.0.1:9223" + } + ] + }); + let target = target_from_inventory_for_selector(&inventory, "chromium").unwrap(); + assert_eq!(target, BrowserTarget::cdp("http://127.0.0.1:9223")); + } + + #[test] + fn active_selector_uses_inventory_active_browser() { + let inventory = json!({ + "active": "edge", + "browsers": [ + { + "name": "managed", + "active": false, + "cdpEndpoint": "http://127.0.0.1:9223" + }, + { + "name": "edge", + "active": true, + "shareUrl": "https://relay.example/share/s#agent=a" + } + ] + }); + let target = target_from_inventory_for_selector(&inventory, "active").unwrap(); + assert!(matches!(target, BrowserTarget::Shared { .. })); + } +} diff --git a/src/browser.rs b/src/browser.rs index 7b45aa8..e12ce54 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -14,6 +14,8 @@ EFFECT: Docker CLI process execution + temporary filesystem writes. INVARIANT: repeated ensure_browser_container(spec) reuses exactly spec.container_name. */ +mod assets; + use anyhow::{anyhow, Context, Result}; use std::fs; use std::net::{TcpStream, ToSocketAddrs}; @@ -21,7 +23,10 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use crate::{BrowserResourceLimits, BrowserSpec}; +use crate::{BrowserResourceLimits, BrowserSpec, BrowserTargetDisplaySpec}; +use assets::{ + BROWSER_DOCKERFILE, BROWSER_START_SCRIPT, NOVNC_PROXY_DOCKERFILE, NOVNC_PROXY_START_SCRIPT, +}; pub(crate) struct BrowserRuntime { pub container_name: String, @@ -29,64 +34,17 @@ pub(crate) struct BrowserRuntime { pub cdp_url: String, } +pub(crate) struct BrowserTargetDisplayRuntime { + pub container_name: String, + pub vnc_endpoint: String, + pub novnc_url: String, +} + pub(crate) struct BrowserStopRuntime { pub container_name: String, pub removed: bool, } -const BROWSER_DOCKERFILE: &str = r#"FROM kechangdev/browser-vnc:latest - -# bash/procps keep upstream startup scripts compatible; socat exposes a stable CDP port. -# xwd/imagemagick provide deterministic X11 framebuffer screenshots for noVNC/CDP proof. -RUN apk add --no-cache bash procps socat python3 net-tools curl xwd imagemagick - -# CHANGE: patch upstream noVNC/websockify for Python 3.12. -# WHY: old websockify calls array.array.fromstring(), removed in Python 3.12, which closes noVNC after the RFB protocol banner. -# QUOTE(ТЗ): "добиться что бы всё работало и этому были доказательства" -# REF: issue-347 -# SOURCE: n/a -# FORMAT THEOREM: websocket_rfb_handshake -> security_types_frame, not websockify_exception(fromstring) -# PURITY: SHELL -# EFFECT: Docker build mutates vendored websockify Python files in the browser image. -# INVARIANT: noVNC connects to the same X11/VNC framebuffer that Chromium renders into. -RUN python3 -c "from pathlib import Path; root=Path('/opt/noVNC/utils/websockify'); [p.write_text(p.read_text().replace('.fromstring(', '.frombytes(').replace('.tostring(', '.tobytes(')) for p in root.rglob('*.py')]" - -COPY docker-git-browser-start.sh /usr/local/bin/docker-git-browser-start.sh -RUN chmod +x /usr/local/bin/docker-git-browser-start.sh - -ENTRYPOINT ["/usr/local/bin/docker-git-browser-start.sh"] -"#; - -const BROWSER_START_SCRIPT: &str = r#"#!/usr/bin/env bash -set -euo pipefail - -rm -f /data/SingletonLock /data/SingletonCookie /data/SingletonSocket || true - -# CHANGE: force no-password shared VNC for automatic noVNC proof/control. -# WHY: docker-git's browser URL is opened by agents and users without a manual VNC password prompt. -# QUOTE(ТЗ): "автоматически для него поднимает noVNC что бы управлять единым браузером с агентом" -# REF: issue-347 -# SOURCE: n/a -# FORMAT THEOREM: start_browser -> noVNC autoconnect reaches Chromium framebuffer -# PURITY: SHELL -# EFFECT: rewrites upstream supervisor config before /start.sh starts supervisord. -# INVARIANT: x11vnc remains shared, so noVNC viewing does not disconnect the agent-controlled browser. -for supervisor_file in /etc/supervisor.d/*.ini /etc/supervisor/conf.d/*.conf; do - if [[ -f "$supervisor_file" ]]; then - sed -i \ - -e 's|-forever -usepw -display :99 -rfbport 5900|-forever -nopw -shared -display :99 -rfbport 5900|g' \ - -e 's|x11vnc -forever -usepw|x11vnc -forever -nopw -shared|g' \ - "$supervisor_file" - fi -done - -# kechangdev/browser-vnc binds Chromium CDP on 127.0.0.1:9222. MCP/Hermes use :9223. -# The proxy keeps Host checks stable and makes the endpoint reachable from the project namespace. -socat TCP-LISTEN:9223,fork,reuseaddr TCP:127.0.0.1:9222 & - -exec /start.sh -"#; - pub struct DockerBrowserShell; impl DockerBrowserShell { @@ -159,6 +117,44 @@ impl DockerBrowserShell { removed, }) } + + pub fn ensure_novnc_proxy_container( + &self, + spec: &BrowserTargetDisplaySpec, + ) -> Result { + ensure_docker_available()?; + ensure_novnc_proxy_image(spec)?; + + let state = inspect_container_state(&spec.container_name)?; + match state.as_deref() { + Some("running") if novnc_proxy_matches(spec)? => { + let novnc_url = wait_for_novnc_proxy(spec)?; + return Ok(BrowserTargetDisplayRuntime { + container_name: spec.container_name.clone(), + vnc_endpoint: spec.vnc_endpoint.clone(), + novnc_url, + }); + } + Some(_) => { + docker(["rm", "-f", &spec.container_name], "docker rm noVNC proxy")?; + } + None => {} + } + + let mut runtime_spec = spec.clone(); + runtime_spec.network_mode = effective_network_mode( + &spec.network_mode, + referenced_container_state(&spec.network_mode)?.as_deref(), + ); + run_novnc_proxy_container(&runtime_spec)?; + let novnc_url = wait_for_novnc_proxy(&runtime_spec)?; + + Ok(BrowserTargetDisplayRuntime { + container_name: runtime_spec.container_name, + vnc_endpoint: runtime_spec.vnc_endpoint, + novnc_url, + }) + } } fn docker(args: [&str; N], label: &str) -> Result { @@ -316,6 +312,41 @@ fn inspect_container_network_mode(container_name: &str) -> Result } } +fn inspect_container_label(container_name: &str, label: &str) -> Result> { + let output = docker_command() + .args([ + "inspect", + "-f", + &format!("{{{{ index .Config.Labels \"{label}\" }}}}"), + container_name, + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .output() + .with_context(|| { + format!("failed to inspect container label {label} for {container_name}") + })?; + + if !output.status.success() { + return Ok(None); + } + + let value = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if value.is_empty() || value == "" { + Ok(None) + } else { + Ok(Some(value)) + } +} + +fn novnc_proxy_matches(spec: &BrowserTargetDisplaySpec) -> Result { + Ok( + inspect_container_label(&spec.container_name, "docker-git.browser-vnc-endpoint")? + .as_deref() + == Some(spec.vnc_endpoint.as_str()), + ) +} + // CHANGE: avoid `docker run --network container:` hard failure by falling back to bridge. // WHY: MCP stdio startup must work when launched before/without a docker-git project container. // QUOTE(ТЗ): "добить задачу ... поднятие MCP Playright вместе с noVNC" @@ -374,6 +405,26 @@ fn ensure_browser_image(spec: &BrowserSpec) -> Result<()> { Ok(()) } +fn ensure_novnc_proxy_image(spec: &BrowserTargetDisplaySpec) -> Result<()> { + if image_exists(&spec.image_name)? { + return Ok(()); + } + + let context = NovncProxyBuildContext::create()?; + docker( + [ + "build", + "-t", + &spec.image_name, + "-f", + context.dockerfile_path_str(), + context.path_str(), + ], + "docker build noVNC proxy image", + )?; + Ok(()) +} + fn ensure_volume(volume_name: &str) -> Result<()> { docker(["volume", "create", volume_name], "docker volume create").map(|_| ()) } @@ -436,6 +487,42 @@ fn run_browser_container(spec: &BrowserSpec, limits: &BrowserResourceLimits) -> docker_dynamic(&args, "docker run browser").map(|_| ()) } +fn run_novnc_proxy_container(spec: &BrowserTargetDisplaySpec) -> Result<()> { + let mut args = vec![ + "run".to_string(), + "-d".to_string(), + "--name".to_string(), + spec.container_name.clone(), + "--label".to_string(), + "docker-git.browser-novnc-proxy=1".to_string(), + "--label".to_string(), + format!("docker-git.browser-target={}", spec.browser_name), + "--label".to_string(), + format!("docker-git.browser-vnc-endpoint={}", spec.vnc_endpoint), + "--network".to_string(), + spec.network_mode.clone(), + ]; + + if should_publish_ports(&spec.network_mode) { + args.extend([ + "--add-host".to_string(), + "host.docker.internal:host-gateway".to_string(), + "-p".to_string(), + format!("127.0.0.1:{}:{}", spec.novnc_port, spec.novnc_port), + ]); + } + + args.extend([ + "-e".to_string(), + format!("BROWSER_CONNECTION_VNC_ENDPOINT={}", spec.vnc_endpoint), + "-e".to_string(), + format!("BROWSER_CONNECTION_NOVNC_PORT={}", spec.novnc_port), + spec.image_name.clone(), + ]); + + docker_dynamic(&args, "docker run noVNC proxy").map(|_| ()) +} + fn cdp_probe_candidates(spec: &BrowserSpec) -> Vec { let mut candidates = if should_publish_ports(&spec.network_mode) { vec![format!("http://127.0.0.1:{}/json/version", spec.ports.cdp)] @@ -499,6 +586,30 @@ fn novnc_probe_candidates(spec: &BrowserSpec) -> Vec { candidates } +fn novnc_proxy_probe_candidates(spec: &BrowserTargetDisplaySpec) -> Vec { + let mut candidates = vec![crate::render_novnc_url_for_port(spec.novnc_port)]; + + if let Some(container_name) = spec.network_mode.strip_prefix("container:") { + if let Ok(Some(ip)) = inspect_container_ip(container_name) { + candidates.push(format!( + "http://{}:{}/vnc.html?autoconnect=true&resize=remote&path=websockify", + ip, spec.novnc_port + )); + } + } + + if let Ok(Some(ip)) = inspect_container_ip(&spec.container_name) { + candidates.push(format!( + "http://{}:{}/vnc.html?autoconnect=true&resize=remote&path=websockify", + ip, spec.novnc_port + )); + } + + candidates.sort(); + candidates.dedup(); + candidates +} + fn runtime_urls(spec: &BrowserSpec) -> Result<(String, String)> { let cdp_url = wait_for_cdp(spec)?; let novnc_url = wait_for_novnc(spec)?; @@ -574,6 +685,29 @@ fn wait_for_novnc(spec: &BrowserSpec) -> Result { )) } +fn wait_for_novnc_proxy(spec: &BrowserTargetDisplaySpec) -> Result { + ensure_curl_available()?; + let mut last_candidates = Vec::new(); + for _ in 0..30 { + last_candidates = novnc_proxy_probe_candidates(spec); + for url in &last_candidates { + let status = Command::new("curl") + .args(["-sSf", "--connect-timeout", "2", "--max-time", "5", url]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + if matches!(status, Ok(exit) if exit.success()) { + return Ok(url.to_string()); + } + } + std::thread::sleep(std::time::Duration::from_secs(1)); + } + Err(anyhow!( + "browser target noVNC proxy did not become ready; tried: {}", + last_candidates.join(", ") + )) +} + // CHANGE: fail fast when the host shell lacks curl for CDP readiness checks. // WHY: otherwise a missing binary is indistinguishable from a slow browser and produces a misleading timeout. // QUOTE(ТЗ): "добиться что бы всё работало и этому были доказательства" @@ -665,76 +799,50 @@ impl Drop for BrowserBuildContext { } } -fn path_to_str(path: &Path) -> &str { - path.to_str() - .expect("temporary Docker build path must be valid UTF-8") +struct NovncProxyBuildContext { + path: PathBuf, + dockerfile: PathBuf, } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn missing_project_container_falls_back_to_bridge_network() { - assert_eq!( - effective_network_mode("container:dg-missing", None), - "bridge" - ); - assert_eq!( - effective_network_mode("container:dg-project", Some("running")), - "container:dg-project" - ); - assert_eq!(effective_network_mode("bridge", None), "bridge"); - } - - #[test] - fn browser_resource_limit_args_are_omitted_when_limits_are_empty() { - assert!(browser_resource_limit_args(&BrowserResourceLimits::none()).is_empty()); - } - - #[test] - fn browser_resource_limit_args_render_docker_run_limits() { - assert_eq!( - browser_resource_limit_args(&BrowserResourceLimits::from_values( - Some("0.5"), - Some("1g") - )), - vec![ - "--cpus".to_string(), - "0.5".to_string(), - "--memory".to_string(), - "1g".to_string() - ] - ); +impl NovncProxyBuildContext { + fn create() -> Result { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .context("system clock before unix epoch")? + .as_nanos(); + let path = std::env::temp_dir().join(format!("docker-git-novnc-proxy-build-{nonce}")); + fs::create_dir_all(&path) + .with_context(|| format!("failed to create {}", path.display()))?; + let dockerfile = path.join("Dockerfile.novnc-proxy"); + fs::write(&dockerfile, NOVNC_PROXY_DOCKERFILE) + .context("failed to write noVNC proxy Dockerfile")?; + fs::write( + path.join("docker-git-novnc-proxy-start.sh"), + NOVNC_PROXY_START_SCRIPT, + ) + .context("failed to write noVNC proxy start script")?; + Ok(Self { path, dockerfile }) } - #[test] - fn docker_host_autodetect_keeps_explicit_env_and_project_env_precedence() { - assert_eq!( - selected_docker_host_override( - Some("tcp://explicit.example:2375"), - Some("tcp://project.example:2375"), - false, - true, - ), - None - ); - assert_eq!( - selected_docker_host_override(None, Some("tcp://project.example:2375"), false, true), - Some("tcp://project.example:2375".to_string()) - ); + fn path_str(&self) -> &str { + path_to_str(&self.path) } - #[test] - fn docker_host_autodetect_falls_back_to_host_docker_internal_when_socket_missing() { - assert_eq!( - selected_docker_host_override(None, None, false, true), - Some("tcp://host.docker.internal:2375".to_string()) - ); - assert_eq!(selected_docker_host_override(None, None, true, true), None); - assert_eq!( - selected_docker_host_override(None, None, false, false), - None - ); + fn dockerfile_path_str(&self) -> &str { + path_to_str(&self.dockerfile) + } +} + +impl Drop for NovncProxyBuildContext { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); } } + +fn path_to_str(path: &Path) -> &str { + path.to_str() + .expect("temporary Docker build path must be valid UTF-8") +} + +#[cfg(test)] +mod tests; diff --git a/src/browser/assets.rs b/src/browser/assets.rs new file mode 100644 index 0000000..6c9eb87 --- /dev/null +++ b/src/browser/assets.rs @@ -0,0 +1,71 @@ +pub(super) const BROWSER_DOCKERFILE: &str = r#"FROM kechangdev/browser-vnc:latest + +# bash/procps keep upstream startup scripts compatible; socat exposes a stable CDP port. +# xwd/imagemagick provide deterministic X11 framebuffer screenshots for noVNC/CDP proof. +RUN apk add --no-cache bash procps socat python3 net-tools curl xwd imagemagick + +RUN python3 -c "from pathlib import Path; root=Path('/opt/noVNC/utils/websockify'); [p.write_text(p.read_text().replace('.fromstring(', '.frombytes(').replace('.tostring(', '.tobytes(')) for p in root.rglob('*.py')]" + +COPY docker-git-browser-start.sh /usr/local/bin/docker-git-browser-start.sh +RUN chmod +x /usr/local/bin/docker-git-browser-start.sh + +ENTRYPOINT ["/usr/local/bin/docker-git-browser-start.sh"] +"#; + +pub(super) const BROWSER_START_SCRIPT: &str = r#"#!/usr/bin/env bash +set -euo pipefail + +rm -f /data/SingletonLock /data/SingletonCookie /data/SingletonSocket || true + +for supervisor_file in /etc/supervisor.d/*.ini /etc/supervisor/conf.d/*.conf; do + if [[ -f "$supervisor_file" ]]; then + sed -i \ + -e 's|-forever -usepw -display :99 -rfbport 5900|-forever -nopw -shared -display :99 -rfbport 5900|g' \ + -e 's|x11vnc -forever -usepw|x11vnc -forever -nopw -shared|g' \ + "$supervisor_file" + fi +done + +socat TCP-LISTEN:9223,fork,reuseaddr TCP:127.0.0.1:9222 & + +exec /start.sh +"#; + +pub(super) const NOVNC_PROXY_DOCKERFILE: &str = r#"FROM kechangdev/browser-vnc:latest + +RUN apk add --no-cache bash curl python3 + +RUN python3 -c "from pathlib import Path; root=Path('/opt/noVNC/utils/websockify'); [p.write_text(p.read_text().replace('.fromstring(', '.frombytes(').replace('.tostring(', '.tobytes(')) for p in root.rglob('*.py')]" + +COPY docker-git-novnc-proxy-start.sh /usr/local/bin/docker-git-novnc-proxy-start.sh +RUN chmod +x /usr/local/bin/docker-git-novnc-proxy-start.sh + +ENTRYPOINT ["/usr/local/bin/docker-git-novnc-proxy-start.sh"] +"#; + +pub(super) const NOVNC_PROXY_START_SCRIPT: &str = r#"#!/usr/bin/env bash +set -euo pipefail + +target="${BROWSER_CONNECTION_VNC_ENDPOINT:?BROWSER_CONNECTION_VNC_ENDPOINT is required}" +listen_port="${BROWSER_CONNECTION_NOVNC_PORT:-6080}" +web_root="${BROWSER_CONNECTION_NOVNC_WEB:-/usr/share/novnc}" + +if [[ ! -d "$web_root" && -d /usr/share/noVNC ]]; then + web_root=/usr/share/noVNC +fi +if [[ ! -d "$web_root" && -d /usr/share/webapps/novnc ]]; then + web_root=/usr/share/webapps/novnc +fi + +if [[ -x /opt/noVNC/utils/novnc_proxy ]]; then + exec /opt/noVNC/utils/novnc_proxy \ + --listen "$listen_port" \ + --vnc "$target" +fi + +if command -v websockify >/dev/null 2>&1; then + exec websockify --web "$web_root" "0.0.0.0:${listen_port}" "$target" +fi + +exec python3 -m websockify --web "$web_root" "0.0.0.0:${listen_port}" "$target" +"#; diff --git a/src/browser/tests.rs b/src/browser/tests.rs new file mode 100644 index 0000000..74ad712 --- /dev/null +++ b/src/browser/tests.rs @@ -0,0 +1,81 @@ +use super::*; + +#[test] +fn missing_project_container_falls_back_to_bridge_network() { + assert_eq!( + effective_network_mode("container:dg-missing", None), + "bridge" + ); + assert_eq!( + effective_network_mode("container:dg-project", Some("running")), + "container:dg-project" + ); + assert_eq!(effective_network_mode("bridge", None), "bridge"); +} + +#[test] +fn browser_resource_limit_args_are_omitted_when_limits_are_empty() { + assert!(browser_resource_limit_args(&BrowserResourceLimits::none()).is_empty()); +} + +#[test] +fn browser_resource_limit_args_render_docker_run_limits() { + assert_eq!( + browser_resource_limit_args(&BrowserResourceLimits::from_values(Some("0.5"), Some("1g"))), + vec![ + "--cpus".to_string(), + "0.5".to_string(), + "--memory".to_string(), + "1g".to_string() + ] + ); +} + +#[test] +fn novnc_proxy_candidates_include_target_specific_localhost_port() { + let spec = BrowserTargetDisplaySpec { + project_id: "dg-test".to_string(), + browser_name: "personal".to_string(), + main_container_name: "dg-test".to_string(), + container_name: "dg-test-browser-novnc-personal".to_string(), + image_name: "dg-test-browser-novnc-proxy:docker-git-browser".to_string(), + network_mode: "bridge".to_string(), + vnc_endpoint: "host.docker.internal:5900".to_string(), + novnc_port: 6611, + }; + + assert!(novnc_proxy_probe_candidates(&spec).contains( + &"http://127.0.0.1:6611/vnc.html?autoconnect=true&resize=remote&path=websockify" + .to_string() + )); +} + +#[test] +fn docker_host_autodetect_keeps_explicit_env_and_project_env_precedence() { + assert_eq!( + selected_docker_host_override( + Some("tcp://explicit.example:2375"), + Some("tcp://project.example:2375"), + false, + true, + ), + None + ); + assert_eq!( + selected_docker_host_override(None, Some("tcp://project.example:2375"), false, true), + Some("tcp://project.example:2375".to_string()) + ); +} + +#[test] +fn docker_host_autodetect_falls_back_to_host_docker_internal_when_socket_missing() { + assert_eq!( + selected_docker_host_override(None, None, false, true), + Some("tcp://host.docker.internal:2375".to_string()) + ); + assert_eq!(selected_docker_host_override(None, None, true, true), None); + assert_eq!( + selected_docker_host_override(None, None, false, false), + None + ); +} diff --git a/src/browser_actions.rs b/src/browser_actions.rs new file mode 100644 index 0000000..871b9c9 --- /dev/null +++ b/src/browser_actions.rs @@ -0,0 +1,207 @@ +use crate::cdp::CdpClient; +use crate::shared_browser::SharedBrowserClient; +use anyhow::{anyhow, Context, Result}; +use serde_json::{json, Value}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BrowserTarget { + Cdp { endpoint: String }, + Shared { share_url: String }, +} + +impl BrowserTarget { + pub fn cdp(endpoint: impl Into) -> Self { + Self::Cdp { + endpoint: endpoint.into(), + } + } + + pub fn shared(share_url: impl Into) -> Self { + Self::Shared { + share_url: share_url.into(), + } + } + + pub fn kind(&self) -> &'static str { + match self { + Self::Cdp { .. } => "cdp", + Self::Shared { .. } => "shared-extension", + } + } + + pub fn safe_label(&self) -> String { + match self { + Self::Cdp { endpoint } => format!("cdp:{endpoint}"), + Self::Shared { share_url } => { + let redacted = share_url + .split_once("#agent=") + .map(|(base, _)| format!("{base}#agent=")) + .unwrap_or_else(|| "".to_string()); + format!("shared:{redacted}") + } + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BrowserCommand { + Navigate { url: String }, + Snapshot, + Evaluate { expression: String }, + Click { selector: String }, + TypeText { selector: String, text: String }, + PressKey { key: String }, + Screenshot { full_page: bool }, + ListTabs, + ActivateTab { tab_id: i64 }, +} + +impl BrowserCommand { + pub fn tool_name(&self) -> &'static str { + match self { + Self::Navigate { .. } => "browser_navigate", + Self::Snapshot => "browser_snapshot", + Self::Evaluate { .. } => "browser_evaluate", + Self::Click { .. } => "browser_click", + Self::TypeText { .. } => "browser_type", + Self::PressKey { .. } => "browser_press_key", + Self::Screenshot { .. } => "browser_take_screenshot", + Self::ListTabs => "browser_list_tabs", + Self::ActivateTab { .. } => "browser_activate_tab", + } + } +} + +pub fn command_from_browser_tool(name: &str, arguments: &Value) -> Result { + match name { + "browser_navigate" => Ok(BrowserCommand::Navigate { + url: required_str(arguments, "url")?.to_string(), + }), + "browser_snapshot" => Ok(BrowserCommand::Snapshot), + "browser_evaluate" => Ok(BrowserCommand::Evaluate { + expression: required_str(arguments, "expression")?.to_string(), + }), + "browser_click" => Ok(BrowserCommand::Click { + selector: required_str(arguments, "selector")?.to_string(), + }), + "browser_type" => Ok(BrowserCommand::TypeText { + selector: required_str(arguments, "selector")?.to_string(), + text: required_str(arguments, "text")?.to_string(), + }), + "browser_press_key" => Ok(BrowserCommand::PressKey { + key: required_str(arguments, "key")?.to_string(), + }), + "browser_take_screenshot" => Ok(BrowserCommand::Screenshot { + full_page: arguments + .get("full_page") + .and_then(Value::as_bool) + .unwrap_or(true), + }), + "browser_list_tabs" => Ok(BrowserCommand::ListTabs), + "browser_activate_tab" => Ok(BrowserCommand::ActivateTab { + tab_id: required_i64(arguments, "tab_id")?, + }), + "" => Err(anyhow!("tools/call params.name is required")), + _ => Err(anyhow!("Unknown browser-connection tool: {name}")), + } +} + +pub fn dispatch_browser_command( + target: &BrowserTarget, + command: &BrowserCommand, +) -> Result { + match target { + BrowserTarget::Cdp { endpoint } => dispatch_cdp_tool(endpoint, command), + BrowserTarget::Shared { share_url } => dispatch_shared_tool(share_url, command), + } +} + +fn dispatch_cdp_tool(cdp_endpoint: &str, command: &BrowserCommand) -> Result { + let client = CdpClient::new(cdp_endpoint); + match command { + BrowserCommand::Navigate { url } => client.navigate(url), + BrowserCommand::Snapshot => client.snapshot(), + BrowserCommand::Evaluate { expression } => client.evaluate(expression), + BrowserCommand::Click { selector } => client.click(selector), + BrowserCommand::TypeText { selector, text } => client.type_text(selector, text), + BrowserCommand::PressKey { key } => client.press_key(key), + BrowserCommand::Screenshot { full_page } => client.screenshot(*full_page), + BrowserCommand::ListTabs | BrowserCommand::ActivateTab { .. } => Err(anyhow!( + "{} is only available for shared-extension browsers", + command.tool_name() + )), + } +} + +fn dispatch_shared_tool(share_url: &str, command: &BrowserCommand) -> Result { + let client = SharedBrowserClient::new(share_url); + match command { + BrowserCommand::Navigate { url } => client.navigate(url), + BrowserCommand::Snapshot => client.snapshot(), + BrowserCommand::Evaluate { expression } => client.evaluate(expression), + BrowserCommand::Click { selector } => client.click(selector), + BrowserCommand::TypeText { selector, text } => client.type_text(selector, text), + BrowserCommand::PressKey { key } => client.press_key(key), + BrowserCommand::Screenshot { full_page } => client.screenshot(*full_page), + BrowserCommand::ListTabs => serde_json::to_string_pretty(&client.list_tabs()?) + .context("failed to render shared browser tabs"), + BrowserCommand::ActivateTab { tab_id } => client.activate_tab(*tab_id), + } +} + +fn required_str<'a>(arguments: &'a Value, name: &str) -> Result<&'a str> { + arguments + .get(name) + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| anyhow!("argument `{name}` is required")) +} + +fn required_i64(arguments: &Value, name: &str) -> Result { + arguments + .get(name) + .and_then(Value::as_i64) + .ok_or_else(|| anyhow!("argument `{name}` is required")) +} + +pub fn command_result_json(command: &BrowserCommand, text: &str) -> Value { + serde_json::from_str::(text).unwrap_or_else(|_| { + json!({ + "tool": command.tool_name(), + "text": text + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_screenshot_tool_defaulting_to_full_page() { + let command = command_from_browser_tool("browser_take_screenshot", &json!({})).unwrap(); + assert_eq!(command, BrowserCommand::Screenshot { full_page: true }); + } + + #[test] + fn rejects_shared_only_commands_for_cdp_without_network() { + let result = dispatch_browser_command( + &BrowserTarget::cdp("http://127.0.0.1:1"), + &BrowserCommand::ListTabs, + ); + assert!(result + .unwrap_err() + .to_string() + .contains("shared-extension browsers")); + } + + #[test] + fn redacts_shared_agent_token_in_safe_label() { + let target = BrowserTarget::shared("https://relay.example/share/s1#agent=secret"); + assert_eq!( + target.safe_label(), + "shared:https://relay.example/share/s1#agent=" + ); + } +} diff --git a/src/browser_target.rs b/src/browser_target.rs new file mode 100644 index 0000000..2ace5d0 --- /dev/null +++ b/src/browser_target.rs @@ -0,0 +1,565 @@ +use anyhow::{anyhow, Result}; +use serde::{Deserialize, Serialize}; +use std::env; + +pub const MANAGED_BROWSER_NAME: &str = "managed"; +pub const EXPLICIT_BROWSER_NAME: &str = "explicit"; +pub const PERSONAL_BROWSER_NAME: &str = "personal"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NamedBrowserEndpoint { + pub name: String, + pub cdp_endpoint: String, + pub vnc_endpoint: Option, + pub novnc_url: Option, + pub share_url: Option, +} + +impl NamedBrowserEndpoint { + pub fn new(name: impl AsRef, cdp_endpoint: impl AsRef) -> Result { + let name = normalize_configured_browser_name(name.as_ref())?; + let cdp_endpoint = normalize_cdp_endpoint(cdp_endpoint.as_ref())?; + Ok(Self { + name, + cdp_endpoint, + vnc_endpoint: None, + novnc_url: None, + share_url: None, + }) + } + + pub fn shared(name: impl AsRef, share_url: impl AsRef) -> Result { + let name = normalize_configured_browser_name(name.as_ref())?; + let share_url = normalize_share_url(share_url.as_ref())?; + Ok(Self { + name, + cdp_endpoint: String::new(), + vnc_endpoint: None, + novnc_url: None, + share_url: Some(share_url), + }) + } + + pub fn with_vnc_endpoint(mut self, vnc_endpoint: impl AsRef) -> Result { + self.vnc_endpoint = Some(normalize_vnc_endpoint(vnc_endpoint.as_ref())?); + Ok(self) + } + + pub fn with_novnc_url(mut self, novnc_url: impl AsRef) -> Result { + self.novnc_url = Some(normalize_novnc_url(novnc_url.as_ref())?); + Ok(self) + } + + pub fn with_share_url(mut self, share_url: impl AsRef) -> Result { + self.share_url = Some(normalize_share_url(share_url.as_ref())?); + Ok(self) + } +} + +pub fn parse_named_browser_endpoint(value: &str) -> Result { + let (name, endpoint) = value + .split_once('=') + .ok_or_else(|| anyhow!("browser endpoint must use NAME=CDP_ENDPOINT format"))?; + NamedBrowserEndpoint::new(name, endpoint) +} + +pub fn parse_named_browser_endpoints(value: &str) -> Result> { + value + .split([',', ';']) + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(parse_named_browser_endpoint) + .collect() +} + +pub fn parse_named_browser_vnc_endpoint(value: &str) -> Result<(String, String)> { + let (name, endpoint) = value + .split_once('=') + .ok_or_else(|| anyhow!("browser VNC endpoint must use NAME=HOST:PORT format"))?; + Ok(( + normalize_configured_browser_name(name)?, + normalize_vnc_endpoint(endpoint)?, + )) +} + +pub fn parse_named_browser_vnc_endpoints(value: &str) -> Result> { + value + .split([',', ';']) + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(parse_named_browser_vnc_endpoint) + .collect() +} + +pub fn parse_named_browser_novnc_url(value: &str) -> Result<(String, String)> { + let (name, url) = value + .split_once('=') + .ok_or_else(|| anyhow!("browser noVNC URL must use NAME=URL format"))?; + Ok(( + normalize_configured_browser_name(name)?, + normalize_novnc_url(url)?, + )) +} + +pub fn parse_named_browser_novnc_urls(value: &str) -> Result> { + value + .split([',', ';']) + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(parse_named_browser_novnc_url) + .collect() +} + +pub fn parse_named_browser_share_url(value: &str) -> Result<(String, String)> { + let (name, url) = value + .split_once('=') + .ok_or_else(|| anyhow!("browser share URL must use NAME=URL format"))?; + Ok(( + normalize_configured_browser_name(name)?, + normalize_share_url(url)?, + )) +} + +pub fn parse_named_browser_share_urls(value: &str) -> Result> { + value + .split([',', ';']) + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(parse_named_browser_share_url) + .collect() +} + +pub fn browser_endpoints_from_env() -> Result> { + let mut endpoints = Vec::new(); + + if let Some(value) = nonempty_env("BROWSER_CONNECTION_BROWSERS") { + endpoints.extend(parse_named_browser_endpoints(&value)?); + } + + if let Some(endpoint) = nonempty_env("BROWSER_CONNECTION_PERSONAL_CDP_ENDPOINT") { + endpoints.push(NamedBrowserEndpoint::new(PERSONAL_BROWSER_NAME, endpoint)?); + } + + if let Some(value) = nonempty_env("BROWSER_CONNECTION_BROWSER_VNCS") { + for (name, endpoint) in parse_named_browser_vnc_endpoints(&value)? { + upsert_browser_vnc_endpoint(&mut endpoints, name, endpoint); + } + } + + if let Some(endpoint) = nonempty_env("BROWSER_CONNECTION_PERSONAL_VNC_ENDPOINT") { + upsert_browser_vnc_endpoint( + &mut endpoints, + PERSONAL_BROWSER_NAME.to_string(), + normalize_vnc_endpoint(&endpoint)?, + ); + } + + if let Some(value) = nonempty_env("BROWSER_CONNECTION_BROWSER_NOVNC_URLS") { + for (name, url) in parse_named_browser_novnc_urls(&value)? { + upsert_browser_novnc_url(&mut endpoints, name, url); + } + } + + if let Some(url) = nonempty_env("BROWSER_CONNECTION_PERSONAL_NOVNC_URL") { + upsert_browser_novnc_url( + &mut endpoints, + PERSONAL_BROWSER_NAME.to_string(), + normalize_novnc_url(&url)?, + ); + } + + if let Some(value) = nonempty_env("BROWSER_CONNECTION_BROWSER_SHARES") { + for (name, url) in parse_named_browser_share_urls(&value)? { + upsert_browser_share_url(&mut endpoints, name, url); + } + } + + Ok(endpoints) +} + +pub fn active_browser_from_env() -> Option { + nonempty_env("BROWSER_CONNECTION_ACTIVE_BROWSER") +} + +pub(crate) fn configured_browser_kind(name: &str) -> &'static str { + if name == PERSONAL_BROWSER_NAME { + "personal" + } else { + "external" + } +} + +pub(crate) fn normalize_browser_name(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(anyhow!("browser name must not be empty")); + } + if !name + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')) + { + return Err(anyhow!( + "browser name `{name}` may only contain ASCII letters, digits, '.', '_' or '-'" + )); + } + Ok(name.to_string()) +} + +pub(crate) fn normalize_cdp_endpoint(endpoint: &str) -> Result { + let endpoint = endpoint.trim().trim_end_matches('/'); + if endpoint.is_empty() { + return Err(anyhow!("CDP endpoint must not be empty")); + } + let endpoint = endpoint + .strip_suffix("/json/version") + .or_else(|| endpoint.strip_suffix("/json/list")) + .unwrap_or(endpoint) + .trim_end_matches('/'); + if !(endpoint.starts_with("http://") || endpoint.starts_with("https://")) { + return Err(anyhow!( + "CDP endpoint `{endpoint}` must start with http:// or https://" + )); + } + Ok(endpoint.to_string()) +} + +pub(crate) fn normalize_vnc_endpoint(endpoint: &str) -> Result { + let endpoint = endpoint.trim().trim_end_matches('/'); + if endpoint.is_empty() { + return Err(anyhow!("VNC endpoint must not be empty")); + } + if endpoint.starts_with("http://") + || endpoint.starts_with("https://") + || endpoint.starts_with("ws://") + || endpoint.starts_with("wss://") + { + return Err(anyhow!( + "VNC endpoint `{endpoint}` must use HOST:PORT, not a URL" + )); + } + let Some((host, port)) = endpoint.rsplit_once(':') else { + return Err(anyhow!("VNC endpoint `{endpoint}` must use HOST:PORT")); + }; + let host = host.trim().trim_matches(['[', ']']); + let port = port + .trim() + .parse::() + .map_err(|_| anyhow!("VNC endpoint `{endpoint}` must end with a valid TCP port"))?; + if host.is_empty() { + return Err(anyhow!("VNC endpoint `{endpoint}` must include a host")); + } + Ok(format!("{host}:{port}")) +} + +pub(crate) fn normalize_novnc_url(url: &str) -> Result { + let url = url.trim().trim_end_matches('/'); + if url.is_empty() { + return Err(anyhow!("noVNC URL must not be empty")); + } + if !(url.starts_with("http://") || url.starts_with("https://")) { + return Err(anyhow!( + "noVNC URL `{url}` must start with http:// or https://" + )); + } + Ok(url.to_string()) +} + +pub(crate) fn normalize_share_url(url: &str) -> Result { + let url = url.trim(); + if url.is_empty() { + return Err(anyhow!("browser share URL must not be empty")); + } + if !(url.starts_with("http://") + || url.starts_with("https://") + || url.starts_with("ws://") + || url.starts_with("wss://")) + { + return Err(anyhow!( + "browser share URL `{url}` must start with http://, https://, ws:// or wss://" + )); + } + Ok(url.to_string()) +} + +pub(crate) fn upsert_browser_endpoint( + endpoints: &mut Vec, + endpoint: NamedBrowserEndpoint, +) { + if let Some(existing) = endpoints + .iter_mut() + .find(|existing| existing.name == endpoint.name) + { + let vnc_endpoint = existing.vnc_endpoint.clone(); + let novnc_url = existing.novnc_url.clone(); + let share_url = existing.share_url.clone(); + *existing = endpoint; + if existing.vnc_endpoint.is_none() { + existing.vnc_endpoint = vnc_endpoint; + } + if existing.novnc_url.is_none() { + existing.novnc_url = novnc_url; + } + if existing.share_url.is_none() { + existing.share_url = share_url; + } + } else { + endpoints.push(endpoint); + } +} + +pub(crate) fn upsert_browser_vnc_endpoint( + endpoints: &mut Vec, + name: String, + vnc_endpoint: String, +) { + if let Some(existing) = endpoints.iter_mut().find(|existing| existing.name == name) { + existing.vnc_endpoint = Some(vnc_endpoint); + } else { + endpoints.push(NamedBrowserEndpoint { + name, + cdp_endpoint: String::new(), + vnc_endpoint: Some(vnc_endpoint), + novnc_url: None, + share_url: None, + }); + } +} + +pub(crate) fn upsert_browser_novnc_url( + endpoints: &mut Vec, + name: String, + novnc_url: String, +) { + if let Some(existing) = endpoints.iter_mut().find(|existing| existing.name == name) { + existing.novnc_url = Some(novnc_url); + } else { + endpoints.push(NamedBrowserEndpoint { + name, + cdp_endpoint: String::new(), + vnc_endpoint: None, + novnc_url: Some(novnc_url), + share_url: None, + }); + } +} + +pub(crate) fn upsert_browser_share_url( + endpoints: &mut Vec, + name: String, + share_url: String, +) { + if let Some(existing) = endpoints.iter_mut().find(|existing| existing.name == name) { + existing.share_url = Some(share_url); + } else { + endpoints.push(NamedBrowserEndpoint { + name, + cdp_endpoint: String::new(), + vnc_endpoint: None, + novnc_url: None, + share_url: Some(share_url), + }); + } +} + +fn normalize_configured_browser_name(name: &str) -> Result { + let name = normalize_browser_name(name)?; + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Err(anyhow!( + "`{name}` is reserved and cannot name a configured browser" + )); + } + Ok(name) +} + +fn nonempty_env(name: &str) -> Option { + env::var(name) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_named_personal_browser_endpoint() { + let endpoint = parse_named_browser_endpoint("personal=http://127.0.0.1:9222/json/version") + .expect("personal endpoint parses"); + + assert_eq!(endpoint.name, PERSONAL_BROWSER_NAME); + assert_eq!(endpoint.cdp_endpoint, "http://127.0.0.1:9222"); + assert_eq!(endpoint.vnc_endpoint, None); + assert_eq!(endpoint.novnc_url, None); + assert_eq!(endpoint.share_url, None); + } + + #[test] + fn parses_named_vnc_endpoint() { + let (name, endpoint) = + parse_named_browser_vnc_endpoint("personal=host.docker.internal:5900") + .expect("vnc endpoint parses"); + + assert_eq!(name, PERSONAL_BROWSER_NAME); + assert_eq!(endpoint, "host.docker.internal:5900"); + } + + #[test] + fn rejects_url_as_vnc_endpoint() { + let error = parse_named_browser_vnc_endpoint("personal=http://127.0.0.1:5900") + .expect_err("VNC endpoint is not an HTTP URL"); + + assert!(error.to_string().contains("HOST:PORT")); + } + + #[test] + fn parses_named_novnc_url() { + let (name, url) = parse_named_browser_novnc_url("personal=http://127.0.0.1:6680/vnc.html") + .expect("noVNC URL parses"); + + assert_eq!(name, PERSONAL_BROWSER_NAME); + assert_eq!(url, "http://127.0.0.1:6680/vnc.html"); + } + + #[test] + fn parses_named_share_url() { + let (name, url) = + parse_named_browser_share_url("edge=https://relay.example/share/s1#agent=a1") + .expect("share URL parses"); + + assert_eq!(name, "edge"); + assert_eq!(url, "https://relay.example/share/s1#agent=a1"); + } + + #[test] + fn rejects_novnc_url_without_http_scheme() { + let error = parse_named_browser_novnc_url("personal=127.0.0.1:6680/vnc.html") + .expect_err("noVNC URL requires a URL scheme"); + + assert!(error + .to_string() + .contains("must start with http:// or https://")); + } + + #[test] + fn upserting_cdp_preserves_display_metadata() { + let mut endpoints = + vec![ + NamedBrowserEndpoint::new(PERSONAL_BROWSER_NAME, "http://127.0.0.1:9222") + .expect("endpoint is valid") + .with_vnc_endpoint("host.docker.internal:5900") + .expect("vnc endpoint is valid") + .with_share_url("https://relay.example/share/s1#agent=a1") + .expect("share URL is valid"), + ]; + + upsert_browser_endpoint( + &mut endpoints, + NamedBrowserEndpoint::new(PERSONAL_BROWSER_NAME, "http://127.0.0.1:9333") + .expect("endpoint is valid"), + ); + + assert_eq!(endpoints[0].cdp_endpoint, "http://127.0.0.1:9333"); + assert_eq!( + endpoints[0].vnc_endpoint.as_deref(), + Some("host.docker.internal:5900") + ); + assert_eq!( + endpoints[0].share_url.as_deref(), + Some("https://relay.example/share/s1#agent=a1") + ); + } + + #[test] + fn rejects_reserved_configured_browser_names() { + let error = NamedBrowserEndpoint::new(MANAGED_BROWSER_NAME, "http://127.0.0.1:9222") + .expect_err("managed is reserved"); + + assert!(error.to_string().contains("reserved")); + } + + #[test] + fn env_configuration_merges_personal_cdp_vnc_and_novnc() { + let saved = [ + ( + "BROWSER_CONNECTION_PERSONAL_CDP_ENDPOINT", + env::var("BROWSER_CONNECTION_PERSONAL_CDP_ENDPOINT").ok(), + ), + ( + "BROWSER_CONNECTION_PERSONAL_VNC_ENDPOINT", + env::var("BROWSER_CONNECTION_PERSONAL_VNC_ENDPOINT").ok(), + ), + ( + "BROWSER_CONNECTION_PERSONAL_NOVNC_URL", + env::var("BROWSER_CONNECTION_PERSONAL_NOVNC_URL").ok(), + ), + ( + "BROWSER_CONNECTION_BROWSERS", + env::var("BROWSER_CONNECTION_BROWSERS").ok(), + ), + ( + "BROWSER_CONNECTION_BROWSER_VNCS", + env::var("BROWSER_CONNECTION_BROWSER_VNCS").ok(), + ), + ( + "BROWSER_CONNECTION_BROWSER_NOVNC_URLS", + env::var("BROWSER_CONNECTION_BROWSER_NOVNC_URLS").ok(), + ), + ( + "BROWSER_CONNECTION_BROWSER_SHARES", + env::var("BROWSER_CONNECTION_BROWSER_SHARES").ok(), + ), + ]; + + env::set_var( + "BROWSER_CONNECTION_PERSONAL_CDP_ENDPOINT", + "http://host.docker.internal:9222", + ); + env::set_var( + "BROWSER_CONNECTION_PERSONAL_VNC_ENDPOINT", + "host.docker.internal:5900", + ); + env::set_var( + "BROWSER_CONNECTION_PERSONAL_NOVNC_URL", + "http://127.0.0.1:6680/vnc.html", + ); + env::remove_var("BROWSER_CONNECTION_BROWSERS"); + env::remove_var("BROWSER_CONNECTION_BROWSER_VNCS"); + env::remove_var("BROWSER_CONNECTION_BROWSER_NOVNC_URLS"); + env::set_var( + "BROWSER_CONNECTION_BROWSER_SHARES", + "edge=https://relay.example/share/s1#agent=a1", + ); + + let endpoints = browser_endpoints_from_env().expect("env endpoints parse"); + let personal = endpoints + .iter() + .find(|endpoint| endpoint.name == PERSONAL_BROWSER_NAME) + .expect("personal endpoint exists"); + + assert_eq!(personal.cdp_endpoint, "http://host.docker.internal:9222"); + assert_eq!( + personal.vnc_endpoint.as_deref(), + Some("host.docker.internal:5900") + ); + assert_eq!( + personal.novnc_url.as_deref(), + Some("http://127.0.0.1:6680/vnc.html") + ); + let edge = endpoints + .iter() + .find(|endpoint| endpoint.name == "edge") + .expect("edge shared endpoint exists"); + assert_eq!( + edge.share_url.as_deref(), + Some("https://relay.example/share/s1#agent=a1") + ); + + for (name, value) in saved { + match value { + Some(value) => env::set_var(name, value), + None => env::remove_var(name), + } + } + } +} diff --git a/src/lib.rs b/src/lib.rs index cabde1e..f16d99b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,8 +15,11 @@ */ mod browser; +pub mod browser_actions; +mod browser_target; pub mod cdp; pub mod mcp; +pub mod shared_browser; use crate::browser::DockerBrowserShell; use anyhow::Result; @@ -26,6 +29,8 @@ use std::env; pub const BROWSER_VNC_PORT: u16 = 5900; pub const BROWSER_NOVNC_PORT: u16 = 6080; pub const BROWSER_CDP_PORT: u16 = 9223; +pub const BROWSER_TARGET_NOVNC_PORT_OFFSET: u16 = 400; +pub const BROWSER_CONTROL_PANEL_PORT_OFFSET: u16 = 800; const DOCKER_GIT_CONTAINER_PREFIX: &str = "dg-"; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -59,6 +64,27 @@ pub fn compute_browser_ports(project_id: &str) -> BrowserPorts { } } +pub fn compute_browser_target_novnc_port(project_id: &str, browser_name: &str) -> u16 { + let normalized = normalize_project_container_name(project_id); + let key = format!("{normalized}:{}", browser_name.trim()); + let hash = key.bytes().fold(0u32, |acc, byte| { + acc.wrapping_mul(31).wrapping_add(u32::from(byte)) + }); + let offset = (hash % 400) as u16; + + BROWSER_NOVNC_PORT + BROWSER_TARGET_NOVNC_PORT_OFFSET + offset +} + +pub fn compute_browser_control_panel_port(project_id: &str) -> u16 { + let normalized = normalize_project_container_name(project_id); + let hash = normalized.bytes().fold(0u32, |acc, byte| { + acc.wrapping_mul(31).wrapping_add(u32::from(byte)) + }); + let offset = (hash % 400) as u16; + + BROWSER_NOVNC_PORT + BROWSER_CONTROL_PANEL_PORT_OFFSET + offset +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct BrowserSpec { pub project_id: String, @@ -70,6 +96,18 @@ pub struct BrowserSpec { pub ports: BrowserPorts, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BrowserTargetDisplaySpec { + pub project_id: String, + pub browser_name: String, + pub main_container_name: String, + pub container_name: String, + pub image_name: String, + pub network_mode: String, + pub vnc_endpoint: String, + pub novnc_port: u16, +} + #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] pub struct BrowserResourceLimits { pub cpu_limit: Option, @@ -111,6 +149,15 @@ pub struct BrowserStopInfo { pub removed: bool, } +#[derive(Debug, Clone, Serialize)] +pub struct BrowserTargetDisplayInfo { + pub project_id: String, + pub browser_name: String, + pub container_name: String, + pub vnc_endpoint: String, + pub novnc_url: String, +} + fn resolved_or(resolve: &F, name: &str, fallback: String) -> String where F: Fn(&str) -> Option, @@ -230,6 +277,75 @@ pub fn browser_spec_from_env(project_id: &str, network: Option<&str>) -> Browser browser_spec_from_resolver(project_id, network, env_value) } +fn browser_target_display_spec_from_resolver( + project_id: &str, + network: Option<&str>, + browser_name: &str, + vnc_endpoint: &str, + resolve: F, +) -> BrowserTargetDisplaySpec +where + F: Fn(&str) -> Option, +{ + let browser_spec = browser_spec_from_resolver(project_id, network, resolve); + let browser_name = browser_name.trim(); + let novnc_port = compute_browser_target_novnc_port(&browser_spec.project_id, browser_name); + let network_mode = display_proxy_network_mode(&browser_spec.network_mode); + + BrowserTargetDisplaySpec { + project_id: browser_spec.project_id, + browser_name: browser_name.to_string(), + main_container_name: browser_spec.main_container_name, + container_name: format!("{}-novnc-{browser_name}", browser_spec.container_name), + image_name: format!( + "{}-novnc-proxy:docker-git-browser", + browser_spec.container_name + ), + network_mode, + vnc_endpoint: vnc_endpoint.trim().to_string(), + novnc_port, + } +} + +fn display_proxy_network_mode(managed_network_mode: &str) -> String { + let network_mode = managed_network_mode.trim(); + if network_mode.is_empty() || network_mode.starts_with("container:") { + "bridge".to_string() + } else { + network_mode.to_string() + } +} + +pub fn browser_target_display_spec_from_defaults( + project_id: &str, + network: Option<&str>, + browser_name: &str, + vnc_endpoint: &str, +) -> BrowserTargetDisplaySpec { + browser_target_display_spec_from_resolver( + project_id, + network, + browser_name, + vnc_endpoint, + |_| None, + ) +} + +pub fn browser_target_display_spec_from_env( + project_id: &str, + network: Option<&str>, + browser_name: &str, + vnc_endpoint: &str, +) -> BrowserTargetDisplaySpec { + browser_target_display_spec_from_resolver( + project_id, + network, + browser_name, + vnc_endpoint, + env_value, + ) +} + // CHANGE: read browser container resource ceilings from docker-git's generated environment. // WHY: docker-git emits DOCKER_GIT_BROWSER_*_LIMIT for the Rust-owned browser container. // QUOTE(ТЗ): "When users set --playwright-cpu/--playwright-ram or rely on the defaults" @@ -275,6 +391,22 @@ pub fn render_cdp_url_for_ports(ports: BrowserPorts) -> String { format!("http://127.0.0.1:{}", ports.cdp) } +pub fn render_novnc_url_for_port(port: u16) -> String { + format!("http://127.0.0.1:{port}/vnc.html?autoconnect=true&resize=remote&path=websockify") +} + +pub fn render_browser_target_novnc_url(project_id: &str, browser_name: &str) -> String { + render_novnc_url_for_port(compute_browser_target_novnc_port(project_id, browser_name)) +} + +pub fn render_browser_control_panel_url(project_id: &str) -> String { + render_browser_control_panel_url_for_port(compute_browser_control_panel_port(project_id)) +} + +pub fn render_browser_control_panel_url_for_port(port: u16) -> String { + format!("http://127.0.0.1:{port}/") +} + pub fn is_single_browser_session(cdp_url: &str, novnc_url: &str) -> bool { novnc_url.contains("/vnc.html") && (cdp_url.starts_with("http://") || cdp_url.starts_with("https://")) @@ -323,6 +455,26 @@ impl BrowserConnection { }) } + pub fn start_browser_target_display( + &self, + project_id: &str, + network: Option<&str>, + browser_name: &str, + vnc_endpoint: &str, + ) -> Result { + let spec = + browser_target_display_spec_from_env(project_id, network, browser_name, vnc_endpoint); + let runtime = self.shell.ensure_novnc_proxy_container(&spec)?; + + Ok(BrowserTargetDisplayInfo { + project_id: spec.project_id, + browser_name: spec.browser_name, + container_name: runtime.container_name, + vnc_endpoint: runtime.vnc_endpoint, + novnc_url: runtime.novnc_url, + }) + } + pub fn get_novnc_url(&self, project_id: &str) -> String { render_novnc_url_for_ports(compute_browser_ports(project_id)) } @@ -331,6 +483,10 @@ impl BrowserConnection { render_cdp_url_for_ports(compute_browser_ports(project_id)) } + pub fn get_browser_target_novnc_url(&self, project_id: &str, browser_name: &str) -> String { + render_browser_target_novnc_url(project_id, browser_name) + } + pub fn is_single_browser_session(&self, cdp_url: &str, novnc_url: &str) -> bool { is_single_browser_session(cdp_url, novnc_url) } @@ -367,6 +523,64 @@ mod tests { assert_eq!(spec.ports, compute_browser_ports("dg-docker-git-issue-347")); } + #[test] + fn target_novnc_port_is_deterministic_and_separate_from_managed_ports() { + let managed = compute_browser_ports("docker-git-issue-347"); + let personal = compute_browser_target_novnc_port("docker-git-issue-347", "personal"); + + assert_eq!( + personal, + compute_browser_target_novnc_port("docker-git-issue-347", "personal") + ); + assert!(personal >= BROWSER_NOVNC_PORT + BROWSER_TARGET_NOVNC_PORT_OFFSET); + assert_ne!(personal, managed.novnc); + } + + #[test] + fn control_panel_port_is_deterministic_and_separate_from_browser_ports() { + let managed = compute_browser_ports("docker-git-issue-347"); + let control = compute_browser_control_panel_port("docker-git-issue-347"); + + assert_eq!( + control, + compute_browser_control_panel_port("docker-git-issue-347") + ); + assert!(control >= BROWSER_NOVNC_PORT + BROWSER_CONTROL_PANEL_PORT_OFFSET); + assert_ne!(control, managed.novnc); + assert_ne!(control, managed.cdp); + } + + #[test] + fn target_display_spec_derives_names_from_browser_spec() { + let spec = browser_target_display_spec_from_defaults( + "docker-git-issue-347", + Some("bridge"), + "personal", + "host.docker.internal:5900", + ); + + assert_eq!(spec.project_id, "docker-git-issue-347"); + assert_eq!(spec.browser_name, "personal"); + assert_eq!( + spec.container_name, + "dg-docker-git-issue-347-browser-novnc-personal" + ); + assert_eq!(spec.network_mode, "bridge"); + assert_eq!(spec.vnc_endpoint, "host.docker.internal:5900"); + } + + #[test] + fn target_display_spec_uses_bridge_when_managed_browser_uses_project_namespace() { + let spec = browser_target_display_spec_from_defaults( + "docker-git-issue-347", + Some("container:dg-docker-git-issue-347"), + "personal", + "host.docker.internal:5900", + ); + + assert_eq!(spec.network_mode, "bridge"); + } + #[test] fn browser_resource_limits_from_resolver_trims_empty_values() { let limits = browser_resource_limits_from_resolver(|name| match name { diff --git a/src/mcp.rs b/src/mcp.rs index 035b271..38956c3 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -7,17 +7,41 @@ REF: https://github.com/ProverCoderAI/docker-git/issues/347 SOURCE: n/a FORMAT THEOREM: initialize ∧ tools/list -> MCP-compatible JSON-RPC responses with browser tools. PURITY: SHELL -EFFECT: stdio JSON-RPC and optional CDP/browser Docker startup. -INVARIANT: MCP startup resolves exactly one CDP endpoint from BrowserConnection or an explicit override. +EFFECT: stdio JSON-RPC, optional CDP/browser Docker startup, and active browser target selection. +INVARIANT: browser tools always target the active CDP endpoint: managed, explicit, or configured. */ -use crate::cdp::CdpClient; -use crate::{render_cdp_url, BrowserConnection}; +use crate::browser_target::{ + configured_browser_kind, normalize_browser_name, normalize_cdp_endpoint, normalize_novnc_url, + normalize_share_url, normalize_vnc_endpoint, upsert_browser_endpoint, upsert_browser_novnc_url, + upsert_browser_share_url, upsert_browser_vnc_endpoint, +}; +use crate::shared_browser::SharedBrowserClient; +use crate::{ + compute_browser_ports, render_browser_control_panel_url_for_port, + render_browser_target_novnc_url, render_cdp_url, render_cdp_url_for_ports, BrowserConnection, +}; +use activity::BrowserActivityLog; use anyhow::{anyhow, Context, Result}; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::env; +use std::fs; use std::io::{BufRead, Write}; - +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +mod activity; +mod control_panel; +mod tools; + +pub use crate::browser_target::{ + active_browser_from_env, browser_endpoints_from_env, parse_named_browser_endpoint, + parse_named_browser_endpoints, parse_named_browser_novnc_url, parse_named_browser_novnc_urls, + parse_named_browser_share_url, parse_named_browser_share_urls, + parse_named_browser_vnc_endpoint, parse_named_browser_vnc_endpoints, NamedBrowserEndpoint, + EXPLICIT_BROWSER_NAME, MANAGED_BROWSER_NAME, PERSONAL_BROWSER_NAME, +}; pub const SERVER_NAME: &str = "browser-connection"; pub const MCP_PROTOCOL_VERSION: &str = "2025-11-25"; pub const PREVIOUS_MCP_PROTOCOL_VERSION: &str = "2025-06-18"; @@ -36,6 +60,9 @@ pub struct McpServerConfig { pub network: Option, pub cdp_endpoint: Option, pub start_browser: bool, + pub browser_endpoints: Vec, + pub active_browser: Option, + pub control_port: Option, } impl McpServerConfig { @@ -50,7 +77,72 @@ impl McpServerConfig { network, cdp_endpoint, start_browser, + browser_endpoints: Vec::new(), + active_browser: None, + control_port: None, + } + } + + pub fn with_browser_endpoints(mut self, endpoints: Vec) -> Self { + for endpoint in endpoints { + upsert_browser_endpoint(&mut self.browser_endpoints, endpoint); } + self + } + + pub fn with_browser_vnc_endpoint( + mut self, + name: impl AsRef, + vnc_endpoint: impl AsRef, + ) -> Result { + let name = normalize_configured_browser_name_for_display(name.as_ref())?; + upsert_browser_vnc_endpoint( + &mut self.browser_endpoints, + name, + normalize_vnc_endpoint(vnc_endpoint.as_ref())?, + ); + Ok(self) + } + + pub fn with_browser_novnc_url( + mut self, + name: impl AsRef, + novnc_url: impl AsRef, + ) -> Result { + let name = normalize_configured_browser_name_for_display(name.as_ref())?; + upsert_browser_novnc_url( + &mut self.browser_endpoints, + name, + normalize_novnc_url(novnc_url.as_ref())?, + ); + Ok(self) + } + + pub fn with_browser_share_url( + mut self, + name: impl AsRef, + share_url: impl AsRef, + ) -> Result { + let name = normalize_configured_browser_name_for_display(name.as_ref())?; + upsert_browser_share_url( + &mut self.browser_endpoints, + name, + normalize_share_url(share_url.as_ref())?, + ); + Ok(self) + } + + pub fn with_active_browser(mut self, active_browser: Option) -> Result { + self.active_browser = active_browser + .as_deref() + .map(normalize_browser_name) + .transpose()?; + Ok(self) + } + + pub fn with_control_port(mut self, control_port: Option) -> Self { + self.control_port = control_port; + self } } @@ -68,14 +160,22 @@ where W: Write, { let mut reader = reader; - let mut runtime = McpRuntime::new(config); + let runtime = Arc::new(Mutex::new(McpRuntime::new(config)?)); + control_panel::spawn_control_panel(Arc::clone(&runtime))?; let mut transport = None; while let Some(message) = read_message(&mut reader, &mut transport)? { - match handle_message(&mut runtime, &message) { + let result = { + let mut runtime = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned"))?; + handle_message(&mut runtime, &message) + }; + match result { Ok(Some(response)) => { - let transport = transport - .ok_or_else(|| anyhow!("stdio transport was unknown after reading a message"))?; + let transport = transport.ok_or_else(|| { + anyhow!("stdio transport was unknown after reading a message") + })?; write_message(&mut writer, &response, transport)?; } Ok(None) => {} @@ -94,41 +194,445 @@ where Ok(()) } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] struct McpRuntime { config: McpServerConfig, - cdp_endpoint: Option, + managed_cdp_endpoint: Option, + active_browser: String, + activity: BrowserActivityLog, } impl McpRuntime { - fn new(config: McpServerConfig) -> Self { - Self { + fn new(mut config: McpServerConfig) -> Result { + load_persisted_runtime_config(&mut config); + let explicit_endpoint = explicit_cdp_endpoint(&config)?; + let active_browser = config.active_browser.clone().unwrap_or_else(|| { + if explicit_endpoint.is_some() { + EXPLICIT_BROWSER_NAME.to_string() + } else { + MANAGED_BROWSER_NAME.to_string() + } + }); + + let runtime = Self { config, - cdp_endpoint: None, + managed_cdp_endpoint: None, + active_browser, + activity: BrowserActivityLog::new(), + }; + runtime.ensure_browser_exists(&runtime.active_browser)?; + Ok(runtime) + } + + fn cdp_endpoint(&mut self) -> Result { + match self.active_browser.as_str() { + MANAGED_BROWSER_NAME => self.managed_cdp_endpoint(), + EXPLICIT_BROWSER_NAME => explicit_cdp_endpoint(&self.config)? + .ok_or_else(|| anyhow!("explicit CDP endpoint is not configured")), + name => self + .config + .browser_endpoints + .iter() + .find(|endpoint| endpoint.name == name) + .and_then(|endpoint| { + (!endpoint.cdp_endpoint.trim().is_empty()) + .then(|| endpoint.cdp_endpoint.clone()) + }) + .ok_or_else(|| { + anyhow!( + "Browser `{name}` does not have a CDP endpoint configured. Available browsers: {}", + self.available_browser_names().join(", ") + ) + }), } } - fn cdp_endpoint(&mut self) -> Result<&str> { - if self.cdp_endpoint.is_none() { - self.cdp_endpoint = Some(resolve_cdp_endpoint(&self.config)?); + fn active_share_url(&self) -> Option { + let name = self.active_browser.as_str(); + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return None; } + self.config + .browser_endpoints + .iter() + .find(|endpoint| endpoint.name == name) + .and_then(|endpoint| endpoint.share_url.clone()) + } - self.cdp_endpoint - .as_deref() - .ok_or_else(|| anyhow!("CDP endpoint cache was empty after resolution")) + fn active_browser_mode(&self) -> String { + match self.active_browser.as_str() { + MANAGED_BROWSER_NAME => "managed".to_string(), + EXPLICIT_BROWSER_NAME => "explicit".to_string(), + name => self + .config + .browser_endpoints + .iter() + .find(|endpoint| endpoint.name == name) + .map(browser_endpoint_kind) + .unwrap_or("unknown") + .to_string(), + } } -} -fn resolve_cdp_endpoint(config: &McpServerConfig) -> Result { - if let Some(endpoint) = config - .cdp_endpoint - .as_deref() - .map(str::trim) - .filter(|endpoint| !endpoint.is_empty()) - { - return Ok(endpoint.to_string()); + fn browser_activity(&mut self, refresh: bool) -> Value { + if refresh { + self.refresh_active_shared_tabs(); + } + self.activity + .snapshot(&self.active_browser, &self.active_browser_mode()) + } + + fn refresh_active_shared_tabs(&mut self) { + let Some(share_url) = self.active_share_url() else { + self.activity.clear_tabs(); + return; + }; + match SharedBrowserClient::new(share_url).list_tabs() { + Ok(tabs) => self.activity.record_tabs(tabs), + Err(error) => self.activity.record_tab_error(error), + } + } + + fn record_tool_activity( + &mut self, + tool: &str, + arguments: &Value, + started_at_ms: u64, + result: &Result, + ) { + let browser = self.active_browser.clone(); + let mode = self.active_browser_mode(); + self.activity + .record_tool_result(&browser, &mode, tool, arguments, started_at_ms, result); + + let Ok(text) = result else { + return; + }; + if tool == "browser_list_tabs" { + match serde_json::from_str::(text) { + Ok(tabs) => self.activity.record_tabs(tabs), + Err(error) => self.activity.record_tab_error(error), + } + return; + } + if self.active_share_url().is_some() && refresh_tabs_after_tool(tool) { + self.refresh_active_shared_tabs(); + } + } + + fn activate_shared_tab_from_panel(&mut self, tab_id: i64) -> Result { + let started_at_ms = activity::now_ms(); + let result = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser")) + .and_then(|share_url| SharedBrowserClient::new(share_url).activate_tab(tab_id)); + let arguments = json!({ "tab_id": tab_id, "source": "control_panel" }); + self.record_tool_activity("browser_activate_tab", &arguments, started_at_ms, &result); + result + .and_then(|text| { + serde_json::from_str::(&text).or_else(|_| Ok(json!({ "result": text }))) + }) + .context("failed to activate shared browser tab") } + fn shared_recording_state_from_panel(&self) -> Result { + let share_url = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser"))?; + SharedBrowserClient::new(share_url).recording_state() + } + + fn start_shared_recording_from_panel(&self) -> Result { + let share_url = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser"))?; + SharedBrowserClient::new(share_url).start_recording() + } + + fn set_shared_recording_mode_from_panel(&self, mode: &str) -> Result { + let share_url = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser"))?; + SharedBrowserClient::new(share_url).set_recording_mode(mode) + } + + fn stop_shared_recording_from_panel(&self) -> Result { + let share_url = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser"))?; + SharedBrowserClient::new(share_url).stop_recording() + } + + fn clear_shared_recording_from_panel(&self) -> Result { + let share_url = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser"))?; + SharedBrowserClient::new(share_url).clear_recording() + } + + fn play_shared_recording_from_panel(&self) -> Result { + let share_url = self + .active_share_url() + .ok_or_else(|| anyhow!("active browser is not a shared-extension browser"))?; + SharedBrowserClient::new(share_url).play_recording() + } + + fn managed_cdp_endpoint(&mut self) -> Result { + if self.managed_cdp_endpoint.is_none() { + self.managed_cdp_endpoint = Some(resolve_managed_cdp_endpoint(&self.config)?); + } + + self.managed_cdp_endpoint + .clone() + .ok_or_else(|| anyhow!("managed CDP endpoint cache was empty after resolution")) + } + + fn browser_inventory_text(&self) -> Result { + serde_json::to_string_pretty(&self.browser_inventory()?) + .context("failed to render browser inventory") + } + + fn browser_inventory(&self) -> Result { + let mut browsers = vec![self.managed_browser_entry()]; + + if let Some(endpoint) = explicit_cdp_endpoint(&self.config)? { + browsers.push(browser_entry( + EXPLICIT_BROWSER_NAME, + "explicit", + Some(endpoint), + None, + None, + None, + "configured", + self.active_browser == EXPLICIT_BROWSER_NAME, + )); + } + + for endpoint in &self.config.browser_endpoints { + browsers.push(browser_entry( + &endpoint.name, + browser_endpoint_kind(endpoint), + (!endpoint.cdp_endpoint.trim().is_empty()).then(|| endpoint.cdp_endpoint.clone()), + endpoint.vnc_endpoint.clone(), + endpoint_novnc_url(&self.config, endpoint), + endpoint.share_url.clone(), + "configured", + self.active_browser == endpoint.name, + )); + } + + Ok(json!({ + "active": self.active_browser, + "controlPanelUrl": control_panel_url(&self.config), + "browsers": browsers + })) + } + + fn managed_browser_entry(&self) -> Value { + let cached_endpoint = self.managed_cdp_endpoint.clone(); + let endpoint = cached_endpoint + .clone() + .or_else(|| (!self.config.start_browser).then(render_cdp_url)) + .or_else(|| { + let ports = compute_browser_ports(&self.config.project_id); + Some(render_cdp_url_for_ports(ports)) + }); + let resolution = if cached_endpoint.is_some() { + "resolved" + } else if self.config.start_browser { + "auto-start" + } else { + "default-localhost" + }; + + browser_entry( + MANAGED_BROWSER_NAME, + "managed", + endpoint, + None, + Some(managed_novnc_url(&self.config)), + None, + resolution, + self.active_browser == MANAGED_BROWSER_NAME, + ) + } + + fn select_browser( + &mut self, + name: &str, + cdp_endpoint: Option<&str>, + vnc_endpoint: Option<&str>, + novnc_url: Option<&str>, + share_url: Option<&str>, + ) -> Result { + let name = normalize_browser_name(name)?; + + if let Some(endpoint) = cdp_endpoint { + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Err(anyhow!( + "`{name}` is reserved; choose a custom name such as `{PERSONAL_BROWSER_NAME}`" + )); + } + let endpoint = NamedBrowserEndpoint::new(&name, endpoint)?; + upsert_browser_endpoint(&mut self.config.browser_endpoints, endpoint); + } + if let Some(endpoint) = vnc_endpoint { + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Err(anyhow!( + "`{name}` is reserved; VNC metadata belongs to custom browser targets" + )); + } + upsert_browser_vnc_endpoint( + &mut self.config.browser_endpoints, + name.clone(), + normalize_vnc_endpoint(endpoint)?, + ); + } + if let Some(url) = novnc_url { + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Err(anyhow!( + "`{name}` is reserved; noVNC metadata belongs to custom browser targets" + )); + } + upsert_browser_novnc_url( + &mut self.config.browser_endpoints, + name.clone(), + normalize_novnc_url(url)?, + ); + } + if let Some(url) = share_url { + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Err(anyhow!( + "`{name}` is reserved; shared browser links belong to custom browser targets" + )); + } + upsert_browser_share_url( + &mut self.config.browser_endpoints, + name.clone(), + normalize_share_url(url)?, + ); + } + + self.ensure_browser_exists(&name)?; + + self.active_browser = name; + self.ensure_active_display()?; + self.persist_runtime_config()?; + let inventory = self.browser_inventory()?; + serde_json::to_string_pretty(&json!({ + "selected": self.active_browser, + "browser": inventory + .get("browsers") + .and_then(Value::as_array) + .and_then(|browsers| browsers.iter().find(|browser| { + browser.get("name").and_then(Value::as_str) == Some(self.active_browser.as_str()) + })) + .cloned() + .unwrap_or(Value::Null) + })) + .context("failed to render browser selection") + } + + fn ensure_browser_exists(&self, name: &str) -> Result<()> { + if name == MANAGED_BROWSER_NAME { + return Ok(()); + } + if name == EXPLICIT_BROWSER_NAME { + if explicit_cdp_endpoint(&self.config)?.is_some() { + return Ok(()); + } + return Err(anyhow!("explicit CDP endpoint is not configured")); + } + if let Some(endpoint) = self + .config + .browser_endpoints + .iter() + .find(|endpoint| endpoint.name == name) + { + if endpoint.cdp_endpoint.trim().is_empty() && endpoint.share_url.is_none() { + return Err(anyhow!( + "Browser `{name}` does not have a CDP endpoint or share URL configured" + )); + } + return Ok(()); + } + + Err(anyhow!( + "Unknown browser `{name}`. Available browsers: {}", + self.available_browser_names().join(", ") + )) + } + + fn persist_runtime_config(&self) -> Result<()> { + if self.config.control_port.is_none() { + return Ok(()); + } + let state = PersistedRuntimeState { + active_browser: Some(self.active_browser.clone()), + browser_endpoints: self.config.browser_endpoints.clone(), + }; + let path = runtime_state_path(&self.config.project_id); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("failed to create {}", parent.display()))?; + } + let body = serde_json::to_vec_pretty(&state).context("failed to encode runtime state")?; + fs::write(&path, body).with_context(|| format!("failed to write {}", path.display())) + } + + fn ensure_active_display(&mut self) -> Result<()> { + if !self.config.start_browser { + return Ok(()); + } + + let name = self.active_browser.clone(); + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Ok(()); + } + + let Some(index) = self + .config + .browser_endpoints + .iter() + .position(|endpoint| endpoint.name == name) + else { + return Ok(()); + }; + let endpoint = self.config.browser_endpoints[index].clone(); + let Some(vnc_endpoint) = endpoint.vnc_endpoint else { + return Ok(()); + }; + if endpoint.novnc_url.is_some() { + return Ok(()); + } + + let connection = BrowserConnection::new()?; + let info = connection.start_browser_target_display( + &self.config.project_id, + self.config.network.as_deref(), + &name, + &vnc_endpoint, + )?; + self.config.browser_endpoints[index].novnc_url = Some(info.novnc_url); + Ok(()) + } + + fn available_browser_names(&self) -> Vec { + let mut names = vec![MANAGED_BROWSER_NAME.to_string()]; + if explicit_cdp_endpoint(&self.config).ok().flatten().is_some() { + names.push(EXPLICIT_BROWSER_NAME.to_string()); + } + names.extend( + self.config + .browser_endpoints + .iter() + .map(|endpoint| endpoint.name.clone()), + ); + names + } +} + +fn resolve_managed_cdp_endpoint(config: &McpServerConfig) -> Result { if !config.start_browser { return Ok(render_cdp_url()); } @@ -138,6 +642,154 @@ fn resolve_cdp_endpoint(config: &McpServerConfig) -> Result { Ok(info.cdp_url) } +fn explicit_cdp_endpoint(config: &McpServerConfig) -> Result> { + config + .cdp_endpoint + .as_deref() + .map(normalize_cdp_endpoint) + .transpose() +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct PersistedRuntimeState { + active_browser: Option, + browser_endpoints: Vec, +} + +fn load_persisted_runtime_config(config: &mut McpServerConfig) { + if config.control_port.is_none() { + return; + } + let path = runtime_state_path(&config.project_id); + let Ok(body) = fs::read_to_string(&path) else { + return; + }; + let Ok(state) = serde_json::from_str::(&body) else { + return; + }; + for endpoint in state.browser_endpoints { + if !config + .browser_endpoints + .iter() + .any(|existing| existing.name == endpoint.name) + { + config.browser_endpoints.push(endpoint); + } + } + if config.active_browser.is_none() { + config.active_browser = state + .active_browser + .and_then(|name| normalize_browser_name(&name).ok()); + } +} + +fn runtime_state_path(project_id: &str) -> PathBuf { + runtime_state_dir().join(format!("{}.json", runtime_state_file_stem(project_id))) +} + +fn runtime_state_dir() -> PathBuf { + env::var_os("BROWSER_CONNECTION_STATE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| env::temp_dir().join("browser-connection")) +} + +fn runtime_state_file_stem(project_id: &str) -> String { + let stem = project_id + .chars() + .map(|ch| { + if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') { + ch + } else { + '_' + } + }) + .collect::(); + if stem.is_empty() { + "default".to_string() + } else { + stem + } +} + +#[allow(clippy::too_many_arguments)] +fn browser_entry( + name: &str, + kind: &str, + cdp_endpoint: Option, + vnc_endpoint: Option, + novnc_url: Option, + share_url: Option, + resolution: &str, + active: bool, +) -> Value { + json!({ + "name": name, + "kind": kind, + "cdpEndpoint": cdp_endpoint, + "vncEndpoint": vnc_endpoint, + "novncUrl": novnc_url, + "shareUrl": share_url, + "resolution": resolution, + "active": active + }) +} + +fn browser_endpoint_kind(endpoint: &NamedBrowserEndpoint) -> &'static str { + if endpoint.share_url.is_some() && endpoint.cdp_endpoint.trim().is_empty() { + "shared-extension" + } else { + configured_browser_kind(&endpoint.name) + } +} + +fn refresh_tabs_after_tool(tool: &str) -> bool { + matches!( + tool, + "browser_navigate" + | "browser_snapshot" + | "browser_evaluate" + | "browser_click" + | "browser_type" + | "browser_press_key" + | "browser_take_screenshot" + | "browser_activate_tab" + ) +} + +fn managed_novnc_url(config: &McpServerConfig) -> String { + if !config.start_browser { + return crate::render_novnc_url(); + } + + let ports = compute_browser_ports(&config.project_id); + crate::render_novnc_url_for_ports(ports) +} + +fn endpoint_novnc_url(config: &McpServerConfig, endpoint: &NamedBrowserEndpoint) -> Option { + endpoint.novnc_url.clone().or_else(|| { + endpoint + .vnc_endpoint + .as_ref() + .map(|_| render_browser_target_novnc_url(&config.project_id, &endpoint.name)) + }) +} + +fn control_panel_url(config: &McpServerConfig) -> Option { + config + .control_port + .map(render_browser_control_panel_url_for_port) +} + +fn normalize_configured_browser_name_for_display(name: &str) -> Result { + let name = normalize_browser_name(name)?; + if name == MANAGED_BROWSER_NAME || name == EXPLICIT_BROWSER_NAME { + return Err(anyhow!( + "`{name}` is reserved and cannot name a configured browser" + )); + } + Ok(name) +} + fn read_message( reader: &mut R, transport: &mut Option, @@ -303,8 +955,8 @@ fn handle_message(runtime: &mut McpRuntime, message: &str) -> Result success_response(id, initialize_result(protocol_version)), Err(error) => error_response(id, -32602, &error.to_string()), }, - "tools/list" => success_response(id, json!({ "tools": tool_definitions() })), - "tools/call" => success_response(id, handle_tool_call(runtime, &request)), + "tools/list" => success_response(id, json!({ "tools": tools::tool_definitions() })), + "tools/call" => success_response(id, tools::handle_tool_call(runtime, &request)), _ => error_response(id, -32601, &format!("Unknown MCP method: {method}")), }; @@ -338,122 +990,6 @@ fn initialize_result(protocol_version: &str) -> Value { }) } -fn tool_definitions() -> Vec { - vec![ - tool( - "browser_navigate", - "Navigate the noVNC-visible Chromium page to a URL through the Rust CDP adapter.", - json!({ "url": { "type": "string", "description": "Absolute URL to open" } }), - vec!["url"], - ), - tool( - "browser_snapshot", - "Return page title, URL, visible text and simple interactive element selectors.", - json!({}), - vec![], - ), - tool( - "browser_evaluate", - "Evaluate JavaScript in the current page and return a JSON/text result.", - json!({ "expression": { "type": "string", "description": "JavaScript expression" } }), - vec!["expression"], - ), - tool( - "browser_click", - "Click an element by CSS selector in the current page.", - json!({ "selector": { "type": "string", "description": "CSS selector" } }), - vec!["selector"], - ), - tool( - "browser_type", - "Set text in an input-like element by CSS selector and dispatch input/change events.", - json!({ - "selector": { "type": "string", "description": "CSS selector" }, - "text": { "type": "string", "description": "Text to type" } - }), - vec!["selector", "text"], - ), - tool( - "browser_press_key", - "Press a key through CDP Input.dispatchKeyEvent.", - json!({ "key": { "type": "string", "description": "Key name, e.g. Enter or a" } }), - vec!["key"], - ), - tool( - "browser_take_screenshot", - "Capture a PNG screenshot and return it as a data URL.", - json!({ "full_page": { "type": "boolean", "description": "Capture beyond viewport", "default": true } }), - vec![], - ), - ] -} - -fn tool(name: &str, description: &str, properties: Value, required: Vec<&str>) -> Value { - json!({ - "name": name, - "description": description, - "inputSchema": { - "type": "object", - "properties": properties, - "required": required - } - }) -} - -fn handle_tool_call(runtime: &mut McpRuntime, request: &Value) -> Value { - let params = request.get("params").unwrap_or(&Value::Null); - let name = params.get("name").and_then(Value::as_str).unwrap_or(""); - let arguments = params.get("arguments").unwrap_or(&Value::Null); - - let result = runtime - .cdp_endpoint() - .and_then(|cdp_endpoint| dispatch_tool(cdp_endpoint, name, arguments)); - match result { - Ok(text) => tool_result(text, false), - Err(error) => tool_result(format!("{error:#}"), true), - } -} - -fn dispatch_tool(cdp_endpoint: &str, name: &str, arguments: &Value) -> Result { - let client = CdpClient::new(cdp_endpoint); - match name { - "browser_navigate" => client.navigate(required_str(arguments, "url")?), - "browser_snapshot" => client.snapshot(), - "browser_evaluate" => client.evaluate(required_str(arguments, "expression")?), - "browser_click" => client.click(required_str(arguments, "selector")?), - "browser_type" => client.type_text( - required_str(arguments, "selector")?, - required_str(arguments, "text")?, - ), - "browser_press_key" => client.press_key(required_str(arguments, "key")?), - "browser_take_screenshot" => { - let full_page = arguments - .get("full_page") - .and_then(Value::as_bool) - .unwrap_or(true); - client.screenshot(full_page) - } - "" => Err(anyhow!("tools/call params.name is required")), - _ => Err(anyhow!("Unknown browser-connection tool: {name}")), - } -} - -fn required_str<'a>(arguments: &'a Value, name: &str) -> Result<&'a str> { - arguments - .get(name) - .and_then(Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .ok_or_else(|| anyhow!("argument `{name}` is required")) -} - -fn tool_result(text: String, is_error: bool) -> Value { - json!({ - "content": [{ "type": "text", "text": text }], - "isError": is_error - }) -} - fn success_response(id: Value, result: Value) -> Value { json!({ "jsonrpc": "2.0", "id": id, "result": result }) } @@ -472,220 +1008,4 @@ fn normalize_project_id(project_id: String) -> String { } #[cfg(test)] -mod tests { - use super::*; - use std::io::Cursor; - - fn encode_message(value: Value) -> Vec { - let body = serde_json::to_vec(&value).expect("message body serializes"); - let mut framed = format!("Content-Length: {}\r\n\r\n", body.len()).into_bytes(); - framed.extend_from_slice(&body); - framed - } - - fn decode_messages(bytes: &[u8]) -> Vec { - let mut cursor = Cursor::new(bytes); - let mut responses = Vec::new(); - - let mut transport = Some(StdioTransport::Framed); - while let Some(message) = read_message(&mut cursor, &mut transport).expect("stdout frame parses") { - responses.push(serde_json::from_str(&message).expect("stdout frame body is JSON")); - } - - responses - } - - fn decode_line_messages(bytes: &[u8]) -> Vec { - let text = String::from_utf8(bytes.to_vec()).expect("stdout lines are utf8"); - text.lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).expect("stdout line is JSON")) - .collect() - } - - #[test] - fn env_fallback_prefers_explicit_project() { - assert_eq!( - project_id_from_env_or_default(Some(" dg-x ".to_string())), - "dg-x" - ); - } - - #[test] - fn stdio_initialize_and_list_use_framed_mcp_transport() { - let config = McpServerConfig::new("dg-test", None, None, false); - let mut input = Vec::new(); - input.extend(encode_message(json!({ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": MCP_PROTOCOL_VERSION, - "capabilities": {}, - "clientInfo": { "name": "probe", "version": "0" } - } - }))); - input.extend(encode_message(json!({ - "jsonrpc": "2.0", - "method": "notifications/initialized", - "params": {} - }))); - input.extend(encode_message(json!({ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/list", - "params": {} - }))); - - let input = Cursor::new(input); - let mut output = Vec::new(); - - run_stdio(config, input, &mut output).expect("stdio loop succeeds"); - - let responses = decode_messages(&output); - assert_eq!(responses.len(), 2); - assert_eq!(responses[0]["id"], 1); - assert_eq!(responses[0]["result"]["serverInfo"]["name"], SERVER_NAME); - assert_eq!(responses[1]["id"], 2); - assert!(responses[1]["result"]["tools"] - .as_array() - .expect("tools/list returns an array") - .iter() - .any(|tool| tool["name"] == "browser_navigate")); - } - - #[test] - fn stdio_initialize_and_list_use_line_delimited_transport() { - let config = McpServerConfig::new("dg-test", None, None, false); - let input = Cursor::new( - [ - r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"elicitation":{}},"clientInfo":{"name":"codex-mcp-client","version":"0"}}}"#, - r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#, - ] - .join("\n"), - ); - let mut output = Vec::new(); - - run_stdio(config, input, &mut output).expect("stdio loop succeeds"); - - let responses = decode_line_messages(&output); - assert_eq!(responses.len(), 2); - assert_eq!(responses[0]["id"], 1); - assert_eq!(responses[0]["result"]["protocolVersion"], "2025-06-18"); - assert_eq!(responses[1]["id"], 2); - assert!(responses[1]["result"]["tools"] - .as_array() - .expect("tools/list returns an array") - .iter() - .any(|tool| tool["name"] == "browser_navigate")); - } - - #[test] - fn initialize_and_tools_list_do_not_resolve_cdp_endpoint() { - let config = McpServerConfig::new("dg-test", None, None, true); - let mut runtime = McpRuntime::new(config); - - handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#, - ) - .expect("initialize succeeds"); - handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#, - ) - .expect("tools/list succeeds"); - - assert_eq!(runtime.cdp_endpoint, None); - } - - #[test] - fn initialize_negotiates_legacy_protocol_version() { - let config = McpServerConfig::new("dg-test", None, None, false); - let mut runtime = McpRuntime::new(config); - - let response = handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}}"#, - ) - .expect("initialize succeeds") - .expect("request with id returns a response"); - - assert_eq!(response["result"]["protocolVersion"], "2024-11-05"); - assert_eq!(response["result"]["capabilities"]["tools"]["listChanged"], false); - } - - #[test] - fn initialize_negotiates_latest_protocol_version() { - let config = McpServerConfig::new("dg-test", None, None, false); - let mut runtime = McpRuntime::new(config); - - let response = handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"roots":{"listChanged":true}},"clientInfo":{"name":"claude-code","version":"2.1.160"}}}"#, - ) - .expect("initialize succeeds") - .expect("request with id returns a response"); - - assert_eq!(response["result"]["protocolVersion"], "2025-11-25"); - } - - #[test] - fn initialize_negotiates_previous_protocol_version() { - let config = McpServerConfig::new("dg-test", None, None, false); - let mut runtime = McpRuntime::new(config); - - let response = handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"elicitation":{}},"clientInfo":{"name":"codex-mcp-client","version":"0"}}}"#, - ) - .expect("initialize succeeds") - .expect("request with id returns a response"); - - assert_eq!(response["result"]["protocolVersion"], "2025-06-18"); - } - - #[test] - fn initialize_rejects_unknown_protocol_version() { - let config = McpServerConfig::new("dg-test", None, None, false); - let mut runtime = McpRuntime::new(config); - - let response = handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2099-01-01","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}}"#, - ) - .expect("initialize response serializes") - .expect("request with id returns a response"); - - assert_eq!(response["error"]["code"], -32602); - assert!(response["error"]["message"] - .as_str() - .expect("error message exists") - .contains("Unsupported MCP protocol version")); - } - - #[test] - fn tools_call_resolves_cdp_endpoint_lazily() { - let config = McpServerConfig::new("dg-test", None, None, false); - let mut runtime = McpRuntime::new(config); - let expected_cdp_url = render_cdp_url(); - - let response = handle_message( - &mut runtime, - r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"unknown","arguments":{}}}"#, - ) - .expect("tools/call response serializes") - .expect("request with id returns a response"); - - assert_eq!( - runtime.cdp_endpoint.as_deref(), - Some(expected_cdp_url.as_str()) - ); - assert_eq!(response["id"], 3); - assert_eq!(response["result"]["isError"], true); - assert!(response["result"]["content"][0]["text"] - .as_str() - .expect("tool result text exists") - .contains("Unknown browser-connection tool")); - } -} +mod tests; diff --git a/src/mcp/activity.rs b/src/mcp/activity.rs new file mode 100644 index 0000000..8a722d7 --- /dev/null +++ b/src/mcp/activity.rs @@ -0,0 +1,420 @@ +use anyhow::Result; +use serde_json::{json, Map, Value}; +use std::collections::{BTreeMap, VecDeque}; +use std::time::{SystemTime, UNIX_EPOCH}; + +const MAX_EVENTS: usize = 200; +const MAX_SCREENSHOTS: usize = 24; +const MAX_TEXT_CHARS: usize = 700; + +#[derive(Debug, Clone, PartialEq)] +pub(super) struct BrowserActivityLog { + next_event_id: u64, + events: VecDeque, + screenshots: VecDeque, + latest_tabs: Option, + latest_tab_error: Option, +} + +impl BrowserActivityLog { + pub(super) fn new() -> Self { + Self { + next_event_id: 1, + events: VecDeque::new(), + screenshots: VecDeque::new(), + latest_tabs: None, + latest_tab_error: None, + } + } + + pub(super) fn snapshot(&self, active_browser: &str, mode: &str) -> Value { + json!({ + "activeBrowser": active_browser, + "mode": mode, + "tabs": self.latest_tabs.clone().unwrap_or(Value::Null), + "tabsError": self.latest_tab_error, + "screenshots": self.screenshots.iter().cloned().collect::>(), + "latestScreenshot": self.screenshots.front().cloned().unwrap_or(Value::Null), + "events": self.events.iter().cloned().collect::>(), + }) + } + + pub(super) fn record_tabs(&mut self, value: Value) { + self.latest_tabs = Some(tab_inventory(value)); + self.latest_tab_error = None; + } + + pub(super) fn record_tab_error(&mut self, error: impl ToString) { + self.latest_tab_error = Some(error.to_string()); + } + + pub(super) fn clear_tabs(&mut self) { + self.latest_tabs = None; + self.latest_tab_error = None; + } + + pub(super) fn record_tool_result( + &mut self, + browser: &str, + mode: &str, + tool: &str, + arguments: &Value, + started_at_ms: u64, + result: &Result, + ) { + let event_id = self.next_event_id; + self.next_event_id += 1; + + let duration_ms = now_ms().saturating_sub(started_at_ms); + let (ok, error, result_summary) = match result { + Ok(text) => (true, Value::Null, result_summary(tool, text)), + Err(error) => (false, json!(error.to_string()), Value::Null), + }; + let screenshot_id = result + .as_ref() + .ok() + .and_then(|text| self.record_screenshot(event_id, browser, tool, text)); + + self.events.push_front(json!({ + "id": event_id, + "at": started_at_ms, + "browser": browser, + "mode": mode, + "tool": tool, + "arguments": sanitize_value(arguments), + "ok": ok, + "durationMs": duration_ms, + "error": error, + "result": result_summary, + "screenshotId": screenshot_id, + })); + truncate(&mut self.events, MAX_EVENTS); + } + + fn record_screenshot( + &mut self, + event_id: u64, + browser: &str, + tool: &str, + text: &str, + ) -> Option { + let screenshot = extract_screenshot(text)?; + let screenshot_id = event_id; + self.screenshots.push_front(json!({ + "id": screenshot_id, + "eventId": event_id, + "at": now_ms(), + "browser": browser, + "tool": tool, + "mimeType": screenshot.mime_type, + "dataUrl": screenshot.data_url, + })); + truncate(&mut self.screenshots, MAX_SCREENSHOTS); + Some(screenshot_id) + } +} + +pub(super) fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64) + .unwrap_or(0) +} + +fn truncate(values: &mut VecDeque, limit: usize) { + while values.len() > limit { + values.pop_back(); + } +} + +fn sanitize_value(value: &Value) -> Value { + match value { + Value::Object(object) => { + let mut sanitized = Map::new(); + for (key, value) in object { + let lower = key.to_ascii_lowercase(); + if lower.contains("token") || lower == "share_url" || lower == "shareurl" { + sanitized.insert(key.clone(), json!("[redacted]")); + } else { + sanitized.insert(key.clone(), sanitize_value(value)); + } + } + Value::Object(sanitized) + } + Value::Array(values) => Value::Array(values.iter().map(sanitize_value).collect()), + _ => value.clone(), + } +} + +fn result_summary(tool: &str, text: &str) -> Value { + if extract_screenshot(text).is_some() { + return json!({ "kind": "screenshot", "text": "screenshot captured" }); + } + + if let Ok(value) = serde_json::from_str::(text) { + let tab = value.get("tab").cloned().unwrap_or(Value::Null); + let snapshot = value.get("snapshot").cloned().unwrap_or(Value::Null); + return json!({ + "kind": "json", + "tool": tool, + "title": snapshot.get("title").or_else(|| tab.get("title")).cloned().unwrap_or(Value::Null), + "url": snapshot.get("url").or_else(|| tab.get("url")).cloned().unwrap_or(Value::Null), + "tab": tab, + }); + } + + json!({ + "kind": "text", + "text": truncate_text(text, MAX_TEXT_CHARS), + }) +} + +struct Screenshot { + data_url: String, + mime_type: String, +} + +fn extract_screenshot(text: &str) -> Option { + let trimmed = text.trim(); + if trimmed.starts_with("data:image/") { + return Some(Screenshot { + mime_type: mime_type_from_data_url(trimmed), + data_url: trimmed.to_string(), + }); + } + + let value = serde_json::from_str::(trimmed).ok()?; + extract_screenshot_from_value(&value) +} + +fn find_data_url(value: &Value) -> Option { + match value { + Value::String(text) if text.starts_with("data:image/") => Some(text.clone()), + Value::Array(values) => values.iter().find_map(find_data_url), + Value::Object(object) => object.values().find_map(find_data_url), + _ => None, + } +} + +fn extract_screenshot_from_value(value: &Value) -> Option { + if let Some(data_url) = find_data_url(value) { + return Some(Screenshot { + mime_type: mime_type_from_data_url(&data_url), + data_url, + }); + } + + let object = value.as_object()?; + let data = object.get("data").and_then(Value::as_str)?; + let mime_type = object + .get("mimeType") + .and_then(Value::as_str) + .filter(|value| value.starts_with("image/")) + .unwrap_or("image/png") + .to_string(); + Some(Screenshot { + data_url: format!("data:{mime_type};base64,{data}"), + mime_type, + }) +} + +fn mime_type_from_data_url(data_url: &str) -> String { + data_url + .strip_prefix("data:") + .and_then(|rest| rest.split_once(';').map(|(mime, _)| mime.to_string())) + .unwrap_or_else(|| "image/png".to_string()) +} + +fn tab_inventory(value: Value) -> Value { + let tabs = value + .get("tabs") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + if let Some(windows) = value.get("windows").and_then(Value::as_array) { + let windows = windows + .iter() + .cloned() + .map(normalize_window) + .collect::>(); + let tabs = if tabs.is_empty() { + tabs_from_windows(&windows) + } else { + tabs + }; + let active_tab = focused_active_tab(&windows) + .or_else(|| { + tabs.iter() + .find(|tab| tab.get("active").and_then(Value::as_bool) == Some(true)) + .cloned() + }) + .unwrap_or(Value::Null); + return json!({ + "totalTabs": tabs.len(), + "totalWindows": windows.len(), + "activeTab": active_tab, + "windows": windows, + "tabs": tabs, + }); + } + + let mut windows = BTreeMap::>::new(); + let mut active_tab = Value::Null; + + for tab in &tabs { + let window_id = tab.get("windowId").and_then(Value::as_i64).unwrap_or(-1); + if tab.get("active").and_then(Value::as_bool) == Some(true) { + active_tab = tab.clone(); + } + windows.entry(window_id).or_default().push(tab.clone()); + } + + let windows = windows + .into_iter() + .map(|(window_id, tabs)| { + let active = tabs + .iter() + .any(|tab| tab.get("active").and_then(Value::as_bool) == Some(true)); + json!({ + "windowId": window_id, + "active": active, + "tabCount": tabs.len(), + "tabs": tabs, + }) + }) + .collect::>(); + + json!({ + "totalTabs": tabs.len(), + "totalWindows": windows.len(), + "activeTab": active_tab, + "windows": windows, + "tabs": tabs, + }) +} + +fn focused_active_tab(windows: &[Value]) -> Option { + windows + .iter() + .find(|window| window.get("focused").and_then(Value::as_bool) == Some(true)) + .and_then(|window| { + window + .get("tabs") + .and_then(Value::as_array) + .and_then(|tabs| { + tabs.iter() + .find(|tab| tab.get("active").and_then(Value::as_bool) == Some(true)) + .cloned() + }) + }) +} + +fn tabs_from_windows(windows: &[Value]) -> Vec { + windows + .iter() + .filter_map(|window| window.get("tabs").and_then(Value::as_array)) + .flatten() + .cloned() + .collect() +} + +fn normalize_window(mut window: Value) -> Value { + let tab_count = window + .get("tabs") + .and_then(Value::as_array) + .map(Vec::len) + .unwrap_or(0); + let active = window + .get("tabs") + .and_then(Value::as_array) + .is_some_and(|tabs| { + tabs.iter() + .any(|tab| tab.get("active").and_then(Value::as_bool) == Some(true)) + }); + if let Some(object) = window.as_object_mut() { + object.insert("tabCount".to_string(), json!(tab_count)); + object.insert("active".to_string(), json!(active)); + } + window +} + +fn truncate_text(text: &str, max_chars: usize) -> String { + let mut output = String::new(); + for (index, ch) in text.chars().enumerate() { + if index >= max_chars { + output.push_str("..."); + return output; + } + output.push(ch); + } + output +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extracts_data_url_from_screenshot_json() { + let screenshot = extract_screenshot(r#"{"dataUrl":"data:image/png;base64,abc"}"#).unwrap(); + + assert_eq!(screenshot.mime_type, "image/png"); + assert_eq!(screenshot.data_url, "data:image/png;base64,abc"); + } + + #[test] + fn extracts_base64_data_from_screenshot_json() { + let screenshot = extract_screenshot(r#"{"mimeType":"image/jpeg","data":"abc"}"#).unwrap(); + + assert_eq!(screenshot.mime_type, "image/jpeg"); + assert_eq!(screenshot.data_url, "data:image/jpeg;base64,abc"); + } + + #[test] + fn groups_tabs_by_window() { + let inventory = tab_inventory(json!({ + "tabs": [ + {"id": 1, "windowId": 10, "active": true}, + {"id": 2, "windowId": 10, "active": false}, + {"id": 3, "windowId": 11, "active": false} + ] + })); + + assert_eq!(inventory["totalTabs"], 3); + assert_eq!(inventory["totalWindows"], 2); + assert_eq!(inventory["activeTab"]["id"], 1); + } + + #[test] + fn preserves_window_metadata_from_extension() { + let inventory = tab_inventory(json!({ + "windows": [{ + "id": 10, + "focused": true, + "incognito": true, + "profile": "incognito", + "type": "normal", + "tabs": [{"id": 1, "windowId": 10, "active": true}] + }], + "tabs": [{"id": 1, "windowId": 10, "active": true}] + })); + + assert_eq!(inventory["totalWindows"], 1); + assert_eq!(inventory["windows"][0]["incognito"], true); + assert_eq!(inventory["windows"][0]["profile"], "incognito"); + assert_eq!(inventory["windows"][0]["tabCount"], 1); + } + + #[test] + fn active_tab_prefers_focused_window() { + let inventory = tab_inventory(json!({ + "windows": [ + {"id": 10, "focused": false, "tabs": [{"id": 1, "active": true}]}, + {"id": 11, "focused": true, "tabs": [{"id": 2, "active": true}]} + ] + })); + + assert_eq!(inventory["totalTabs"], 2); + assert_eq!(inventory["activeTab"]["id"], 2); + } +} diff --git a/src/mcp/control_panel.html b/src/mcp/control_panel.html new file mode 100644 index 0000000..62a4719 --- /dev/null +++ b/src/mcp/control_panel.html @@ -0,0 +1,1539 @@ + + + + + +browser-connection + + + +
+ + +
+
+
+
Current target
+

Waiting for browser

+
-
+
+ +
+ + + + + + +
+
+ + + + diff --git a/src/mcp/control_panel.rs b/src/mcp/control_panel.rs new file mode 100644 index 0000000..f1ea453 --- /dev/null +++ b/src/mcp/control_panel.rs @@ -0,0 +1,700 @@ +use super::{McpRuntime, PERSONAL_BROWSER_NAME}; +use crate::shared_browser::BrowserShareRelay; +use anyhow::{anyhow, Context, Result}; +use serde_json::{json, Value}; +use std::env; +use std::fmt::Write as _; +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +const MAX_HTTP_REQUEST_BYTES: usize = 64 * 1024; + +pub(super) fn spawn_control_panel(runtime: Arc>) -> Result<()> { + let (port, project_id) = { + let runtime = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned"))?; + let Some(port) = runtime.config.control_port else { + return Ok(()); + }; + (port, runtime.config.project_id.clone()) + }; + + let listener = TcpListener::bind(("127.0.0.1", port)) + .with_context(|| format!("failed to bind browser control panel on 127.0.0.1:{port}"))?; + let relay = BrowserShareRelay::new(); + let control_token = Arc::new(load_or_create_control_token(&project_id)?); + thread::Builder::new() + .name("browser-control-panel".to_string()) + .spawn(move || { + for stream in listener.incoming().flatten() { + let runtime = Arc::clone(&runtime); + let relay = relay.clone(); + let control_token = Arc::clone(&control_token); + thread::Builder::new() + .name("browser-control-panel-client".to_string()) + .spawn(move || { + let _ = handle_connection(runtime, relay, control_token, stream); + }) + .ok(); + } + }) + .context("failed to spawn browser control panel thread")?; + + Ok(()) +} + +fn handle_connection( + runtime: Arc>, + relay: BrowserShareRelay, + control_token: Arc, + mut stream: TcpStream, +) -> Result<()> { + stream.set_read_timeout(Some(Duration::from_secs(3))).ok(); + stream.set_write_timeout(Some(Duration::from_secs(3))).ok(); + + if is_relay_websocket_request(&stream)? { + return relay + .handle_stream(stream) + .context("failed to handle embedded browser share relay client"); + } + + let request = read_http_request(&mut stream)?; + let response = route_request(runtime, control_token.as_str(), &request); + write_http_response(&mut stream, response) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct HttpRequest { + method: String, + target: String, + headers: Vec<(String, String)>, + body: String, +} + +struct HttpResponse { + status: u16, + reason: &'static str, + content_type: &'static str, + body: Vec, +} + +fn read_http_request(stream: &mut TcpStream) -> Result { + let mut data = Vec::new(); + let mut buffer = [0_u8; 4096]; + + loop { + let read = stream + .read(&mut buffer) + .context("failed to read control panel HTTP request")?; + if read == 0 { + break; + } + data.extend_from_slice(&buffer[..read]); + if data.len() > MAX_HTTP_REQUEST_BYTES { + return Err(anyhow!("control panel HTTP request was too large")); + } + if let Some(header_end) = header_end(&data) { + let content_length = content_length(&data[..header_end])?; + let request_end = header_end + 4 + content_length; + while data.len() < request_end { + let read = stream + .read(&mut buffer) + .context("failed to read control panel HTTP request body")?; + if read == 0 { + break; + } + data.extend_from_slice(&buffer[..read]); + if data.len() > MAX_HTTP_REQUEST_BYTES { + return Err(anyhow!("control panel HTTP request was too large")); + } + } + break; + } + } + + parse_http_request(&data) +} + +fn is_relay_websocket_request(stream: &TcpStream) -> Result { + let mut data = [0_u8; 2048]; + let read = stream + .peek(&mut data) + .context("failed to peek control panel request")?; + if read == 0 { + return Ok(false); + } + let head = String::from_utf8_lossy(&data[..read]); + let Some(request_line) = head.lines().next() else { + return Ok(false); + }; + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap_or_default(); + let target = parts.next().unwrap_or_default(); + Ok(method.eq_ignore_ascii_case("GET") && is_relay_path(request_path(target))) +} + +fn is_relay_path(path: &str) -> bool { + path.starts_with("/ws/browser/") || path.starts_with("/ws/agent/") +} + +fn header_end(data: &[u8]) -> Option { + data.windows(4).position(|window| window == b"\r\n\r\n") +} + +fn content_length(header: &[u8]) -> Result { + let header = String::from_utf8_lossy(header); + for line in header.lines().skip(1) { + let Some((name, value)) = line.split_once(':') else { + continue; + }; + if name.eq_ignore_ascii_case("Content-Length") { + return value + .trim() + .parse::() + .context("control panel Content-Length was invalid"); + } + } + Ok(0) +} + +fn parse_http_request(data: &[u8]) -> Result { + let header_end = header_end(data).ok_or_else(|| anyhow!("HTTP header terminator missing"))?; + let head = String::from_utf8_lossy(&data[..header_end]); + let request_line = head + .lines() + .next() + .ok_or_else(|| anyhow!("HTTP request line missing"))?; + let mut parts = request_line.split_whitespace(); + let method = parts + .next() + .ok_or_else(|| anyhow!("HTTP method missing"))? + .to_string(); + let target = parts + .next() + .ok_or_else(|| anyhow!("HTTP target missing"))? + .to_string(); + let headers = head + .lines() + .skip(1) + .filter_map(|line| { + let (name, value) = line.split_once(':')?; + Some((name.trim().to_ascii_lowercase(), value.trim().to_string())) + }) + .collect(); + let body = String::from_utf8_lossy(&data[header_end + 4..]).to_string(); + + Ok(HttpRequest { + method, + target, + headers, + body, + }) +} + +fn route_request( + runtime: Arc>, + control_token: &str, + request: &HttpRequest, +) -> HttpResponse { + match (request.method.as_str(), request_path(&request.target)) { + ("OPTIONS", _) => empty_response(204, "No Content"), + ("GET", "/") | ("GET", "/index.html") => control_panel_response(runtime, control_token), + ("GET", "/api/browsers") => browser_inventory_response(runtime), + ("GET", "/api/activity") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + activity_response(runtime, request) + } + ("POST", "/api/activate-tab") | ("GET", "/api/activate-tab") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + activate_tab_response(runtime, request) + } + ("GET", "/api/recording") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "state") + } + ("POST", "/api/recording/start") | ("GET", "/api/recording/start") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "start") + } + ("POST", "/api/recording/record") | ("GET", "/api/recording/record") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "record") + } + ("POST", "/api/recording/inspect") | ("GET", "/api/recording/inspect") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "inspect") + } + ("POST", "/api/recording/stop") | ("GET", "/api/recording/stop") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "stop") + } + ("POST", "/api/recording/clear") | ("GET", "/api/recording/clear") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "clear") + } + ("POST", "/api/recording/play") | ("GET", "/api/recording/play") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + recording_response(runtime, "play") + } + ("POST", "/api/share") | ("GET", "/api/share") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + register_share_response(runtime, request) + } + ("POST", "/api/select") | ("GET", "/api/select") => { + if !has_valid_control_token(request, control_token) { + return json_response( + 403, + "Forbidden", + json!({ "error": "invalid control token" }), + ); + } + select_browser_response(runtime, request) + } + _ => json_response(404, "Not Found", json!({ "error": "not found" })), + } +} + +fn request_path(target: &str) -> &str { + target + .split_once('?') + .map(|(path, _)| path) + .unwrap_or(target) +} + +fn control_panel_response(runtime: Arc>, control_token: &str) -> HttpResponse { + let project_id = runtime + .lock() + .map(|runtime| runtime.config.project_id.clone()) + .unwrap_or_else(|_| "browser-connection".to_string()); + html_response(control_panel_html(control_token, &project_id)) +} + +fn has_valid_control_token(request: &HttpRequest, control_token: &str) -> bool { + let provided = request + .header("x-browser-control-token") + .or_else(|| query_param(&request.target, "control_token")) + .or_else(|| query_param(&request.body, "control_token")); + provided.as_deref() == Some(control_token) +} + +impl HttpRequest { + fn header(&self, name: &str) -> Option { + let name = name.to_ascii_lowercase(); + self.headers + .iter() + .find_map(|(key, value)| (key == &name).then(|| value.clone())) + } +} + +fn browser_inventory_response(runtime: Arc>) -> HttpResponse { + let result = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned")) + .and_then(|runtime| runtime.browser_inventory()); + match result { + Ok(inventory) => json_response(200, "OK", inventory), + Err(error) => json_response( + 500, + "Internal Server Error", + json!({ "error": error.to_string() }), + ), + } +} + +fn activity_response(runtime: Arc>, request: &HttpRequest) -> HttpResponse { + let refresh = query_param(&request.target, "refresh").as_deref() == Some("1"); + let result = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned")) + .map(|mut runtime| runtime.browser_activity(refresh)); + match result { + Ok(activity) => json_response(200, "OK", activity), + Err(error) => json_response( + 500, + "Internal Server Error", + json!({ "error": error.to_string() }), + ), + } +} + +fn activate_tab_response(runtime: Arc>, request: &HttpRequest) -> HttpResponse { + let Some(tab_id) = + query_param(&request.target, "tab_id").or_else(|| query_param(&request.body, "tab_id")) + else { + return json_response(400, "Bad Request", json!({ "error": "tab_id is required" })); + }; + let Ok(tab_id) = tab_id.parse::() else { + return json_response( + 400, + "Bad Request", + json!({ "error": "tab_id must be an integer" }), + ); + }; + + let result = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned")) + .and_then(|mut runtime| runtime.activate_shared_tab_from_panel(tab_id)); + match result { + Ok(value) => json_response(200, "OK", value), + Err(error) => json_response(400, "Bad Request", json!({ "error": error.to_string() })), + } +} + +fn recording_response(runtime: Arc>, action: &str) -> HttpResponse { + let result = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned")) + .and_then(|runtime| match action { + "state" => runtime.shared_recording_state_from_panel(), + "start" => runtime.start_shared_recording_from_panel(), + "record" => runtime.set_shared_recording_mode_from_panel("record"), + "inspect" => runtime.set_shared_recording_mode_from_panel("inspect"), + "stop" => runtime.stop_shared_recording_from_panel(), + "clear" => runtime.clear_shared_recording_from_panel(), + "play" => runtime.play_shared_recording_from_panel(), + _ => Err(anyhow!("unknown recording action")), + }); + match result { + Ok(value) => json_response(200, "OK", value), + Err(error) => json_response(400, "Bad Request", json!({ "error": error.to_string() })), + } +} + +fn select_browser_response(runtime: Arc>, request: &HttpRequest) -> HttpResponse { + let Some(name) = + query_param(&request.target, "name").or_else(|| query_param(&request.body, "name")) + else { + return json_response(400, "Bad Request", json!({ "error": "name is required" })); + }; + + let result = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned")) + .and_then(|mut runtime| runtime.select_browser(&name, None, None, None, None)); + match result { + Ok(text) => { + let value = serde_json::from_str::(&text) + .unwrap_or_else(|_| json!({ "selected": name })); + json_response(200, "OK", value) + } + Err(error) => json_response(400, "Bad Request", json!({ "error": error.to_string() })), + } +} + +fn register_share_response(runtime: Arc>, request: &HttpRequest) -> HttpResponse { + let Some(name) = + query_param(&request.target, "name").or_else(|| query_param(&request.body, "name")) + else { + return json_response(400, "Bad Request", json!({ "error": "name is required" })); + }; + let Some(share_url) = query_param(&request.target, "share_url") + .or_else(|| query_param(&request.body, "share_url")) + else { + return json_response( + 400, + "Bad Request", + json!({ "error": "share_url is required" }), + ); + }; + + let result = runtime + .lock() + .map_err(|_| anyhow!("MCP runtime lock was poisoned")) + .and_then(|mut runtime| runtime.select_browser(&name, None, None, None, Some(&share_url))); + match result { + Ok(text) => { + let value = serde_json::from_str::(&text) + .unwrap_or_else(|_| json!({ "selected": name })); + json_response(200, "OK", value) + } + Err(error) => json_response(400, "Bad Request", json!({ "error": error.to_string() })), + } +} + +fn query_param(target: &str, name: &str) -> Option { + let query = target + .split_once('?') + .map(|(_, query)| query) + .unwrap_or(target); + query.split('&').find_map(|part| { + let (key, value) = part.split_once('=')?; + (url_decode(key) == name).then(|| url_decode(value)) + }) +} + +fn url_decode(value: &str) -> String { + let mut decoded = Vec::with_capacity(value.len()); + let bytes = value.as_bytes(); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'+' => decoded.push(b' '), + b'%' if index + 2 < bytes.len() => { + if let (Some(high), Some(low)) = + (hex_value(bytes[index + 1]), hex_value(bytes[index + 2])) + { + decoded.push(high * 16 + low); + index += 2; + } else { + decoded.push(bytes[index]); + } + } + byte => decoded.push(byte), + } + index += 1; + } + String::from_utf8_lossy(&decoded).to_string() +} + +fn hex_value(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +fn write_http_response(stream: &mut TcpStream, response: HttpResponse) -> Result<()> { + write!( + stream, + "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n", + response.status, + response.reason, + response.content_type, + response.body.len() + ) + .context("failed to write control panel HTTP response headers")?; + stream + .write_all(&response.body) + .context("failed to write control panel HTTP response body")?; + stream + .flush() + .context("failed to flush control panel HTTP response") +} + +fn empty_response(status: u16, reason: &'static str) -> HttpResponse { + HttpResponse { + status, + reason, + content_type: "text/plain; charset=utf-8", + body: Vec::new(), + } +} + +fn html_response(html: String) -> HttpResponse { + HttpResponse { + status: 200, + reason: "OK", + content_type: "text/html; charset=utf-8", + body: html.into_bytes(), + } +} + +fn json_response(status: u16, reason: &'static str, value: Value) -> HttpResponse { + let body = + serde_json::to_vec_pretty(&value).unwrap_or_else(|_| b"{\"error\":\"json\"}".to_vec()); + HttpResponse { + status, + reason, + content_type: "application/json; charset=utf-8", + body, + } +} + +fn generate_control_token() -> Result { + let mut bytes = [0_u8; 32]; + File::open("/dev/urandom") + .context("failed to open /dev/urandom for control panel token")? + .read_exact(&mut bytes) + .context("failed to read control panel token bytes")?; + let mut token = String::with_capacity(bytes.len() * 2); + for byte in bytes { + write!(&mut token, "{byte:02x}").expect("writing to a String cannot fail"); + } + Ok(token) +} + +fn load_or_create_control_token(project_id: &str) -> Result { + let path = control_token_path(project_id); + if let Ok(token) = fs::read_to_string(&path) { + let token = token.trim(); + if is_control_token(token) { + return Ok(token.to_string()); + } + } + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("failed to create {}", parent.display()))?; + } + let token = generate_control_token()?; + let mut options = OpenOptions::new(); + options.create(true).write(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options + .open(&path) + .with_context(|| format!("failed to write {}", path.display()))?; + file.write_all(token.as_bytes()) + .with_context(|| format!("failed to write {}", path.display()))?; + Ok(token) +} + +fn is_control_token(token: &str) -> bool { + token.len() == 64 && token.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn control_token_path(project_id: &str) -> PathBuf { + runtime_state_dir().join(format!( + "{}.control-token", + runtime_state_file_stem(project_id) + )) +} + +fn runtime_state_dir() -> PathBuf { + env::var_os("BROWSER_CONNECTION_STATE_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| env::temp_dir().join("browser-connection")) +} + +fn runtime_state_file_stem(project_id: &str) -> String { + let stem = project_id + .chars() + .map(|ch| { + if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') { + ch + } else { + '_' + } + }) + .collect::(); + if stem.is_empty() { + "default".to_string() + } else { + stem + } +} + +fn escape_js_string(value: &str) -> String { + value + .chars() + .flat_map(|ch| match ch { + '\\' => "\\\\".chars().collect::>(), + '"' => "\\\"".chars().collect(), + '\n' => "\\n".chars().collect(), + '\r' => "\\r".chars().collect(), + '<' => "\\u003c".chars().collect(), + '>' => "\\u003e".chars().collect(), + '&' => "\\u0026".chars().collect(), + _ => vec![ch], + }) + .collect() +} + +fn control_panel_html(control_token: &str, project_id: &str) -> String { + include_str!("control_panel.html") + .replace( + "__PERSONAL_BROWSER_NAME__", + &escape_js_string(PERSONAL_BROWSER_NAME), + ) + .replace("__PROJECT_ID__", &escape_js_string(project_id)) + .replace("__CONTROL_TOKEN__", &escape_js_string(control_token)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn query_param_decodes_names() { + assert_eq!( + query_param("/api/select?name=personal+browser", "name").as_deref(), + Some("personal browser") + ); + assert_eq!( + query_param("/api/select?name=work%2Dbrowser", "name").as_deref(), + Some("work-browser") + ); + } + + #[test] + fn validates_control_token_from_header() { + let request = parse_http_request( + b"POST /api/share HTTP/1.1\r\nX-Browser-Control-Token: secret\r\nContent-Length: 0\r\n\r\n", + ) + .expect("request parses"); + + assert!(has_valid_control_token(&request, "secret")); + assert!(!has_valid_control_token(&request, "other")); + } +} diff --git a/src/mcp/tests.rs b/src/mcp/tests.rs new file mode 100644 index 0000000..fa8d00f --- /dev/null +++ b/src/mcp/tests.rs @@ -0,0 +1,451 @@ +use super::*; +use serde_json::{json, Value}; +use std::fs; +use std::io::Cursor; + +fn encode_message(value: Value) -> Vec { + let body = serde_json::to_vec(&value).expect("message body serializes"); + let mut framed = format!("Content-Length: {}\r\n\r\n", body.len()).into_bytes(); + framed.extend_from_slice(&body); + framed +} + +fn decode_messages(bytes: &[u8]) -> Vec { + let mut cursor = Cursor::new(bytes); + let mut responses = Vec::new(); + + let mut transport = Some(StdioTransport::Framed); + while let Some(message) = + read_message(&mut cursor, &mut transport).expect("stdout frame parses") + { + responses.push(serde_json::from_str(&message).expect("stdout frame body is JSON")); + } + + responses +} + +fn decode_line_messages(bytes: &[u8]) -> Vec { + let text = String::from_utf8(bytes.to_vec()).expect("stdout lines are utf8"); + text.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).expect("stdout line is JSON")) + .collect() +} + +#[test] +fn env_fallback_prefers_explicit_project() { + assert_eq!( + project_id_from_env_or_default(Some(" dg-x ".to_string())), + "dg-x" + ); +} + +#[test] +fn stdio_initialize_and_list_use_framed_mcp_transport() { + let config = McpServerConfig::new("dg-test", None, None, false); + let mut input = Vec::new(); + input.extend(encode_message(json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": MCP_PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": { "name": "probe", "version": "0" } + } + }))); + input.extend(encode_message(json!({ + "jsonrpc": "2.0", + "method": "notifications/initialized", + "params": {} + }))); + input.extend(encode_message(json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/list", + "params": {} + }))); + + let input = Cursor::new(input); + let mut output = Vec::new(); + + run_stdio(config, input, &mut output).expect("stdio loop succeeds"); + + let responses = decode_messages(&output); + assert_eq!(responses.len(), 2); + assert_eq!(responses[0]["id"], 1); + assert_eq!(responses[0]["result"]["serverInfo"]["name"], SERVER_NAME); + assert_eq!(responses[1]["id"], 2); + assert!(responses[1]["result"]["tools"] + .as_array() + .expect("tools/list returns an array") + .iter() + .any(|tool| tool["name"] == "browser_navigate")); +} + +#[test] +fn stdio_initialize_and_list_use_line_delimited_transport() { + let config = McpServerConfig::new("dg-test", None, None, false); + let input = Cursor::new( + [ + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"elicitation":{}},"clientInfo":{"name":"codex-mcp-client","version":"0"}}}"#, + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#, + ] + .join("\n"), + ); + let mut output = Vec::new(); + + run_stdio(config, input, &mut output).expect("stdio loop succeeds"); + + let responses = decode_line_messages(&output); + assert_eq!(responses.len(), 2); + assert_eq!(responses[0]["id"], 1); + assert_eq!(responses[0]["result"]["protocolVersion"], "2025-06-18"); + assert_eq!(responses[1]["id"], 2); + assert!(responses[1]["result"]["tools"] + .as_array() + .expect("tools/list returns an array") + .iter() + .any(|tool| tool["name"] == "browser_navigate")); +} + +#[test] +fn initialize_and_tools_list_do_not_resolve_cdp_endpoint() { + let config = McpServerConfig::new("dg-test", None, None, true); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#, + ) + .expect("initialize succeeds"); + handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#, + ) + .expect("tools/list succeeds"); + + assert_eq!(runtime.managed_cdp_endpoint, None); + assert_eq!(runtime.active_browser, MANAGED_BROWSER_NAME); +} + +#[test] +fn initialize_negotiates_legacy_protocol_version() { + let config = McpServerConfig::new("dg-test", None, None, false); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}}"#, + ) + .expect("initialize succeeds") + .expect("request with id returns a response"); + + assert_eq!(response["result"]["protocolVersion"], "2024-11-05"); + assert_eq!( + response["result"]["capabilities"]["tools"]["listChanged"], + false + ); +} + +#[test] +fn initialize_negotiates_latest_protocol_version() { + let config = McpServerConfig::new("dg-test", None, None, false); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"roots":{"listChanged":true}},"clientInfo":{"name":"claude-code","version":"2.1.160"}}}"#, + ) + .expect("initialize succeeds") + .expect("request with id returns a response"); + + assert_eq!(response["result"]["protocolVersion"], "2025-11-25"); +} + +#[test] +fn initialize_negotiates_previous_protocol_version() { + let config = McpServerConfig::new("dg-test", None, None, false); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"elicitation":{}},"clientInfo":{"name":"codex-mcp-client","version":"0"}}}"#, + ) + .expect("initialize succeeds") + .expect("request with id returns a response"); + + assert_eq!(response["result"]["protocolVersion"], "2025-06-18"); +} + +#[test] +fn initialize_rejects_unknown_protocol_version() { + let config = McpServerConfig::new("dg-test", None, None, false); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2099-01-01","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}}"#, + ) + .expect("initialize response serializes") + .expect("request with id returns a response"); + + assert_eq!(response["error"]["code"], -32602); + assert!(response["error"]["message"] + .as_str() + .expect("error message exists") + .contains("Unsupported MCP protocol version")); +} + +#[test] +fn tools_call_resolves_cdp_endpoint_lazily() { + let config = McpServerConfig::new("dg-test", None, None, false); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + let expected_cdp_url = crate::render_cdp_url(); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"unknown","arguments":{}}}"#, + ) + .expect("tools/call response serializes") + .expect("request with id returns a response"); + + assert_eq!( + runtime.managed_cdp_endpoint.as_deref(), + Some(expected_cdp_url.as_str()) + ); + assert_eq!(response["id"], 3); + assert_eq!(response["result"]["isError"], true); + assert!(response["result"]["content"][0]["text"] + .as_str() + .expect("tool result text exists") + .contains("Unknown browser-connection tool")); +} + +#[test] +fn configured_personal_browser_can_be_active_without_docker() { + let config = McpServerConfig::new("dg-test", None, None, true) + .with_browser_endpoints(vec![NamedBrowserEndpoint::new( + PERSONAL_BROWSER_NAME, + "http://127.0.0.1:9333", + ) + .expect("endpoint is valid")]) + .with_active_browser(Some(PERSONAL_BROWSER_NAME.to_string())) + .expect("active browser name is valid"); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + assert_eq!( + runtime.cdp_endpoint().expect("personal endpoint resolves"), + "http://127.0.0.1:9333" + ); + assert_eq!(runtime.managed_cdp_endpoint, None); +} + +#[test] +fn browser_select_registers_ad_hoc_personal_endpoint_without_resolving_managed_browser() { + let config = McpServerConfig::new("dg-test", None, None, true); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"browser_select","arguments":{"name":"personal","cdp_endpoint":"http://127.0.0.1:9444"}}}"#, + ) + .expect("browser_select response serializes") + .expect("request with id returns a response"); + + assert_eq!(response["id"], 4); + assert_eq!(response["result"]["isError"], false); + assert_eq!(runtime.active_browser, PERSONAL_BROWSER_NAME); + assert_eq!(runtime.managed_cdp_endpoint, None); + assert_eq!( + runtime.cdp_endpoint().expect("personal endpoint resolves"), + "http://127.0.0.1:9444" + ); +} + +#[test] +fn browser_select_registers_personal_display_metadata_without_docker_when_novnc_url_exists() { + let config = McpServerConfig::new("dg-test", None, None, true); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let response = handle_message( + &mut runtime, + r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"browser_select","arguments":{"name":"personal","cdp_endpoint":"http://127.0.0.1:9444","vnc_endpoint":"host.docker.internal:5900","novnc_url":"http://127.0.0.1:6680/vnc.html"}}}"#, + ) + .expect("browser_select response serializes") + .expect("request with id returns a response"); + + assert_eq!(response["result"]["isError"], false); + let text = response["result"]["content"][0]["text"] + .as_str() + .expect("tool result text exists"); + let selection: Value = serde_json::from_str(text).expect("selection text is JSON"); + assert_eq!( + selection["browser"]["vncEndpoint"], + "host.docker.internal:5900" + ); + assert_eq!( + selection["browser"]["novncUrl"], + "http://127.0.0.1:6680/vnc.html" + ); + assert_eq!(runtime.managed_cdp_endpoint, None); +} + +#[test] +fn browser_list_reports_active_personal_browser() { + let config = McpServerConfig::new("dg-test", None, None, false) + .with_browser_endpoints(vec![NamedBrowserEndpoint::new( + PERSONAL_BROWSER_NAME, + "http://127.0.0.1:9222", + ) + .expect("endpoint is valid")]) + .with_active_browser(Some(PERSONAL_BROWSER_NAME.to_string())) + .expect("active browser name is valid"); + let runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let inventory = runtime.browser_inventory().expect("inventory renders"); + + assert_eq!(inventory["active"], PERSONAL_BROWSER_NAME); + assert!(inventory["browsers"] + .as_array() + .expect("browsers array") + .iter() + .any(|browser| { + browser["name"] == PERSONAL_BROWSER_NAME + && browser["kind"] == "personal" + && browser["active"] == true + })); +} + +#[test] +fn browser_list_reports_active_shared_browser_without_cdp() { + let config = McpServerConfig::new("dg-test", None, None, false) + .with_browser_share_url("edge", "https://relay.example/share/s1#agent=a1") + .expect("share URL is valid") + .with_active_browser(Some("edge".to_string())) + .expect("active browser name is valid"); + let runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let inventory = runtime.browser_inventory().expect("inventory renders"); + + assert_eq!(inventory["active"], "edge"); + assert!(inventory["browsers"] + .as_array() + .expect("browsers array") + .iter() + .any(|browser| { + browser["name"] == "edge" + && browser["kind"] == "shared-extension" + && browser["shareUrl"] == "https://relay.example/share/s1#agent=a1" + && browser["active"] == true + })); +} + +#[test] +fn browser_list_reports_control_panel_url_when_enabled() { + let config = McpServerConfig::new("dg-test", None, None, false).with_control_port(Some(6888)); + let runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let inventory = runtime.browser_inventory().expect("inventory renders"); + + assert_eq!(inventory["controlPanelUrl"], "http://127.0.0.1:6888/"); +} + +#[test] +fn runtime_restores_panel_selected_shared_browser_from_state_file() { + let project = format!( + "dg-test-persist-{}-{}", + std::process::id(), + activity::now_ms() + ); + let config = McpServerConfig::new(&project, None, None, false).with_control_port(Some(6888)); + let mut runtime = McpRuntime::new(config).expect("runtime config is valid"); + + runtime + .select_browser( + "edge", + None, + None, + None, + Some("https://relay.example/share/s1#agent=a1"), + ) + .expect("shared browser selection persists"); + + let restored = McpRuntime::new( + McpServerConfig::new(&project, None, None, false).with_control_port(Some(6888)), + ) + .expect("runtime restores persisted shared browser"); + let inventory = restored.browser_inventory().expect("inventory renders"); + + assert_eq!(inventory["active"], "edge"); + assert!(inventory["browsers"] + .as_array() + .expect("browsers array") + .iter() + .any(|browser| { + browser["name"] == "edge" + && browser["kind"] == "shared-extension" + && browser["shareUrl"] == "https://relay.example/share/s1#agent=a1" + && browser["active"] == true + })); + + let _ = fs::remove_file(runtime_state_path(&project)); +} + +#[test] +fn browser_list_reports_null_control_panel_url_when_disabled() { + let config = McpServerConfig::new("dg-test", None, None, false); + let runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let inventory = runtime.browser_inventory().expect("inventory renders"); + + assert!(inventory["controlPanelUrl"].is_null()); +} + +#[test] +fn browser_list_reports_personal_vnc_and_deterministic_novnc_url_without_docker() { + let config = McpServerConfig::new("dg-test", None, None, false).with_browser_endpoints(vec![ + NamedBrowserEndpoint::new(PERSONAL_BROWSER_NAME, "http://127.0.0.1:9222") + .expect("endpoint is valid") + .with_vnc_endpoint("host.docker.internal:5900") + .expect("vnc endpoint is valid"), + ]); + let runtime = McpRuntime::new(config).expect("runtime config is valid"); + + let inventory = runtime.browser_inventory().expect("inventory renders"); + + let personal = inventory["browsers"] + .as_array() + .expect("browsers array") + .iter() + .find(|browser| browser["name"] == PERSONAL_BROWSER_NAME) + .expect("personal browser is listed"); + assert_eq!(personal["vncEndpoint"], "host.docker.internal:5900"); + assert_eq!( + personal["novncUrl"], + crate::render_browser_target_novnc_url("dg-test", PERSONAL_BROWSER_NAME) + ); + assert_eq!(runtime.managed_cdp_endpoint, None); +} + +#[test] +fn invalid_active_browser_fails_runtime_creation() { + let config = McpServerConfig::new("dg-test", None, None, false) + .with_active_browser(Some("personal".to_string())) + .expect("active browser name normalizes"); + + let error = McpRuntime::new(config).expect_err("unknown active browser fails"); + + assert!(error.to_string().contains("Unknown browser `personal`")); +} + +#[test] +fn malformed_explicit_cdp_endpoint_fails_runtime_creation() { + let config = McpServerConfig::new("dg-test", None, Some("127.0.0.1:9222".to_string()), false); + + let error = McpRuntime::new(config).expect_err("malformed explicit endpoint fails"); + + assert!(error + .to_string() + .contains("must start with http:// or https://")); +} diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs new file mode 100644 index 0000000..07b4702 --- /dev/null +++ b/src/mcp/tools.rs @@ -0,0 +1,147 @@ +use super::activity; +use super::McpRuntime; +use crate::browser_actions::{command_from_browser_tool, dispatch_browser_command, BrowserTarget}; +use anyhow::{anyhow, Result}; +use serde_json::{json, Value}; + +pub(super) fn tool_definitions() -> Vec { + vec![ + tool( + "browser_list", + "List available browser targets and show which target is active.", + json!({}), + vec![], + ), + tool( + "browser_select", + "Switch the active browser target by name, optionally registering CDP and display endpoints first.", + json!({ + "name": { "type": "string", "description": "Browser target name, e.g. managed or personal" }, + "cdp_endpoint": { "type": "string", "description": "Optional CDP endpoint to register for this browser name" }, + "vnc_endpoint": { "type": "string", "description": "Optional VNC endpoint to register as HOST:PORT" }, + "novnc_url": { "type": "string", "description": "Optional pre-existing noVNC URL for this browser name" }, + "share_url": { "type": "string", "description": "Optional shared browser extension link for this browser name" } + }), + vec!["name"], + ), + tool( + "browser_navigate", + "Navigate the active browser page to a URL through the Rust CDP adapter.", + json!({ "url": { "type": "string", "description": "Absolute URL to open" } }), + vec!["url"], + ), + tool( + "browser_snapshot", + "Return page title, URL, visible text and simple interactive element selectors.", + json!({}), + vec![], + ), + tool( + "browser_evaluate", + "Evaluate JavaScript in the current page and return a JSON/text result.", + json!({ "expression": { "type": "string", "description": "JavaScript expression" } }), + vec!["expression"], + ), + tool( + "browser_click", + "Click an element by CSS selector in the current page.", + json!({ "selector": { "type": "string", "description": "CSS selector" } }), + vec!["selector"], + ), + tool( + "browser_type", + "Set text in an input-like element by CSS selector and dispatch input/change events.", + json!({ + "selector": { "type": "string", "description": "CSS selector" }, + "text": { "type": "string", "description": "Text to type" } + }), + vec!["selector", "text"], + ), + tool( + "browser_press_key", + "Press a key through CDP Input.dispatchKeyEvent.", + json!({ "key": { "type": "string", "description": "Key name, e.g. Enter or a" } }), + vec!["key"], + ), + tool( + "browser_take_screenshot", + "Capture a PNG screenshot and return it as a data URL.", + json!({ "full_page": { "type": "boolean", "description": "Capture beyond viewport", "default": true } }), + vec![], + ), + tool( + "browser_list_tabs", + "List tabs and windows visible to the active shared browser extension.", + json!({}), + vec![], + ), + tool( + "browser_activate_tab", + "Activate a tab in the active shared browser extension.", + json!({ "tab_id": { "type": "integer", "description": "Chrome tab id to activate" } }), + vec!["tab_id"], + ), + ] +} + +fn tool(name: &str, description: &str, properties: Value, required: Vec<&str>) -> Value { + json!({ + "name": name, + "description": description, + "inputSchema": { + "type": "object", + "properties": properties, + "required": required + } + }) +} + +pub(super) fn handle_tool_call(runtime: &mut McpRuntime, request: &Value) -> Value { + let params = request.get("params").unwrap_or(&Value::Null); + let name = params.get("name").and_then(Value::as_str).unwrap_or(""); + let arguments = params.get("arguments").unwrap_or(&Value::Null); + let started_at_ms = activity::now_ms(); + + let result = match name { + "browser_list" => runtime.browser_inventory_text(), + "browser_select" => runtime.select_browser( + required_str(arguments, "name").unwrap_or(""), + arguments.get("cdp_endpoint").and_then(Value::as_str), + arguments.get("vnc_endpoint").and_then(Value::as_str), + arguments.get("novnc_url").and_then(Value::as_str), + arguments.get("share_url").and_then(Value::as_str), + ), + _ => runtime.ensure_active_display().and_then(|_| { + let target = if let Some(share_url) = runtime.active_share_url() { + BrowserTarget::shared(share_url) + } else { + BrowserTarget::cdp(runtime.cdp_endpoint()?) + }; + let command = command_from_browser_tool(name, arguments)?; + dispatch_browser_command(&target, &command) + }), + }; + + runtime.record_tool_activity(name, arguments, started_at_ms, &result); + + match result { + Ok(text) => tool_result(text, false), + Err(error) => tool_result(format!("{error:#}"), true), + } +} + +fn tool_result(text: String, is_error: bool) -> Value { + json!({ + "content": [{ "type": "text", "text": text }], + "isError": is_error + }) +} + +fn required_str<'a>(arguments: &'a Value, name: &str) -> Result<&'a str> { + arguments + .get(name) + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| anyhow!("argument `{name}` is required")) +} diff --git a/src/shared_browser.rs b/src/shared_browser.rs new file mode 100644 index 0000000..8b2d5e3 --- /dev/null +++ b/src/shared_browser.rs @@ -0,0 +1,985 @@ +/*! Bounded WebSocket relay for browser share sessions. + +CHANGE: pair browser-extension clients and agent clients through an outbound-friendly relay. +WHY: remote browsers need simple share links without exposing CDP/VNC ports. +PURITY: SHELL +EFFECT: listens for WebSocket clients and forwards bounded JSON messages by request id. +INVARIANT: browser clients register sessions; agent clients must present the matching agent token. +*/ + +use anyhow::{anyhow, Context, Result}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::io::ErrorKind; +use std::net::{TcpListener, TcpStream}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread; +use std::time::Duration; +use tungstenite::handshake::server::{Callback, ErrorResponse, Request, Response}; +use tungstenite::protocol::WebSocketConfig; +use tungstenite::stream::MaybeTlsStream; +use tungstenite::{accept_hdr_with_config, connect, Error as WsError, Message, WebSocket}; + +pub const DEFAULT_RELAY_BIND: &str = "127.0.0.1:8765"; +pub const MAX_SESSION_ID_BYTES: usize = 128; +pub const MAX_TOKEN_BYTES: usize = 512; +pub const MAX_JSON_MESSAGE_BYTES: usize = 8 * 1024 * 1024; +pub const MAX_SESSIONS: usize = 1024; +pub const SHARED_BROWSER_COMMAND_TIMEOUT: Duration = Duration::from_secs(10); +pub const SHARED_BROWSER_PLAYWRIGHT_TIMEOUT: Duration = Duration::from_secs(120); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RelayConfig { + pub bind: String, +} + +impl RelayConfig { + pub fn new(bind: impl Into) -> Self { + Self { bind: bind.into() } + } +} + +impl Default for RelayConfig { + fn default() -> Self { + Self::new(DEFAULT_RELAY_BIND) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShareAgentUrl { + pub session: String, + pub agent_token: String, + pub websocket_url: String, +} + +pub fn parse_share_agent_url(input: &str) -> Result { + let input = input.trim(); + let (scheme, rest) = input + .split_once("://") + .ok_or_else(|| anyhow!("share URL must include http:// or https:// scheme"))?; + let websocket_scheme = match scheme { + "http" | "ws" => "ws", + "https" | "wss" => "wss", + _ => return Err(anyhow!("share URL scheme must be http, https, ws, or wss")), + }; + if (input.starts_with("ws://") || input.starts_with("wss://")) && input.contains("/ws/agent/") { + let endpoint = + RelayEndpoint::parse(rest.split_once('/').map(|(_, path)| path).unwrap_or(rest))?; + if let RelayEndpoint::Agent { + session, + agent_token, + } = endpoint + { + return Ok(ShareAgentUrl { + session, + agent_token, + websocket_url: input.to_string(), + }); + } + } + + let (without_fragment, fragment) = input + .split_once('#') + .ok_or_else(|| anyhow!("share URL must include #agent= fragment"))?; + let agent_token = query_param(fragment, "agent") + .ok_or_else(|| anyhow!("share URL fragment must include agent token"))?; + let rest = without_fragment + .split_once("://") + .map(|(_, rest)| rest) + .unwrap_or(rest); + let (authority, path_and_query) = rest + .split_once('/') + .ok_or_else(|| anyhow!("share URL must include /share/ path"))?; + if authority.trim().is_empty() { + return Err(anyhow!("share URL host is required")); + } + let (path, query) = path_and_query + .split_once('?') + .unwrap_or((path_and_query, "")); + let session = parse_share_path(path)?; + let agent_token = query_param(fragment, "agent") + .or_else(|| query_param(query, "agent")) + .unwrap_or(agent_token); + let agent_token = validate_token("agent token", &agent_token)?; + let websocket_url = + format!("{websocket_scheme}://{authority}/ws/agent/{session}?token={agent_token}"); + + Ok(ShareAgentUrl { + session, + agent_token, + websocket_url, + }) +} + +pub fn agent_ws_url_from_share_url(input: &str) -> Result { + Ok(parse_share_agent_url(input)?.websocket_url) +} + +pub fn agent_websocket_url_from_share_url(input: &str) -> Result { + agent_ws_url_from_share_url(input) +} + +pub fn run_relay(config: RelayConfig) -> Result<()> { + let listener = TcpListener::bind(&config.bind) + .with_context(|| format!("failed to bind browser share relay on {}", config.bind))?; + serve_listener(listener) +} + +pub fn serve_listener(listener: TcpListener) -> Result<()> { + let relay = BrowserShareRelay::new(); + for stream in listener.incoming() { + match stream { + Ok(stream) => { + let relay = relay.clone(); + thread::Builder::new() + .name("browser-share-relay-client".to_string()) + .spawn(move || { + let _ = relay.handle_stream(stream); + }) + .context("failed to spawn relay client thread")?; + } + Err(error) => return Err(error).context("failed to accept relay TCP connection"), + } + } + Ok(()) +} + +#[derive(Debug, Clone)] +pub struct BrowserShareRelay { + state: SharedRelayState, +} + +impl BrowserShareRelay { + pub fn new() -> Self { + Self { + state: Arc::new(RelayState::default()), + } + } + + pub fn handle_stream(&self, stream: TcpStream) -> Result<()> { + handle_client(Arc::clone(&self.state), stream) + } +} + +impl Default for BrowserShareRelay { + fn default() -> Self { + Self::new() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SharedBrowserClient { + share_url: String, +} + +impl SharedBrowserClient { + pub fn new(share_url: impl Into) -> Self { + Self { + share_url: share_url.into(), + } + } + + pub fn navigate(&self, url: &str) -> Result { + self.call_text("navigate", json!({ "url": url })) + } + + pub fn snapshot(&self) -> Result { + self.call_text("snapshot", json!({})) + } + + pub fn evaluate(&self, expression: &str) -> Result { + self.call_text("evaluate", json!({ "expression": expression })) + } + + pub fn click(&self, selector: &str) -> Result { + self.call_text("click", json!({ "selector": selector })) + } + + pub fn type_text(&self, selector: &str, text: &str) -> Result { + self.call_text("type", json!({ "selector": selector, "text": text })) + } + + pub fn press_key(&self, key: &str) -> Result { + self.call_text("press_key", json!({ "key": key })) + } + + pub fn screenshot(&self, full_page: bool) -> Result { + self.call_text("screenshot", json!({ "fullPage": full_page })) + } + + pub fn list_tabs(&self) -> Result { + self.call("list_tabs", json!({})) + } + + pub fn activate_tab(&self, tab_id: i64) -> Result { + self.call_text("activate_tab", json!({ "tabId": tab_id })) + } + + pub fn recording_state(&self) -> Result { + self.call("recording_state", json!({})) + } + + pub fn start_recording(&self) -> Result { + self.call("start_recording", json!({})) + } + + pub fn set_recording_mode(&self, mode: &str) -> Result { + self.call("set_recording_mode", json!({ "mode": mode })) + } + + pub fn stop_recording(&self) -> Result { + self.call("stop_recording", json!({})) + } + + pub fn clear_recording(&self) -> Result { + self.call("clear_recording", json!({})) + } + + pub fn play_recording(&self) -> Result { + self.call("play_recording", json!({})) + } + + pub fn run_playwright(&self, code: &str, allow_close: bool) -> Result { + self.call_with_timeout( + "run_playwright", + json!({ + "code": code, + "allowClose": allow_close, + "timeoutMs": SHARED_BROWSER_PLAYWRIGHT_TIMEOUT.as_millis() as u64 + }), + SHARED_BROWSER_PLAYWRIGHT_TIMEOUT, + ) + } + + pub fn call_command(&self, command: &str, params: Value) -> Result { + self.call(command, params) + } + + fn call_text(&self, command: &str, params: Value) -> Result { + let result = self.call(command, params)?; + if let Some(text) = result.as_str() { + return Ok(text.to_string()); + } + serde_json::to_string_pretty(&result).context("failed to render shared browser response") + } + + fn call(&self, command: &str, params: Value) -> Result { + self.call_with_timeout(command, params, SHARED_BROWSER_COMMAND_TIMEOUT) + } + + fn call_with_timeout(&self, command: &str, params: Value, timeout: Duration) -> Result { + let websocket_url = agent_ws_url_from_share_url(&self.share_url)?; + let (mut socket, _) = connect(&websocket_url).with_context(|| { + format!("failed to connect to shared browser relay {websocket_url}") + })?; + set_agent_socket_timeouts(&mut socket, timeout); + let request = json!({ "id": 1, "command": command, "params": params }); + socket + .send(Message::Text(request.to_string())) + .with_context(|| format!("failed to send shared browser command {command}"))?; + + loop { + match socket + .read() + .with_context(|| format!("failed to read shared browser response for {command}"))? + { + Message::Text(text) => { + let value: Value = serde_json::from_str(&text).with_context(|| { + format!("shared browser response for {command} was not JSON") + })?; + if value.get("id").and_then(Value::as_i64) != Some(1) { + continue; + } + if value.get("ok").and_then(Value::as_bool) == Some(false) { + let error = value + .get("error") + .and_then(Value::as_str) + .unwrap_or("shared browser command failed"); + return Err(anyhow!("{error}")); + } + return Ok(value.get("result").cloned().unwrap_or(Value::Null)); + } + Message::Ping(payload) => { + socket + .send(Message::Pong(payload)) + .context("failed to answer shared browser relay ping")?; + } + Message::Close(_) => { + return Err(anyhow!( + "shared browser relay closed before {command} response" + )) + } + _ => {} + } + } + } +} + +fn set_agent_socket_timeouts(socket: &mut WebSocket>, timeout: Duration) { + let stream = socket.get_mut(); + match stream { + MaybeTlsStream::Plain(stream) => { + let _ = stream.set_read_timeout(Some(timeout)); + let _ = stream.set_write_timeout(Some(timeout)); + } + MaybeTlsStream::NativeTls(stream) => { + let stream = stream.get_mut(); + let _ = stream.set_read_timeout(Some(timeout)); + let _ = stream.set_write_timeout(Some(timeout)); + } + _ => {} + } +} + +type SharedRelayState = Arc; + +#[derive(Debug, Default)] +struct RelayState { + sessions: Mutex>, + next_connection_id: AtomicU64, +} + +#[derive(Debug)] +struct RelaySession { + browser_token: String, + agent_token: String, + browser: Option, + agents: HashMap, + pending_agent_requests: HashMap, +} + +#[derive(Debug, Clone)] +struct PeerHandle { + connection_id: u64, + tx: mpsc::Sender, +} + +#[derive(Debug, Clone)] +struct PendingAgentRequest { + connection_id: u64, + original_id: Value, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PeerRole { + Browser, + Agent, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum RelayEndpoint { + Browser { + session: String, + browser_token: String, + agent_token: String, + }, + Agent { + session: String, + agent_token: String, + }, +} + +impl RelayState { + fn register( + &self, + endpoint: &RelayEndpoint, + tx: mpsc::Sender, + ) -> Result<(String, PeerRole, u64)> { + let connection_id = self.next_connection_id.fetch_add(1, Ordering::Relaxed) + 1; + let mut sessions = self + .sessions + .lock() + .map_err(|_| anyhow!("relay session lock was poisoned"))?; + match endpoint { + RelayEndpoint::Browser { + session, + browser_token, + agent_token, + } => { + if !sessions.contains_key(session) && sessions.len() >= MAX_SESSIONS { + return Err(anyhow!("relay session limit reached")); + } + let session_entry = + sessions + .entry(session.clone()) + .or_insert_with(|| RelaySession { + browser_token: browser_token.clone(), + agent_token: agent_token.clone(), + browser: None, + agents: HashMap::new(), + pending_agent_requests: HashMap::new(), + }); + if session_entry.browser_token != *browser_token { + return Err(anyhow!("browser token did not match session")); + } + if session_entry.agent_token != *agent_token { + return Err(anyhow!("agent token did not match session")); + } + session_entry.browser = Some(PeerHandle { connection_id, tx }); + Ok((session.clone(), PeerRole::Browser, connection_id)) + } + RelayEndpoint::Agent { + session, + agent_token, + } => { + let session_entry = sessions + .get_mut(session) + .ok_or_else(|| anyhow!("relay session is not registered"))?; + if session_entry.agent_token != *agent_token { + return Err(anyhow!("agent token did not match session")); + } + session_entry + .agents + .insert(connection_id, PeerHandle { connection_id, tx }); + Ok((session.clone(), PeerRole::Agent, connection_id)) + } + } + } + + fn unregister(&self, session: &str, role: PeerRole, connection_id: u64) { + let Ok(mut sessions) = self.sessions.lock() else { + return; + }; + let Some(session_entry) = sessions.get_mut(session) else { + return; + }; + match role { + PeerRole::Browser => { + if session_entry + .browser + .as_ref() + .is_some_and(|peer| peer.connection_id == connection_id) + { + sessions.remove(session); + } + } + PeerRole::Agent => { + session_entry.agents.remove(&connection_id); + session_entry + .pending_agent_requests + .retain(|_, pending| pending.connection_id != connection_id); + } + } + } + + fn route_message( + &self, + session: &str, + from: PeerRole, + connection_id: u64, + raw_message: &str, + ) -> Result<()> { + let mut message = match validate_relay_json_message(from, raw_message)? { + Some(message) => message, + None => return Ok(()), + }; + let mut sessions = self + .sessions + .lock() + .map_err(|_| anyhow!("relay session lock was poisoned"))?; + let session_entry = sessions + .get(session) + .ok_or_else(|| anyhow!("relay session is not registered"))?; + match from { + PeerRole::Agent => { + if !session_entry.agents.contains_key(&connection_id) { + return Err(anyhow!("relay sender connection is stale")); + } + } + PeerRole::Browser => { + let sender = session_entry + .browser + .as_ref() + .ok_or_else(|| anyhow!("relay sender is not connected"))?; + if sender.connection_id != connection_id { + return Err(anyhow!("relay sender connection is stale")); + } + } + } + + let session_entry = sessions + .get_mut(session) + .ok_or_else(|| anyhow!("relay session is not registered"))?; + match from { + PeerRole::Agent => { + let original_id = message + .get("id") + .cloned() + .ok_or_else(|| anyhow!("relay JSON message must include request id"))?; + let relay_id = relay_agent_request_id(connection_id, &original_id)?; + message["id"] = Value::String(relay_id.clone()); + session_entry.pending_agent_requests.insert( + relay_id, + PendingAgentRequest { + connection_id, + original_id, + }, + ); + let target = session_entry + .browser + .as_ref() + .ok_or_else(|| anyhow!("relay peer is not connected"))?; + target + .tx + .send(serde_json::to_string(&message)?) + .context("failed to forward relay message") + } + PeerRole::Browser => { + let relay_id = message + .get("id") + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| anyhow!("relay browser response id was not rewritten"))?; + let Some(pending) = session_entry.pending_agent_requests.remove(&relay_id) else { + return Ok(()); + }; + message["id"] = pending.original_id; + let Some(target) = session_entry.agents.get(&pending.connection_id) else { + return Ok(()); + }; + target + .tx + .send(serde_json::to_string(&message)?) + .context("failed to forward relay message") + } + } + } +} + +impl RelayEndpoint { + fn parse(target: &str) -> Result { + let (path, query) = target.split_once('?').unwrap_or((target, "")); + let segments = path + .trim_matches('/') + .split('/') + .filter(|segment| !segment.is_empty()) + .collect::>(); + match segments.as_slice() { + ["ws", "browser", session] => Ok(Self::Browser { + session: validate_session_id(session)?, + browser_token: validate_token( + "browser token", + &query_param(query, "token") + .ok_or_else(|| anyhow!("browser token is required"))?, + )?, + agent_token: validate_token( + "agent token", + &query_param(query, "agent_token") + .ok_or_else(|| anyhow!("agent token is required"))?, + )?, + }), + ["ws", "agent", session] => Ok(Self::Agent { + session: validate_session_id(session)?, + agent_token: validate_token( + "agent token", + &query_param(query, "token") + .ok_or_else(|| anyhow!("agent token is required"))?, + )?, + }), + _ => Err(anyhow!( + "relay endpoint must be /ws/browser/ or /ws/agent/" + )), + } + } + + fn role(&self) -> PeerRole { + match self { + Self::Browser { .. } => PeerRole::Browser, + Self::Agent { .. } => PeerRole::Agent, + } + } + + fn session(&self) -> &str { + match self { + Self::Browser { session, .. } | Self::Agent { session, .. } => session, + } + } +} + +fn handle_client(state: SharedRelayState, stream: TcpStream) -> Result<()> { + stream + .set_read_timeout(Some(Duration::from_millis(100))) + .ok(); + stream.set_write_timeout(Some(Duration::from_secs(5))).ok(); + let target = Arc::new(Mutex::new(String::new())); + let callback = TargetCapture { + target: Arc::clone(&target), + }; + let mut websocket = accept_hdr_with_config(stream, callback, Some(websocket_config())) + .context("failed to accept relay websocket")?; + let target = target + .lock() + .map_err(|_| anyhow!("relay request target lock was poisoned"))? + .clone(); + let endpoint = RelayEndpoint::parse(&target)?; + let (tx, rx) = mpsc::channel(); + let (session, role, connection_id) = state.register(&endpoint, tx)?; + let result = relay_client_loop( + &state, + endpoint.session(), + endpoint.role(), + connection_id, + &mut websocket, + rx, + ); + state.unregister(&session, role, connection_id); + result +} + +struct TargetCapture { + target: Arc>, +} + +impl Callback for TargetCapture { + #[allow(clippy::result_large_err)] + fn on_request( + self, + request: &Request, + response: Response, + ) -> std::result::Result { + if let Ok(mut target) = self.target.lock() { + *target = request.uri().to_string(); + } + Ok(response) + } +} + +fn relay_client_loop( + state: &SharedRelayState, + session: &str, + role: PeerRole, + connection_id: u64, + websocket: &mut WebSocket, + rx: mpsc::Receiver, +) -> Result<()> { + loop { + drain_outbound(websocket, &rx)?; + match websocket.read() { + Ok(message) => { + if message.is_close() { + return Ok(()); + } + if message.is_ping() || message.is_pong() { + continue; + } + let text = message + .to_text() + .context("relay message was not valid utf8")?; + state.route_message(session, role, connection_id, text)?; + } + Err(WsError::Io(error)) + if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} + Err(WsError::ConnectionClosed | WsError::AlreadyClosed) => return Ok(()), + Err(error) => return Err(error).context("relay websocket read failed"), + } + } +} + +fn drain_outbound(websocket: &mut WebSocket, rx: &mpsc::Receiver) -> Result<()> { + loop { + match rx.try_recv() { + Ok(message) => websocket + .send(Message::Text(message)) + .context("failed to send relay websocket message")?, + Err(mpsc::TryRecvError::Empty) => return Ok(()), + Err(mpsc::TryRecvError::Disconnected) => return Ok(()), + } + } +} + +fn websocket_config() -> WebSocketConfig { + WebSocketConfig { + max_message_size: Some(MAX_JSON_MESSAGE_BYTES), + max_frame_size: Some(MAX_JSON_MESSAGE_BYTES), + max_write_buffer_size: MAX_JSON_MESSAGE_BYTES * 2, + ..WebSocketConfig::default() + } +} + +fn parse_share_path(path: &str) -> Result { + let segments = path + .trim_matches('/') + .split('/') + .filter(|segment| !segment.is_empty()) + .collect::>(); + match segments.as_slice() { + ["share", session] => validate_session_id(session), + _ => Err(anyhow!("share URL path must be /share/")), + } +} + +fn validate_relay_json_message(from: PeerRole, raw_message: &str) -> Result> { + if raw_message.len() > MAX_JSON_MESSAGE_BYTES { + return Err(anyhow!("relay JSON message exceeded size limit")); + } + let value: Value = serde_json::from_str(raw_message).context("relay message was not JSON")?; + let Some(id) = value.get("id") else { + if from == PeerRole::Browser { + return Ok(None); + } + return Err(anyhow!("relay JSON message must include request id")); + }; + if id.is_null() || id.is_array() || id.is_object() { + return Err(anyhow!( + "relay JSON message id must be a string, number, or boolean" + )); + } + Ok(Some(value)) +} + +fn relay_agent_request_id(connection_id: u64, original_id: &Value) -> Result { + if original_id.is_null() || original_id.is_array() || original_id.is_object() { + return Err(anyhow!( + "relay JSON message id must be a string, number, or boolean" + )); + } + let encoded_id = + serde_json::to_string(original_id).context("failed to encode relay request id")?; + Ok(format!("{connection_id}:{encoded_id}")) +} + +fn validate_session_id(value: &str) -> Result { + let value = decode_url_component(value).trim().to_string(); + if value.is_empty() { + return Err(anyhow!("session id is required")); + } + if value.len() > MAX_SESSION_ID_BYTES { + return Err(anyhow!("session id is too long")); + } + if !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + { + return Err(anyhow!("session id contains unsupported characters")); + } + Ok(value) +} + +fn validate_token(name: &str, value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + return Err(anyhow!("{name} is required")); + } + if value.len() > MAX_TOKEN_BYTES { + return Err(anyhow!("{name} is too long")); + } + if value + .chars() + .any(|ch| ch.is_control() || ch.is_whitespace()) + { + return Err(anyhow!( + "{name} contains unsupported whitespace/control characters" + )); + } + Ok(value.to_string()) +} + +fn query_param(query: &str, name: &str) -> Option { + query.split('&').find_map(|part| { + let (key, value) = part.split_once('=')?; + (decode_url_component(key) == name).then(|| decode_url_component(value)) + }) +} + +fn decode_url_component(value: &str) -> String { + let mut decoded = Vec::with_capacity(value.len()); + let bytes = value.as_bytes(); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'+' => decoded.push(b' '), + b'%' if index + 2 < bytes.len() => { + if let (Some(high), Some(low)) = + (hex_value(bytes[index + 1]), hex_value(bytes[index + 2])) + { + decoded.push(high * 16 + low); + index += 2; + } else { + decoded.push(bytes[index]); + } + } + byte => decoded.push(byte), + } + index += 1; + } + String::from_utf8_lossy(&decoded).to_string() +} + +fn hex_value(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::TcpListener; + + #[test] + fn parses_share_url_into_agent_websocket_url() { + let parsed = + parse_share_agent_url("http://relay.local/share/edge-1#agent=agent-token").unwrap(); + + assert_eq!(parsed.session, "edge-1"); + assert_eq!(parsed.agent_token, "agent-token"); + assert_eq!( + parsed.websocket_url, + "ws://relay.local/ws/agent/edge-1?token=agent-token" + ); + } + + #[test] + fn parses_https_share_url_into_wss_url() { + let ws_url = + agent_ws_url_from_share_url("https://relay.example.com/share/s_1#agent=a%2Db").unwrap(); + + assert_eq!(ws_url, "wss://relay.example.com/ws/agent/s_1?token=a-b"); + } + + #[test] + fn preserves_direct_agent_websocket_url() { + let url = agent_websocket_url_from_share_url("ws://127.0.0.1:8787/ws/agent/abc?token=tok") + .unwrap(); + + assert_eq!(url, "ws://127.0.0.1:8787/ws/agent/abc?token=tok"); + } + + #[test] + fn rejects_share_url_without_agent_fragment() { + let error = parse_share_agent_url("http://relay.local/share/edge-1").unwrap_err(); + + assert!(error.to_string().contains("#agent")); + } + + #[test] + fn parses_browser_and_agent_ws_endpoints() { + let browser = + RelayEndpoint::parse("/ws/browser/edge-1?token=browser-token&agent_token=agent-token") + .unwrap(); + let agent = RelayEndpoint::parse("/ws/agent/edge-1?token=agent-token").unwrap(); + + assert_eq!( + browser, + RelayEndpoint::Browser { + session: "edge-1".to_string(), + browser_token: "browser-token".to_string(), + agent_token: "agent-token".to_string() + } + ); + assert_eq!( + agent, + RelayEndpoint::Agent { + session: "edge-1".to_string(), + agent_token: "agent-token".to_string() + } + ); + } + + #[test] + fn rejects_messages_without_request_id() { + let error = + validate_relay_json_message(PeerRole::Agent, r#"{"method":"ping"}"#).unwrap_err(); + + assert!(error.to_string().contains("request id")); + } + + #[test] + fn ignores_browser_events_without_request_id() { + let result = validate_relay_json_message(PeerRole::Browser, r#"{"type":"hello"}"#).unwrap(); + + assert_eq!(result, None); + } + + #[test] + fn forwards_json_messages_between_browser_and_agent() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + thread::spawn(move || { + let _ = serve_listener(listener); + }); + + let browser_url = format!( + "ws://127.0.0.1:{port}/ws/browser/session-1?token=browser-token&agent_token=agent-token" + ); + let agent_url = format!("ws://127.0.0.1:{port}/ws/agent/session-1?token=agent-token"); + let (mut browser, _) = connect(browser_url).unwrap(); + let (mut agent, _) = connect(agent_url).unwrap(); + + agent + .send(Message::Text(r#"{"id":"1","method":"ping"}"#.to_string())) + .unwrap(); + let forwarded_to_browser = browser.read().unwrap().to_text().unwrap().to_string(); + let forwarded_json: Value = serde_json::from_str(&forwarded_to_browser).unwrap(); + let relay_id = forwarded_json["id"].as_str().unwrap().to_string(); + assert!(relay_id.ends_with(":\"1\"")); + assert_eq!(forwarded_json["method"], "ping"); + + browser + .send(Message::Text( + json!({ "id": relay_id, "result": "pong" }).to_string(), + )) + .unwrap(); + let forwarded_to_agent = agent.read().unwrap().to_text().unwrap().to_string(); + assert_eq!(forwarded_to_agent, r#"{"id":"1","result":"pong"}"#); + } + + #[test] + fn routes_concurrent_agent_requests_by_rewritten_id() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + thread::spawn(move || { + let _ = serve_listener(listener); + }); + + let browser_url = format!( + "ws://127.0.0.1:{port}/ws/browser/session-2?token=browser-token&agent_token=agent-token" + ); + let agent_url = format!("ws://127.0.0.1:{port}/ws/agent/session-2?token=agent-token"); + let (mut browser, _) = connect(browser_url).unwrap(); + let (mut agent_a, _) = connect(agent_url.clone()).unwrap(); + let (mut agent_b, _) = connect(agent_url).unwrap(); + + agent_a + .send(Message::Text(r#"{"id":1,"method":"first"}"#.to_string())) + .unwrap(); + agent_b + .send(Message::Text(r#"{"id":1,"method":"second"}"#.to_string())) + .unwrap(); + + let first_to_browser: Value = + serde_json::from_str(browser.read().unwrap().to_text().unwrap()).unwrap(); + let second_to_browser: Value = + serde_json::from_str(browser.read().unwrap().to_text().unwrap()).unwrap(); + let mut first_id = String::new(); + let mut second_id = String::new(); + for message in [first_to_browser, second_to_browser] { + match message["method"].as_str().unwrap() { + "first" => first_id = message["id"].as_str().unwrap().to_string(), + "second" => second_id = message["id"].as_str().unwrap().to_string(), + other => panic!("unexpected method {other}"), + } + } + assert_ne!(first_id, second_id); + + browser + .send(Message::Text( + json!({ "id": second_id, "result": "second-ok" }).to_string(), + )) + .unwrap(); + browser + .send(Message::Text( + json!({ "id": first_id, "result": "first-ok" }).to_string(), + )) + .unwrap(); + + let response_b = agent_b.read().unwrap().to_text().unwrap().to_string(); + let response_a = agent_a.read().unwrap().to_text().unwrap().to_string(); + assert_eq!(response_b, r#"{"id":1,"result":"second-ok"}"#); + assert_eq!(response_a, r#"{"id":1,"result":"first-ok"}"#); + } +} diff --git a/tests/cli_status.rs b/tests/cli_status.rs index 2cf6232..77e2267 100644 --- a/tests/cli_status.rs +++ b/tests/cli_status.rs @@ -1,6 +1,7 @@ use docker_git_browser_connection::{ compute_browser_ports, render_cdp_url_for_ports, render_novnc_url_for_ports, }; +use std::fs; use std::process::Command; #[test] @@ -43,3 +44,119 @@ fn root_help_exposes_stop_command_without_docker() { let stdout = String::from_utf8_lossy(&output.stdout); assert!(stdout.contains("stop")); } + +#[test] +fn rbc_help_exposes_browser_actions_without_mcp() { + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .args(["--help"]) + .output() + .expect("Failed to execute rbc"); + + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("snapshot")); + assert!(stdout.contains("navigate")); + assert!(stdout.contains("--share-url")); + assert!(stdout.contains("--cdp-url")); + assert!(stdout.contains("--control-url")); + assert!(stdout.contains("Browser name")); + assert!(!stdout.contains("--project")); +} + +#[test] +fn rbc_eval_requires_expression_or_file_before_network() { + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .args(["--cdp-url", "http://127.0.0.1:1", "dg-test", "eval"]) + .output() + .expect("Failed to execute rbc"); + + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("eval requires JS, --expression, or --file")); +} + +#[test] +fn rbc_supports_tools_namespace_for_project_commands() { + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .args(["dg-test", "tools", "--help"]) + .output() + .expect("Failed to execute rbc"); + + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("snapshot")); + assert!(stdout.contains("activate-tab")); +} + +#[test] +fn rbc_pw_requires_script_or_code_before_network() { + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .args(["--cdp-url", "http://127.0.0.1:1", "dg-test", "pw"]) + .output() + .expect("Failed to execute rbc"); + + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("pw requires SCRIPT or --code")); +} + +#[test] +fn rbc_pw_runs_code_with_fake_playwright_core() { + let temp = tempfile::tempdir().expect("tempdir is created"); + let module_dir = temp.path().join("node_modules/playwright-core"); + fs::create_dir_all(&module_dir).expect("fake module dir is created"); + fs::write( + module_dir.join("index.js"), + r#" +exports.chromium = { + connectOverCDP: async (url) => ({ + contexts: () => [{ + pages: () => [{ + title: async () => "Fake Title", + url: () => url + }], + newPage: async () => ({ + title: async () => "New Page", + url: () => url + }), + close: async () => {} + }], + newContext: async () => ({ + pages: () => [], + newPage: async () => ({ + title: async () => "New Context Page", + url: () => url + }), + close: async () => {} + }), + close: async () => {} + }) +}; +"#, + ) + .expect("fake playwright-core is written"); + + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .env("NODE_PATH", temp.path().join("node_modules")) + .args([ + "--cdp-url", + "http://fake-cdp:9222", + "--json", + "dg-test", + "pw", + "--code", + "return { title: await page.title(), url: page.url() };", + ]) + .output() + .expect("run rbc pw"); + + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: serde_json::Value = serde_json::from_slice(&output.stdout).expect("stdout is JSON"); + assert_eq!(value["tool"], "browser_playwright"); + assert_eq!(value["result"]["title"], "Fake Title"); + assert_eq!(value["result"]["url"], "http://fake-cdp:9222"); +} diff --git a/tests/mcp_stdio.rs b/tests/mcp_stdio.rs index 05b7174..0b8e937 100644 --- a/tests/mcp_stdio.rs +++ b/tests/mcp_stdio.rs @@ -1,7 +1,12 @@ -use std::io::Write; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; use std::process::{Command, Stdio}; +use std::thread; +use std::time::Duration; -use serde_json::Value; +use serde_json::{json, Value}; +use tungstenite::stream::MaybeTlsStream; +use tungstenite::{connect, Message, WebSocket}; fn encode_message(value: Value) -> Vec { let body = serde_json::to_vec(&value).expect("message body serializes"); @@ -49,6 +54,79 @@ fn decode_line_messages(stdout: &[u8]) -> Vec { .collect() } +fn unused_local_port() -> u16 { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind an unused local port"); + listener + .local_addr() + .expect("read local listener address") + .port() +} + +fn http_request(port: u16, request: &str) -> String { + let mut last_error = None; + for _ in 0..50 { + match TcpStream::connect(("127.0.0.1", port)) { + Ok(mut stream) => { + stream + .write_all(request.as_bytes()) + .expect("write HTTP request"); + let mut response = String::new(); + stream + .read_to_string(&mut response) + .expect("read HTTP response"); + return response; + } + Err(error) => { + last_error = Some(error); + thread::sleep(Duration::from_millis(20)); + } + } + } + panic!("control panel did not accept connections: {last_error:?}"); +} + +fn websocket_connect(url: &str) -> WebSocket> { + let mut last_error = None; + for _ in 0..50 { + match connect(url) { + Ok((socket, _response)) => return socket, + Err(error) => { + last_error = Some(error); + thread::sleep(Duration::from_millis(20)); + } + } + } + panic!("control panel websocket did not accept connections: {last_error:?}"); +} + +fn control_panel_token(port: u16) -> String { + let response = http_request( + port, + "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n", + ); + assert!(response.contains("200 OK"), "{response}"); + let marker = "const controlToken = \""; + let token = response + .split_once(marker) + .and_then(|(_, rest)| rest.split_once('"')) + .map(|(token, _)| token) + .expect("control token is embedded in panel HTML"); + token.to_string() +} + +fn initialize_request(id: u64) -> Vec { + encode_message(serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "method": "initialize", + "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": { "name": "probe", "version": "0" } + } + })) +} + #[test] fn browser_connection_help_exposes_custom_mcp_command_without_npx() { let output = Command::new(env!("CARGO_BIN_EXE_browser-connection")) @@ -60,6 +138,16 @@ fn browser_connection_help_exposes_custom_mcp_command_without_npx() { let stdout = String::from_utf8_lossy(&output.stdout); assert!(stdout.contains("browser-connection")); assert!(stdout.contains("--project")); + assert!(stdout.contains("--browser")); + assert!(stdout.contains("--browser-vnc")); + assert!(stdout.contains("--browser-novnc")); + assert!(stdout.contains("--browser-share")); + assert!(stdout.contains("--personal-browser")); + assert!(stdout.contains("--personal-vnc")); + assert!(stdout.contains("--personal-novnc")); + assert!(stdout.contains("--active-browser")); + assert!(stdout.contains("--control-port")); + assert!(stdout.contains("--no-control-panel")); assert!(stdout.contains("--no-start-browser")); assert!(!stdout.contains("playwright/mcp")); assert!(!stdout.contains("npx")); @@ -68,7 +156,12 @@ fn browser_connection_help_exposes_custom_mcp_command_without_npx() { #[test] fn browser_connection_stdio_initializes_and_lists_browser_tools_without_docker() { let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) - .args(["--project", "dg-test", "--no-start-browser"]) + .args([ + "--project", + "dg-test", + "--no-start-browser", + "--no-control-panel", + ]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -144,12 +237,268 @@ fn browser_connection_stdio_initializes_and_lists_browser_tools_without_docker() assert!(names.contains(&"browser_type")); assert!(names.contains(&"browser_press_key")); assert!(names.contains(&"browser_take_screenshot")); + assert!(names.contains(&"browser_list")); + assert!(names.contains(&"browser_select")); +} + +#[test] +fn browser_connection_stdio_selects_personal_browser_without_docker() { + let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) + .args([ + "--project", + "dg-test", + "--no-start-browser", + "--no-control-panel", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("Failed to spawn browser-connection MCP server"); + + { + let stdin = child.stdin.as_mut().expect("stdin is piped"); + let mut input = Vec::new(); + input.extend(encode_message(serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": { "name": "probe", "version": "0" } + } + }))); + input.extend(encode_message(serde_json::json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "browser_select", + "arguments": { + "name": "personal", + "cdp_endpoint": "http://127.0.0.1:9444/json/version", + "vnc_endpoint": "host.docker.internal:5900", + "novnc_url": "http://127.0.0.1:6680/vnc.html" + } + } + }))); + input.extend(encode_message(serde_json::json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "browser_list", + "arguments": {} + } + }))); + stdin + .write_all(&input) + .expect("write MCP browser selection requests"); + } + drop(child.stdin.take()); + + let output = child + .wait_with_output() + .expect("browser-connection process exits after stdin EOF"); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let responses = decode_messages(&output.stdout); + assert_eq!(responses.len(), 3); + assert_eq!(responses[1]["result"]["isError"], false); + let inventory_text = responses[2]["result"]["content"][0]["text"] + .as_str() + .expect("browser_list returns text content"); + let inventory: Value = serde_json::from_str(inventory_text).expect("browser_list text is JSON"); + + assert_eq!(inventory["active"], "personal"); + assert!(inventory["browsers"] + .as_array() + .expect("browsers array") + .iter() + .any(|browser| { + browser["name"] == "personal" + && browser["cdpEndpoint"] == "http://127.0.0.1:9444" + && browser["vncEndpoint"] == "host.docker.internal:5900" + && browser["novncUrl"] == "http://127.0.0.1:6680/vnc.html" + && browser["active"] == true + })); +} + +#[test] +fn control_panel_selection_updates_mcp_browser_list_without_restart() { + let port = unused_local_port(); + let port_arg = port.to_string(); + let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) + .args([ + "--project", + "dg-test-control-panel", + "--no-start-browser", + "--control-port", + &port_arg, + "--browser", + "personal=http://127.0.0.1:9444", + "--browser-novnc", + "personal=http://127.0.0.1:6680/vnc.html", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("Failed to spawn browser-connection MCP server"); + + { + let stdin = child.stdin.as_mut().expect("stdin is piped"); + stdin + .write_all(&encode_message(serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": { "name": "probe", "version": "0" } + } + }))) + .expect("write MCP initialize request"); + + let token = control_panel_token(port); + let response = http_request( + port, + &format!( + "POST /api/select?name=personal HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Browser-Control-Token: {token}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ), + ); + assert!(response.contains("200 OK"), "{response}"); + assert!( + response.contains("\"selected\": \"personal\""), + "{response}" + ); + + stdin + .write_all(&encode_message(serde_json::json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "browser_list", + "arguments": {} + } + }))) + .expect("write MCP browser_list request"); + } + drop(child.stdin.take()); + + let output = child + .wait_with_output() + .expect("browser-connection process exits after stdin EOF"); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let responses = decode_messages(&output.stdout); + assert_eq!(responses.len(), 2); + let inventory_text = responses[1]["result"]["content"][0]["text"] + .as_str() + .expect("browser_list returns text content"); + let inventory: Value = serde_json::from_str(inventory_text).expect("browser_list text is JSON"); + + assert_eq!(inventory["active"], "personal"); + assert_eq!( + inventory["controlPanelUrl"], + format!("http://127.0.0.1:{port}/") + ); +} + +#[test] +fn control_panel_embeds_browser_share_relay() { + let port = unused_local_port(); + let port_arg = port.to_string(); + let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) + .args([ + "--project", + "dg-test-embedded-relay", + "--no-start-browser", + "--control-port", + &port_arg, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("Failed to spawn browser-connection MCP server"); + + { + let stdin = child.stdin.as_mut().expect("stdin is piped"); + stdin + .write_all(&initialize_request(1)) + .expect("write MCP initialize request"); + + let browser_url = format!( + "ws://127.0.0.1:{port}/ws/browser/session-1?token=browser-token&agent_token=agent-token" + ); + let agent_url = format!("ws://127.0.0.1:{port}/ws/agent/session-1?token=agent-token"); + let mut browser = websocket_connect(&browser_url); + let mut agent = websocket_connect(&agent_url); + + agent + .send(Message::Text(r#"{"id":"1","method":"ping"}"#.to_string())) + .expect("send agent command"); + let forwarded_to_browser = browser + .read() + .expect("browser receives command") + .to_text() + .expect("command is text") + .to_string(); + let forwarded_json: Value = + serde_json::from_str(&forwarded_to_browser).expect("forwarded command is JSON"); + let relay_id = forwarded_json["id"] + .as_str() + .expect("relay request id is a string") + .to_string(); + assert!(relay_id.ends_with(":\"1\"")); + assert_eq!(forwarded_json["method"], "ping"); + + browser + .send(Message::Text( + json!({ "id": relay_id, "result": "pong" }).to_string(), + )) + .expect("send browser response"); + let forwarded_to_agent = agent + .read() + .expect("agent receives response") + .to_text() + .expect("response is text") + .to_string(); + assert_eq!(forwarded_to_agent, r#"{"id":"1","result":"pong"}"#); + } + drop(child.stdin.take()); + + let output = child + .wait_with_output() + .expect("browser-connection process exits after stdin EOF"); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); } #[test] fn browser_connection_stdio_accepts_claude_framed_initialize() { let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) - .args(["--project", "dg-test", "--no-start-browser"]) + .args([ + "--project", + "dg-test", + "--no-start-browser", + "--no-control-panel", + ]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -203,7 +552,12 @@ fn browser_connection_stdio_accepts_claude_framed_initialize() { #[test] fn browser_connection_stdio_accepts_codex_line_delimited_initialize() { let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) - .args(["--project", "dg-test", "--no-start-browser"]) + .args([ + "--project", + "dg-test", + "--no-start-browser", + "--no-control-panel", + ]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) diff --git a/tests/shared_browser_relay.rs b/tests/shared_browser_relay.rs new file mode 100644 index 0000000..17270fd --- /dev/null +++ b/tests/shared_browser_relay.rs @@ -0,0 +1,369 @@ +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use serde_json::{json, Value}; +use tungstenite::{connect, stream::MaybeTlsStream, Message, WebSocket}; + +fn unused_local_port() -> u16 { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind an unused local port"); + listener + .local_addr() + .expect("read local listener address") + .port() +} + +fn encode_message(value: Value) -> Vec { + let body = serde_json::to_vec(&value).expect("message body serializes"); + let mut framed = format!("Content-Length: {}\r\n\r\n", body.len()).into_bytes(); + framed.extend_from_slice(&body); + framed +} + +fn decode_messages(mut stdout: &[u8]) -> Vec { + let mut responses = Vec::new(); + + while !stdout.is_empty() { + let split = stdout + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("frame separator present"); + let (header, rest) = stdout.split_at(split); + let body_start = &rest[4..]; + let header_text = String::from_utf8(header.to_vec()).expect("header is utf8"); + let content_length = header_text + .lines() + .find_map(|line| { + line.split_once(':').and_then(|(name, value)| { + name.eq_ignore_ascii_case("Content-Length") + .then(|| value.trim().parse::().ok()) + .flatten() + }) + }) + .expect("Content-Length header present"); + let (body, remaining) = body_start.split_at(content_length); + responses.push(serde_json::from_slice(body).expect("frame body is JSON")); + stdout = remaining; + } + + responses +} + +fn retry_browser_connect(url: &str) -> WebSocket> { + let mut last_error = None; + for _ in 0..100 { + match connect(url) { + Ok((socket, _)) => return socket, + Err(error) => { + last_error = Some(error); + thread::sleep(Duration::from_millis(20)); + } + } + } + panic!("browser websocket did not connect: {last_error:?}"); +} + +fn stop_child(mut child: Child) { + let _ = child.kill(); + let _ = child.wait(); +} + +fn spawn_inventory_server(inventory: Value) -> (String, thread::JoinHandle<()>) { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind inventory server"); + let url = format!( + "http://{}", + listener.local_addr().expect("inventory server addr") + ); + let handle = thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept inventory request"); + let mut request = [0; 2048]; + let bytes = stream.read(&mut request).expect("read inventory request"); + let request = String::from_utf8_lossy(&request[..bytes]); + assert!(request.starts_with("GET /api/browsers ")); + let body = inventory.to_string(); + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + stream + .write_all(response.as_bytes()) + .expect("write inventory response"); + }); + (url, handle) +} + +#[test] +fn mcp_navigates_shared_browser_through_relay_link() { + let relay_port = unused_local_port(); + let relay_bind = format!("127.0.0.1:{relay_port}"); + let relay = Command::new(env!("CARGO_BIN_EXE_browser-connection-relay")) + .args(["--bind", &relay_bind]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn browser-connection-relay"); + + let session = "session-test"; + let agent_token = "agent-token"; + let browser_url = format!( + "ws://127.0.0.1:{relay_port}/ws/browser/{session}?token=browser-token&agent_token={agent_token}" + ); + let (ready_tx, ready_rx) = mpsc::channel(); + let browser_thread = thread::spawn(move || { + let mut socket = retry_browser_connect(&browser_url); + ready_tx.send(()).expect("signal browser websocket ready"); + loop { + let message = socket.read().expect("read relayed browser command"); + if let Message::Text(text) = message { + let request: Value = serde_json::from_str(&text).expect("request is JSON"); + assert_eq!(request["command"], "navigate"); + assert_eq!(request["params"]["url"], "https://example.com/"); + socket + .send(Message::Text( + json!({ + "id": request["id"].clone(), + "ok": true, + "result": "Navigated remote Edge" + }) + .to_string(), + )) + .expect("send relayed browser response"); + break; + } + } + }); + ready_rx + .recv_timeout(Duration::from_secs(5)) + .expect("browser websocket connects to relay"); + + let share_url = format!("http://127.0.0.1:{relay_port}/share/{session}#agent={agent_token}"); + let mut child = Command::new(env!("CARGO_BIN_EXE_browser-connection")) + .args([ + "--project", + "dg-shared-browser-test", + "--no-start-browser", + "--no-control-panel", + "--browser-share", + &format!("edge={share_url}"), + "--active-browser", + "edge", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn browser-connection MCP server"); + + { + let stdin = child.stdin.as_mut().expect("stdin is piped"); + let mut input = Vec::new(); + input.extend(encode_message(json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": { "name": "probe", "version": "0" } + } + }))); + input.extend(encode_message(json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "browser_navigate", + "arguments": { "url": "https://example.com/" } + } + }))); + stdin.write_all(&input).expect("write MCP requests"); + } + drop(child.stdin.take()); + + let output = child + .wait_with_output() + .expect("browser-connection process exits after stdin EOF"); + stop_child(relay); + browser_thread.join().expect("browser thread exits"); + + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let responses = decode_messages(&output.stdout); + assert_eq!(responses.len(), 2); + assert_eq!(responses[1]["result"]["isError"], false); + assert_eq!( + responses[1]["result"]["content"][0]["text"], + "Navigated remote Edge" + ); +} + +#[test] +fn rbc_navigates_shared_browser_through_relay_link_without_mcp() { + let relay_port = unused_local_port(); + let relay_bind = format!("127.0.0.1:{relay_port}"); + let relay = Command::new(env!("CARGO_BIN_EXE_browser-connection-relay")) + .args(["--bind", &relay_bind]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn browser-connection-relay"); + + let session = "rbc-session-test"; + let agent_token = "agent-token"; + let browser_url = format!( + "ws://127.0.0.1:{relay_port}/ws/browser/{session}?token=browser-token&agent_token={agent_token}" + ); + let (ready_tx, ready_rx) = mpsc::channel(); + let browser_thread = thread::spawn(move || { + let mut socket = retry_browser_connect(&browser_url); + ready_tx.send(()).expect("signal browser websocket ready"); + loop { + let message = socket.read().expect("read relayed browser command"); + if let Message::Text(text) = message { + let request: Value = serde_json::from_str(&text).expect("request is JSON"); + assert_eq!(request["command"], "navigate"); + assert_eq!(request["params"]["url"], "https://example.com/"); + socket + .send(Message::Text( + json!({ + "id": request["id"].clone(), + "ok": true, + "result": "Navigated remote Edge through CLI" + }) + .to_string(), + )) + .expect("send relayed browser response"); + break; + } + } + }); + ready_rx + .recv_timeout(Duration::from_secs(5)) + .expect("browser websocket connects to relay"); + + let share_url = format!("http://127.0.0.1:{relay_port}/share/{session}#agent={agent_token}"); + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .env( + "BROWSER_CONNECTION_BROWSER_SHARES", + format!("edge={share_url}"), + ) + .args(["edge", "navigate", "https://example.com/"]) + .output() + .expect("run rbc"); + + stop_child(relay); + browser_thread.join().expect("browser thread exits"); + + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&output.stdout).trim(), + "Navigated remote Edge through CLI" + ); +} + +#[test] +fn rbc_runs_playwright_crx_through_shared_browser_link() { + let relay_port = unused_local_port(); + let relay_bind = format!("127.0.0.1:{relay_port}"); + let relay = Command::new(env!("CARGO_BIN_EXE_browser-connection-relay")) + .args(["--bind", &relay_bind]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn browser-connection-relay"); + + let session = "rbc-pw-session-test"; + let agent_token = "agent-token"; + let browser_url = format!( + "ws://127.0.0.1:{relay_port}/ws/browser/{session}?token=browser-token&agent_token={agent_token}" + ); + let (ready_tx, ready_rx) = mpsc::channel(); + let browser_thread = thread::spawn(move || { + let mut socket = retry_browser_connect(&browser_url); + ready_tx.send(()).expect("signal browser websocket ready"); + let message = socket.read().expect("read relayed browser command"); + if let Message::Text(text) = message { + let request: Value = serde_json::from_str(&text).expect("request is JSON"); + assert_eq!(request["command"], "run_playwright"); + assert_eq!(request["params"]["allowClose"], false); + assert!(request["params"]["code"] + .as_str() + .expect("code param is a string") + .contains("page.goto('https://example.com/')")); + socket + .send(Message::Text( + json!({ + "id": request["id"].clone(), + "ok": true, + "result": { + "ok": true, + "mode": "playwright-crx", + "tab": { "url": "https://example.com/" } + } + }) + .to_string(), + )) + .expect("send relayed browser response"); + } + }); + ready_rx + .recv_timeout(Duration::from_secs(5)) + .expect("browser websocket connects to relay"); + + let share_url = format!("http://127.0.0.1:{relay_port}/share/{session}#agent={agent_token}"); + let (control_url, control_thread) = spawn_inventory_server(json!({ + "active": "managed", + "browsers": [ + { + "name": "managed", + "active": true, + "cdpEndpoint": "http://127.0.0.1:9223" + }, + { + "name": "edge", + "active": false, + "shareUrl": share_url + } + ] + })); + let output = Command::new(env!("CARGO_BIN_EXE_rbc")) + .env("BROWSER_CONNECTION_CONTROL_URL", &control_url) + .args([ + "--json", + "edge", + "pw", + "--code", + "await page.goto('https://example.com/'); return { title: await page.title() };", + ]) + .output() + .expect("run rbc pw"); + + stop_child(relay); + control_thread.join().expect("inventory server exits"); + browser_thread.join().expect("browser thread exits"); + + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("stdout is JSON"); + assert_eq!(value["tool"], "browser_playwright"); + assert_eq!(value["target"]["kind"], "shared-extension"); + assert_eq!(value["result"]["mode"], "playwright-crx"); + assert_eq!(value["result"]["tab"]["url"], "https://example.com/"); +}